-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
353 lines (299 loc) · 10.1 KB
/
server.js
File metadata and controls
353 lines (299 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const Room = require('./lib/Room');
const User = require('./lib/User');
const InviteURL = require('./lib/InviteURL');
const MessageHandler = require('./lib/MessageHandler');
const TorService = require('./services/torService');
const { securityMiddleware, apiLimiter, roomCreationLimiter, validateInput, checkWSRateLimit, checkWSMessageRate } = require('./middleware/security');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const PORT = process.env.PORT || 8000;
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
scriptSrcAttr: ["'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'", "data:"],
frameSrc: ["'none'"],
upgradeInsecureRequests: null
}
}
}));
// Apply security middleware
app.use(apiLimiter);
app.use(securityMiddleware);
app.use(validateInput);
// Parse JSON bodies
app.use(express.json({ limit: '10mb' }));
// Serve static files
app.use(express.static('public'));
// Global state
const rooms = new Map();
const messageHandler = new MessageHandler();
const torService = new TorService();
// WebSocket connection handling
wss.on('connection', (ws, req) => {
// Check WebSocket rate limit
if (!checkWSRateLimit(req)) {
ws.close(1008, 'Rate limit exceeded');
return;
}
const user = new User();
let currentRoom = null;
ws.on('message', async (data) => {
try {
// Check message rate limit
if (!checkWSMessageRate(user.id)) {
ws.send(JSON.stringify({
type: 'error',
message: 'Message rate limit exceeded'
}));
return;
}
const message = JSON.parse(data);
switch (message.type) {
case 'join_room':
const room = rooms.get(message.roomId);
if (room && room.canJoin(message.inviteCode)) {
// Burn the invite code after successful join
InviteURL.burn(message.inviteCode);
currentRoom = room;
room.addUser(user, ws, message.inviteCode);
// Send current user list to new joiner
const userList = Array.from(room.users.values()).map(userData => ({
userId: userData.user.id,
username: userData.user.username,
joinedAt: userData.joinedAt,
inviteCode: userData.inviteCode
}));
ws.send(JSON.stringify({
type: 'room_joined',
roomId: message.roomId,
userId: user.id,
username: user.username,
persistenceMode: room.persistenceMode,
encryptionKey: room.encryptionKey,
userList: userList
}));
} else {
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid room or invite code'
}));
}
break;
case 'join_room_admin':
const adminRoom = rooms.get(message.roomId);
if (adminRoom && adminRoom.verifyAdmin(message.adminToken)) {
currentRoom = adminRoom;
adminRoom.addUser(user, ws, null); // Admin doesn't use invite code
// Send current user list to admin
const userList = Array.from(adminRoom.users.values()).map(userData => ({
userId: userData.user.id,
username: userData.user.username,
joinedAt: userData.joinedAt,
isAdmin: userData.user.id === user.id,
inviteCode: userData.inviteCode
}));
ws.send(JSON.stringify({
type: 'room_joined',
roomId: message.roomId,
userId: user.id,
username: user.username,
persistenceMode: adminRoom.persistenceMode,
encryptionKey: adminRoom.encryptionKey,
userList: userList,
isAdmin: true
}));
} else {
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid room or admin token'
}));
}
break;
case 'send_message':
if (currentRoom && message.encrypted) {
// Only handle encrypted messages - no plaintext accepted
await messageHandler.handleMessage(currentRoom, user, null, message.encrypted);
}
break;
case 'ratchet_key_exchange':
if (currentRoom && message.publicKey && message.userId) {
// Broadcast Double Ratchet public key to other room members
currentRoom.broadcast({
type: 'ratchet_key_exchange',
publicKey: message.publicKey,
userId: message.userId,
timestamp: Date.now()
}, user.id); // Exclude the sender
}
break;
case 'leave_room':
if (currentRoom) {
currentRoom.removeUser(user);
currentRoom = null;
}
break;
}
} catch (error) {
console.error('WebSocket message processing failed');
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid message format'
}));
}
});
ws.on('close', () => {
if (currentRoom) {
currentRoom.removeUser(user);
}
});
});
// HTTP API endpoints
app.post('/api/room/create', roomCreationLimiter, async (req, res) => {
try {
const { persistenceMode = 'ephemeral', adminPassword } = req.body;
const room = new Room(persistenceMode);
const inviteUrl = new InviteURL(room.id);
rooms.set(room.id, room);
res.json({
roomId: room.id,
inviteUrl: inviteUrl.url,
inviteCode: inviteUrl.code,
adminToken: room.adminToken,
persistenceMode: room.persistenceMode
});
} catch (error) {
res.status(500).json({ error: 'Failed to create room' });
}
});
app.post('/api/room/:roomId/invite', async (req, res) => {
try {
const room = rooms.get(req.params.roomId);
if (!room || !room.verifyAdmin(req.body.adminToken)) {
return res.status(403).json({ error: 'Unauthorized' });
}
const inviteUrl = new InviteURL(room.id);
res.json({ inviteUrl: inviteUrl.url });
} catch (error) {
res.status(500).json({ error: 'Failed to create invite' });
}
});
app.delete('/api/room/:roomId/user/:userId', async (req, res) => {
try {
const room = rooms.get(req.params.roomId);
if (!room || !room.verifyAdmin(req.body.adminToken)) {
return res.status(403).json({ error: 'Unauthorized' });
}
room.kickUser(req.params.userId);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: 'Failed to kick user' });
}
});
// API endpoint to get room ID from invite code
app.get('/api/invite/:inviteCode/room', (req, res) => {
try {
const { inviteCode } = req.params;
const roomId = InviteURL.getRoomId(inviteCode);
if (!roomId || !rooms.has(roomId)) {
return res.status(404).json({ error: 'Invalid or expired invite code' });
}
// Check if invite is still valid (not expired or used)
const invite = InviteURL.inviteCodes.get(inviteCode);
if (!invite || invite.used || (Date.now() - invite.createdAt > invite.expirationMs)) {
return res.status(404).json({ error: 'Invite code has expired or been used' });
}
res.json({ roomId: roomId });
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
// Join room via invite URL
app.get('/join/:inviteCode', (req, res) => {
try {
const { inviteCode } = req.params;
const roomId = InviteURL.getRoomId(inviteCode);
if (!roomId || !rooms.has(roomId)) {
return res.status(404).send('Invalid or expired invite link');
}
// Serve the main page with invite code in URL for client-side handling
res.sendFile(path.join(__dirname, 'public', 'index.html'));
} catch (error) {
res.status(500).send('Server error');
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: Date.now() });
});
// Cleanup expired rooms every 5 minutes
setInterval(() => {
for (const [roomId, room] of rooms.entries()) {
if (room.isExpired()) {
room.cleanup();
rooms.delete(roomId);
}
}
}, 5 * 60 * 1000);
// Initialize Tor service and start server
async function startServer() {
try {
console.log('Starting Tor hidden service...');
await torService.start();
const onionAddress = await torService.getOnionAddress();
console.log(`Tor hidden service running at: ${onionAddress}`);
server.listen(PORT, '127.0.0.1', () => {
console.log(`Anonymous messaging server running on http://127.0.0.1:${PORT}`);
console.log(`Tor hidden service accessible at: ${onionAddress}`);
});
} catch (error) {
console.error('Failed to start services:', error.message);
console.log('Starting server without Tor service...');
server.listen(PORT, '127.0.0.1', () => {
console.log(`Anonymous messaging server running on http://127.0.0.1:${PORT}`);
console.log('Warning: Tor service not available');
});
}
}
startServer();
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log('Shutting down gracefully...');
// Cleanup all rooms
for (const room of rooms.values()) {
room.cleanup();
}
// Stop Tor service
await torService.stop();
server.close(() => {
process.exit(0);
});
});
process.on('SIGINT', async () => {
console.log('\nReceived SIGINT, shutting down gracefully...');
// Cleanup all rooms
for (const room of rooms.values()) {
room.cleanup();
}
// Stop Tor service
await torService.stop();
server.close(() => {
process.exit(0);
});
});
module.exports = { app, server, wss };