peerpigeon 0.1.0 โ 1.0.0
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 +141 -1365
- package/cli.js +1382 -0
- package/dist/peerpigeon-browser.js +12290 -0
- package/dist/peerpigeon-browser.js.map +7 -0
- package/docs/API_DOCUMENTATION.md +1945 -0
- package/docs/BOOTSTRAP_HUBS.md +319 -0
- package/docs/CLI_README.md +371 -0
- package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
- package/docs/HUB_QUICK_REF.md +107 -0
- package/docs/HUB_SCRIPTS.md +331 -0
- package/docs/HUB_SYSTEM.md +552 -0
- package/docs/MIGRATION_COMPLETE.md +93 -0
- package/docs/NETWORK_NAMESPACES.md +212 -0
- package/docs/README.md +107 -0
- package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
- package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
- package/examples/bootstrap-hub-example.js +292 -0
- package/examples/browser/README.md +278 -0
- package/examples/browser/app.js +2426 -49
- package/examples/browser/index.html +482 -543
- package/examples/browser/minimal/README.md +55 -0
- package/examples/browser/minimal/index.html +75 -0
- package/examples/browser/minimal/minimal.js +234 -0
- package/examples/browser/styles.css +687 -1425
- package/examples/browser/test-bundle.html +35 -0
- package/examples/browser-2/index.html +30 -0
- package/examples/browser-2/package.json +21 -0
- package/examples/browser-2/src/App-simple.vue +21 -0
- package/examples/browser-2/src/App.vue +420 -0
- package/examples/browser-2/src/components/CryptoView.vue +1661 -0
- package/examples/browser-2/src/components/DHTView.vue +1281 -0
- package/examples/browser-2/src/components/DebugView.vue +1773 -0
- package/examples/browser-2/src/components/MediaView.vue +1048 -0
- package/examples/browser-2/src/components/MessagingView.vue +775 -0
- package/examples/browser-2/src/components/NetworkView.vue +930 -0
- package/examples/browser-2/src/components/StorageView.vue +1376 -0
- package/examples/browser-2/src/main.js +5 -0
- package/examples/browser-2/src/stores/peerpigeon.js +895 -0
- package/examples/browser-2/vite.config.js +6 -0
- package/examples/hub-example.js +186 -0
- package/examples/multi-hub-test.js +186 -0
- package/examples/node/README.md +2 -2
- package/examples/node/storage-test.js +141 -6
- package/examples/selective-streaming-demo.html +698 -0
- package/examples/standard-events-demo.js +126 -0
- package/package.json +33 -16
- package/server/index.js +1032 -98
- package/server/start.js +49 -0
- package/src/ConnectionManager.js +239 -225
- package/src/CryptoManager.js +147 -18
- package/src/DebugLogger.js +0 -7
- package/src/DistributedStorageManager.js +245 -205
- package/src/EnvironmentDetector.js +109 -2
- package/src/EventEmitter.js +79 -1
- package/src/EvictionManager.js +10 -9
- package/src/GossipManager.js +163 -11
- package/src/LexicalStorageInterface.js +332 -0
- package/src/PeerConnection.js +333 -310
- package/src/PeerPigeonMesh.js +577 -135
- package/src/SignalingClient.js +14 -243
- package/src/SignalingHandler.js +31 -10
- package/src/StorageManager.js +0 -39
- package/src/WebDHT-Simple.js +389 -0
- package/src/WebDHT.js +363 -1165
- package/src/browser-entry.js +40 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/crypto-test.html +0 -427
- package/examples/browser/ui-old.js +0 -1926
- package/examples/browser/ui.js +0 -3010
- package/websocket-server/README.md +0 -247
- package/websocket-server/server.js +0 -391
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
# PeerPigeon WebSocket Server
|
|
2
|
-
|
|
3
|
-
A local WebSocket server for PeerPigeon development and testing.
|
|
4
|
-
|
|
5
|
-
## Features
|
|
6
|
-
|
|
7
|
-
- WebSocket-based peer signaling
|
|
8
|
-
- XOR distance-based peer discovery
|
|
9
|
-
- WebRTC signaling message routing
|
|
10
|
-
- In-memory peer storage
|
|
11
|
-
- Real-time peer announcements
|
|
12
|
-
- Graceful connection handling
|
|
13
|
-
|
|
14
|
-
## Quick Start
|
|
15
|
-
|
|
16
|
-
### Option 1: Using npm package (Recommended)
|
|
17
|
-
|
|
18
|
-
```bash
|
|
19
|
-
# Install PeerPigeon
|
|
20
|
-
npm install peerpigeon
|
|
21
|
-
|
|
22
|
-
# Start the server using npm scripts
|
|
23
|
-
npm start
|
|
24
|
-
|
|
25
|
-
# Or with custom configuration
|
|
26
|
-
PORT=8080 HOST=0.0.0.0 npm start
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
### Option 2: From source
|
|
30
|
-
|
|
31
|
-
```bash
|
|
32
|
-
# Clone the repository
|
|
33
|
-
git clone https://github.com/draeder/peerpigeon.git
|
|
34
|
-
cd peerpigeon
|
|
35
|
-
|
|
36
|
-
# Start the server directly
|
|
37
|
-
npm start
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
### Option 3: Programmatic usage (Recommended for applications)
|
|
41
|
-
|
|
42
|
-
```javascript
|
|
43
|
-
import { PeerPigeonServer } from 'peerpigeon';
|
|
44
|
-
|
|
45
|
-
// Create and configure server
|
|
46
|
-
const server = new PeerPigeonServer({
|
|
47
|
-
port: 3000,
|
|
48
|
-
maxConnections: 500
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
// Start server
|
|
52
|
-
await server.start();
|
|
53
|
-
|
|
54
|
-
// Listen for events
|
|
55
|
-
server.on('peerConnected', ({ peerId, totalConnections }) => {
|
|
56
|
-
console.log(`New peer connected: ${peerId}`);
|
|
57
|
-
});
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
The server will start on `ws://localhost:3000` by default.
|
|
61
|
-
|
|
62
|
-
### 3. Connect from Browser
|
|
63
|
-
|
|
64
|
-
Update your browser application to connect to the local server:
|
|
65
|
-
|
|
66
|
-
```javascript
|
|
67
|
-
const mesh = new PeerPigeonMesh();
|
|
68
|
-
await mesh.connect('ws://localhost:3000');
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
## Configuration
|
|
72
|
-
|
|
73
|
-
### Environment Variables
|
|
74
|
-
|
|
75
|
-
- `PORT`: Server port (default: 3000)
|
|
76
|
-
- `HOST`: Server host (default: localhost)
|
|
77
|
-
|
|
78
|
-
### Example Usage
|
|
79
|
-
|
|
80
|
-
```bash
|
|
81
|
-
# Start on custom port
|
|
82
|
-
PORT=8080 npm start
|
|
83
|
-
|
|
84
|
-
# Start on all interfaces
|
|
85
|
-
HOST=0.0.0.0 npm start
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
## API
|
|
89
|
-
|
|
90
|
-
### Connection
|
|
91
|
-
|
|
92
|
-
Connect with a valid 40-character hex peer ID:
|
|
93
|
-
|
|
94
|
-
```
|
|
95
|
-
ws://localhost:3000?peerId=abc123def456...
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
### Message Types
|
|
99
|
-
|
|
100
|
-
#### Peer Announcement
|
|
101
|
-
```json
|
|
102
|
-
{
|
|
103
|
-
"type": "announce",
|
|
104
|
-
"data": { "peerId": "abc123..." }
|
|
105
|
-
}
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
#### WebRTC Signaling
|
|
109
|
-
```json
|
|
110
|
-
{
|
|
111
|
-
"type": "offer",
|
|
112
|
-
"data": { "sdp": "..." },
|
|
113
|
-
"targetPeerId": "def456..."
|
|
114
|
-
}
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
#### Keep-Alive
|
|
118
|
-
```json
|
|
119
|
-
{
|
|
120
|
-
"type": "ping",
|
|
121
|
-
"data": { "timestamp": 1234567890 }
|
|
122
|
-
}
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
### Response Messages
|
|
126
|
-
|
|
127
|
-
#### Connection Confirmation
|
|
128
|
-
```json
|
|
129
|
-
{
|
|
130
|
-
"type": "connected",
|
|
131
|
-
"peerId": "abc123...",
|
|
132
|
-
"timestamp": 1234567890
|
|
133
|
-
}
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
#### Peer Discovery
|
|
137
|
-
```json
|
|
138
|
-
{
|
|
139
|
-
"type": "peer-discovered",
|
|
140
|
-
"data": { "peerId": "def456..." },
|
|
141
|
-
"fromPeerId": "system",
|
|
142
|
-
"targetPeerId": "abc123...",
|
|
143
|
-
"timestamp": 1234567890
|
|
144
|
-
}
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
#### Pong Response
|
|
148
|
-
```json
|
|
149
|
-
{
|
|
150
|
-
"type": "pong",
|
|
151
|
-
"timestamp": 1234567890,
|
|
152
|
-
"originalTimestamp": 1234567885
|
|
153
|
-
}
|
|
154
|
-
```
|
|
155
|
-
|
|
156
|
-
## Testing
|
|
157
|
-
|
|
158
|
-
### Manual Testing
|
|
159
|
-
|
|
160
|
-
You can test the server using a WebSocket client:
|
|
161
|
-
|
|
162
|
-
```javascript
|
|
163
|
-
const ws = new WebSocket('ws://localhost:3000?peerId=1234567890abcdef1234567890abcdef12345678');
|
|
164
|
-
|
|
165
|
-
ws.onopen = () => {
|
|
166
|
-
console.log('Connected');
|
|
167
|
-
|
|
168
|
-
// Send announcement
|
|
169
|
-
ws.send(JSON.stringify({
|
|
170
|
-
type: 'announce',
|
|
171
|
-
data: { peerId: '1234567890abcdef1234567890abcdef12345678' }
|
|
172
|
-
}));
|
|
173
|
-
};
|
|
174
|
-
|
|
175
|
-
ws.onmessage = (event) => {
|
|
176
|
-
console.log('Received:', JSON.parse(event.data));
|
|
177
|
-
};
|
|
178
|
-
```
|
|
179
|
-
|
|
180
|
-
### Browser Testing
|
|
181
|
-
|
|
182
|
-
1. Open `examples/browser/index.html` in multiple browser tabs
|
|
183
|
-
2. Update the WebSocket URL to `ws://localhost:3000`
|
|
184
|
-
3. Click "Connect" in each tab
|
|
185
|
-
4. Watch peers discover each other
|
|
186
|
-
|
|
187
|
-
## Development
|
|
188
|
-
|
|
189
|
-
### Watch Mode
|
|
190
|
-
|
|
191
|
-
For development with automatic restarts:
|
|
192
|
-
|
|
193
|
-
```bash
|
|
194
|
-
npm run dev
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
### Logging
|
|
198
|
-
|
|
199
|
-
The server provides detailed logging:
|
|
200
|
-
|
|
201
|
-
- โ
Peer connections
|
|
202
|
-
- ๐จ Message routing
|
|
203
|
-
- ๐ข Peer announcements
|
|
204
|
-
- ๐ Disconnections
|
|
205
|
-
- โ Errors
|
|
206
|
-
|
|
207
|
-
## Architecture
|
|
208
|
-
|
|
209
|
-
```
|
|
210
|
-
Browser Client 1 Browser Client 2 Browser Client N
|
|
211
|
-
| | |
|
|
212
|
-
v v v
|
|
213
|
-
WebSocket WebSocket WebSocket
|
|
214
|
-
| | |
|
|
215
|
-
+-------------------+-------------------+
|
|
216
|
-
|
|
|
217
|
-
Local WebSocket Server
|
|
218
|
-
|
|
|
219
|
-
In-Memory Storage
|
|
220
|
-
(peers, connections)
|
|
221
|
-
```
|
|
222
|
-
|
|
223
|
-
## Troubleshooting
|
|
224
|
-
|
|
225
|
-
### Common Issues
|
|
226
|
-
|
|
227
|
-
1. **Connection Refused**: Check if server is running on correct port
|
|
228
|
-
2. **Invalid Peer ID**: Ensure peer ID is 40-character hex string
|
|
229
|
-
3. **Message Not Delivered**: Check if target peer is connected
|
|
230
|
-
4. **Server Won't Start**: Check if port is already in use
|
|
231
|
-
|
|
232
|
-
### Debug Commands
|
|
233
|
-
|
|
234
|
-
```bash
|
|
235
|
-
# Check if port is in use
|
|
236
|
-
lsof -i :3000
|
|
237
|
-
|
|
238
|
-
# Kill process on port
|
|
239
|
-
kill -9 $(lsof -t -i:3000)
|
|
240
|
-
|
|
241
|
-
# Check server logs
|
|
242
|
-
npm start | grep "ERROR"
|
|
243
|
-
```
|
|
244
|
-
|
|
245
|
-
## License
|
|
246
|
-
|
|
247
|
-
MIT - Same as PeerPigeon main project
|
|
@@ -1,391 +0,0 @@
|
|
|
1
|
-
import { WebSocketServer, WebSocket } from 'ws';
|
|
2
|
-
import { createServer } from 'http';
|
|
3
|
-
import { URL } from 'url';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Local WebSocket Server for PeerPigeon Development
|
|
7
|
-
*
|
|
8
|
-
* This server provides WebSocket signaling functionality
|
|
9
|
-
* for local development and testing of the PeerPigeon mesh network.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
const PORT = process.env.PORT || 3000;
|
|
13
|
-
const HOST = process.env.HOST || 'localhost';
|
|
14
|
-
|
|
15
|
-
// In-memory storage for connections and peer data
|
|
16
|
-
const connections = new Map(); // peerId -> WebSocket connection
|
|
17
|
-
const peerData = new Map(); // peerId -> { peerId, timestamp, data }
|
|
18
|
-
|
|
19
|
-
// Utility functions
|
|
20
|
-
function validatePeerId(peerId) {
|
|
21
|
-
return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
|
|
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;
|
|
37
|
-
}
|
|
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);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function getActivePeers(excludePeerId = null) {
|
|
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
|
-
}
|
|
59
|
-
}
|
|
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;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function isConnectionAlive(connection) {
|
|
73
|
-
if (!connection || connection.readyState !== WebSocket.OPEN) {
|
|
74
|
-
return false;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Simple alive check - if connection is open, it's considered alive
|
|
78
|
-
// Detailed health monitoring is handled by the peer mesh itself
|
|
79
|
-
return true;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function sendToConnection(peerId, data) {
|
|
83
|
-
const connection = connections.get(peerId);
|
|
84
|
-
if (connection && connection.readyState === WebSocket.OPEN) {
|
|
85
|
-
try {
|
|
86
|
-
connection.send(JSON.stringify(data));
|
|
87
|
-
return true;
|
|
88
|
-
} catch (error) {
|
|
89
|
-
console.error(`Error sending to ${peerId}:`, error);
|
|
90
|
-
// Clean up failed connection
|
|
91
|
-
cleanupPeer(peerId);
|
|
92
|
-
return false;
|
|
93
|
-
}
|
|
94
|
-
} else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
|
|
95
|
-
// Clean up closed connection
|
|
96
|
-
cleanupPeer(peerId);
|
|
97
|
-
}
|
|
98
|
-
return false;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
function cleanupPeer(peerId) {
|
|
102
|
-
const wasConnected = connections.has(peerId);
|
|
103
|
-
connections.delete(peerId);
|
|
104
|
-
peerData.delete(peerId);
|
|
105
|
-
|
|
106
|
-
if (wasConnected) {
|
|
107
|
-
console.log(`๐งน Cleaned up peer: ${peerId.substring(0, 8)}...`);
|
|
108
|
-
|
|
109
|
-
// Notify other peers about disconnection
|
|
110
|
-
const activePeers = getActivePeers();
|
|
111
|
-
activePeers.forEach(otherPeerId => {
|
|
112
|
-
sendToConnection(otherPeerId, {
|
|
113
|
-
type: 'peer-disconnected',
|
|
114
|
-
data: { peerId },
|
|
115
|
-
fromPeerId: 'system',
|
|
116
|
-
targetPeerId: otherPeerId,
|
|
117
|
-
timestamp: Date.now()
|
|
118
|
-
});
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
|
|
124
|
-
const activePeers = getActivePeers(fromPeerId);
|
|
125
|
-
const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
|
|
126
|
-
|
|
127
|
-
console.log(`Broadcasting from ${fromPeerId} to ${closestPeers.length} closest peers`);
|
|
128
|
-
|
|
129
|
-
closestPeers.forEach(peerId => {
|
|
130
|
-
sendToConnection(peerId, message);
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function sendToSpecificPeer(targetPeerId, message) {
|
|
135
|
-
return sendToConnection(targetPeerId, message);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// Create HTTP server
|
|
139
|
-
const server = createServer();
|
|
140
|
-
|
|
141
|
-
// Create WebSocket server
|
|
142
|
-
const wss = new WebSocketServer({ server });
|
|
143
|
-
|
|
144
|
-
console.log('๐ Starting PeerPigeon WebSocket server...');
|
|
145
|
-
|
|
146
|
-
// Periodic cleanup of stale connections
|
|
147
|
-
setInterval(() => {
|
|
148
|
-
const totalConnections = connections.size;
|
|
149
|
-
getActivePeers(); // This will clean up stale connections
|
|
150
|
-
const cleanedUp = totalConnections - connections.size;
|
|
151
|
-
|
|
152
|
-
if (cleanedUp > 0) {
|
|
153
|
-
console.log(`๐งน Periodic cleanup: removed ${cleanedUp} stale connections, ${connections.size} active`);
|
|
154
|
-
}
|
|
155
|
-
}, 30000); // Clean up every 30 seconds
|
|
156
|
-
|
|
157
|
-
// Note: Signaling servers should NOT initiate pings to peers
|
|
158
|
-
// Health monitoring is the responsibility of the peer mesh network itself
|
|
159
|
-
|
|
160
|
-
wss.on('connection', (ws, req) => {
|
|
161
|
-
let peerId = null;
|
|
162
|
-
|
|
163
|
-
// Extract peerId from query parameters
|
|
164
|
-
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
165
|
-
const queryPeerId = url.searchParams.get('peerId');
|
|
166
|
-
|
|
167
|
-
if (!queryPeerId || !validatePeerId(queryPeerId)) {
|
|
168
|
-
console.log(`โ Invalid peerId: ${queryPeerId}`);
|
|
169
|
-
ws.close(1008, 'Invalid peerId');
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
peerId = queryPeerId;
|
|
174
|
-
|
|
175
|
-
// Check if peerId is already connected
|
|
176
|
-
if (connections.has(peerId)) {
|
|
177
|
-
const existingConnection = connections.get(peerId);
|
|
178
|
-
if (existingConnection.readyState === WebSocket.OPEN) {
|
|
179
|
-
console.log(`โ ๏ธ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
|
|
180
|
-
ws.close(1008, 'Peer already connected');
|
|
181
|
-
return;
|
|
182
|
-
} else {
|
|
183
|
-
// Clean up stale connection
|
|
184
|
-
console.log(`๐ Replacing stale connection for ${peerId.substring(0, 8)}...`);
|
|
185
|
-
cleanupPeer(peerId);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// Store connection
|
|
190
|
-
connections.set(peerId, ws);
|
|
191
|
-
peerData.set(peerId, {
|
|
192
|
-
peerId,
|
|
193
|
-
timestamp: Date.now(),
|
|
194
|
-
connected: true
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
// Set up connection metadata
|
|
198
|
-
ws.connectedAt = Date.now();
|
|
199
|
-
|
|
200
|
-
console.log(`โ
Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
|
|
201
|
-
|
|
202
|
-
// Send connection confirmation
|
|
203
|
-
ws.send(JSON.stringify({
|
|
204
|
-
type: 'connected',
|
|
205
|
-
peerId,
|
|
206
|
-
timestamp: Date.now()
|
|
207
|
-
}));
|
|
208
|
-
|
|
209
|
-
// Handle incoming messages
|
|
210
|
-
ws.on('message', (data) => {
|
|
211
|
-
try {
|
|
212
|
-
const message = JSON.parse(data);
|
|
213
|
-
const { type, data: messageData, targetPeerId } = message;
|
|
214
|
-
|
|
215
|
-
console.log(`๐จ Received ${type} from ${peerId.substring(0, 8)}...`);
|
|
216
|
-
|
|
217
|
-
const responseMessage = {
|
|
218
|
-
type,
|
|
219
|
-
data: messageData,
|
|
220
|
-
fromPeerId: peerId,
|
|
221
|
-
targetPeerId,
|
|
222
|
-
timestamp: Date.now()
|
|
223
|
-
};
|
|
224
|
-
|
|
225
|
-
// Handle different message types - SIGNALING ONLY
|
|
226
|
-
switch (type) {
|
|
227
|
-
case 'announce': {
|
|
228
|
-
// Handle peer announcement
|
|
229
|
-
peerData.set(peerId, {
|
|
230
|
-
peerId,
|
|
231
|
-
timestamp: Date.now(),
|
|
232
|
-
data: messageData,
|
|
233
|
-
connected: true
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
// Get active peers with immediate validation
|
|
237
|
-
const activePeers = getActivePeers(peerId);
|
|
238
|
-
|
|
239
|
-
// Double-check each active peer with a quick ping test
|
|
240
|
-
const validatedPeers = [];
|
|
241
|
-
for (const otherPeerId of activePeers) {
|
|
242
|
-
const connection = connections.get(otherPeerId);
|
|
243
|
-
if (connection && isConnectionAlive(connection)) {
|
|
244
|
-
validatedPeers.push(otherPeerId);
|
|
245
|
-
} else {
|
|
246
|
-
console.log(`๐งน Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
|
|
247
|
-
cleanupPeer(otherPeerId);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
console.log(`๐ข Announcing ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers`);
|
|
252
|
-
|
|
253
|
-
// Send peer-discovered messages to validated peers only
|
|
254
|
-
validatedPeers.forEach(otherPeerId => {
|
|
255
|
-
sendToConnection(otherPeerId, {
|
|
256
|
-
type: 'peer-discovered',
|
|
257
|
-
data: { peerId, ...messageData },
|
|
258
|
-
fromPeerId: 'system',
|
|
259
|
-
targetPeerId: otherPeerId,
|
|
260
|
-
timestamp: Date.now()
|
|
261
|
-
});
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
// Send existing validated peers to the new peer
|
|
265
|
-
validatedPeers.forEach(existingPeerId => {
|
|
266
|
-
const existingPeerData = peerData.get(existingPeerId);
|
|
267
|
-
ws.send(JSON.stringify({
|
|
268
|
-
type: 'peer-discovered',
|
|
269
|
-
data: { peerId: existingPeerId, ...existingPeerData?.data },
|
|
270
|
-
fromPeerId: 'system',
|
|
271
|
-
targetPeerId: peerId,
|
|
272
|
-
timestamp: Date.now()
|
|
273
|
-
}));
|
|
274
|
-
});
|
|
275
|
-
break;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
case 'goodbye': {
|
|
279
|
-
// Handle peer disconnect
|
|
280
|
-
peerData.delete(peerId);
|
|
281
|
-
broadcastToClosestPeers(peerId, responseMessage);
|
|
282
|
-
break;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
case 'offer':
|
|
286
|
-
case 'answer':
|
|
287
|
-
case 'ice-candidate': {
|
|
288
|
-
// CRITICAL DEBUG: Log answer routing details
|
|
289
|
-
if (type === 'answer') {
|
|
290
|
-
console.log('๐ WEBSOCKET DEBUG: Received answer message:', {
|
|
291
|
-
type,
|
|
292
|
-
fromPeerId: peerId?.substring(0, 8) + '...',
|
|
293
|
-
targetPeerId: targetPeerId?.substring(0, 8) + '...',
|
|
294
|
-
hasTargetPeerId: !!targetPeerId,
|
|
295
|
-
hasData: !!messageData
|
|
296
|
-
});
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// Handle WebRTC signaling - this is the server's primary purpose
|
|
300
|
-
if (targetPeerId) {
|
|
301
|
-
const success = sendToSpecificPeer(targetPeerId, responseMessage);
|
|
302
|
-
if (!success) {
|
|
303
|
-
console.log(`โ ๏ธ Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
|
|
304
|
-
} else if (type === 'answer') {
|
|
305
|
-
console.log(`โ
WEBSOCKET DEBUG: Answer successfully routed to ${targetPeerId.substring(0, 8)}...`);
|
|
306
|
-
}
|
|
307
|
-
} else {
|
|
308
|
-
console.log(`โ ๏ธ ${type} message missing targetPeerId`);
|
|
309
|
-
}
|
|
310
|
-
break;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
default:
|
|
314
|
-
// Signaling server should NOT route regular peer messages
|
|
315
|
-
// Peers handle their own message routing through WebRTC data channels
|
|
316
|
-
console.log(`โ ๏ธ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
|
|
317
|
-
ws.send(JSON.stringify({
|
|
318
|
-
type: 'error',
|
|
319
|
-
error: `Signaling server does not route '${type}' messages. Use WebRTC data channels for peer-to-peer communication.`,
|
|
320
|
-
timestamp: Date.now()
|
|
321
|
-
}));
|
|
322
|
-
break;
|
|
323
|
-
}
|
|
324
|
-
} catch (error) {
|
|
325
|
-
console.error(`โ Error handling message from ${peerId?.substring(0, 8)}...:`, error);
|
|
326
|
-
ws.send(JSON.stringify({
|
|
327
|
-
type: 'error',
|
|
328
|
-
error: 'Invalid message format',
|
|
329
|
-
timestamp: Date.now()
|
|
330
|
-
}));
|
|
331
|
-
}
|
|
332
|
-
});
|
|
333
|
-
|
|
334
|
-
// Handle connection close
|
|
335
|
-
ws.on('close', (code, reason) => {
|
|
336
|
-
console.log(`๐ Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
|
|
337
|
-
|
|
338
|
-
if (peerId) {
|
|
339
|
-
cleanupPeer(peerId);
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
console.log(`๐ Active connections: ${connections.size}`);
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
// Handle connection errors
|
|
346
|
-
ws.on('error', (error) => {
|
|
347
|
-
console.error(`โ WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
|
|
348
|
-
|
|
349
|
-
// Clean up errored connection
|
|
350
|
-
if (peerId && (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING)) {
|
|
351
|
-
cleanupPeer(peerId);
|
|
352
|
-
}
|
|
353
|
-
});
|
|
354
|
-
});
|
|
355
|
-
|
|
356
|
-
// Start server
|
|
357
|
-
server.listen(PORT, HOST, () => {
|
|
358
|
-
console.log(`๐ PeerPigeon WebSocket server running on ws://${HOST}:${PORT}`);
|
|
359
|
-
console.log('๐ Usage: Connect with ?peerId=<40-char-hex-id>');
|
|
360
|
-
console.log('๐ Ready to handle peer connections...');
|
|
361
|
-
});
|
|
362
|
-
|
|
363
|
-
// Handle graceful shutdown
|
|
364
|
-
process.on('SIGINT', () => {
|
|
365
|
-
console.log('\n๐ Shutting down WebSocket server...');
|
|
366
|
-
|
|
367
|
-
// Close all connections
|
|
368
|
-
for (const [, connection] of connections) {
|
|
369
|
-
connection.close(1001, 'Server shutting down');
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// Close server
|
|
373
|
-
server.close(() => {
|
|
374
|
-
console.log('โ
WebSocket server closed');
|
|
375
|
-
process.exit(0);
|
|
376
|
-
});
|
|
377
|
-
});
|
|
378
|
-
|
|
379
|
-
// Error handling
|
|
380
|
-
process.on('uncaughtException', (error) => {
|
|
381
|
-
console.error('โ Uncaught Exception:', error);
|
|
382
|
-
process.exit(1);
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
process.on('unhandledRejection', (reason, promise) => {
|
|
386
|
-
console.error('โ Unhandled Rejection at:', promise, 'reason:', reason);
|
|
387
|
-
process.exit(1);
|
|
388
|
-
});
|
|
389
|
-
|
|
390
|
-
// Export for programmatic use
|
|
391
|
-
export { server, wss, connections, peerData };
|