-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
460 lines (360 loc) · 14.7 KB
/
server.js
File metadata and controls
460 lines (360 loc) · 14.7 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import express from 'express'
import { WebSocketServer } from 'ws'
import compression from 'compression'
import dotenv from 'dotenv'
import { initValkey, saveSnapshot, getSnapshot } from './lib/valkey.js'
import { getOrCreateRoom, getRoom, deleteRoom, getRoomCount, startCleanupTimer, closeAllRooms } from './lib/rooms.js'
import { sendDiscordMessage } from './lib/discord.js'
dotenv.config()
const PORT = process.env.PORT
const VALKEY_URL = process.env.VALKEY_URL || 'redis://localhost:6379'
const DRAW_INTERNAL_KEY = process.env.DRAW_INTERNAL_KEY
const ROOM_CLEANUP_MS = parseInt(process.env.ROOM_CLEANUP_MS) || 600000
const MAX_ROOMS = parseInt(process.env.MAX_ROOMS) || 100
const SNAPSHOT_INTERVAL_MS = parseInt(process.env.SNAPSHOT_INTERVAL_MS) || 30000
const RATE_LIMIT_WINDOW_MS = parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 1000
const RATE_LIMIT_MAX_MESSAGES = parseInt(process.env.RATE_LIMIT_MAX_MESSAGES) || 100
const RATE_LIMIT_BURST_THRESHOLD = parseInt(process.env.RATE_LIMIT_BURST_THRESHOLD) || 50
class SlidingWindowRateLimiter {
constructor(windowMs, maxRequests) {
this.windowMs = windowMs
this.maxRequests = maxRequests
this.timestamps = []
}
checkAndRecord() {
const now = Date.now()
const windowStart = now - this.windowMs
this.timestamps = this.timestamps.filter(t => t > windowStart)
if (this.timestamps.length >= this.maxRequests) {
const oldestInWindow = this.timestamps[0]
return {
allowed: false,
remaining: 0,
resetIn: oldestInWindow + this.windowMs - now
}
}
this.timestamps.push(now)
return {
allowed: true,
remaining: this.maxRequests - this.timestamps.length,
resetIn: this.windowMs
}
}
getUsageLevel() {
const now = Date.now()
const windowStart = now - this.windowMs
this.timestamps = this.timestamps.filter(t => t > windowStart)
return this.timestamps.length / this.maxRequests
}
}
if (!DRAW_INTERNAL_KEY) {
console.error('ERROR: DRAW_INTERNAL_KEY is required')
process.exit(1)
}
const app = express()
app.use(compression())
app.use(express.json())
initValkey(VALKEY_URL)
app.get('/health', (req, res) => {
res.json({
status: 'ok',
rooms: getRoomCount(),
uptime: process.uptime(),
memory: process.memoryUsage()
})
})
const server = app.listen(PORT, () => {
console.log(`[DRAW:MAIN] Running on port ${PORT}`)
console.log(`[DRAW:MAIN] Protocol: ${process.env.DRAW_PROTOCOL}`)
})
const wss = new WebSocketServer({
server,
maxPayload: 10 * 1024 * 1024
})
startCleanupTimer(60000, ROOM_CLEANUP_MS)
const MAX_BROADCAST_DATA_SIZE = 10 * 1024 * 1024 // 10MB limit
function validateBroadcastData(data) {
if (typeof data !== 'string') {
return { valid: false, reason: 'Data must be a string' }
}
if (data.length > MAX_BROADCAST_DATA_SIZE) {
return { valid: false, reason: 'Data exceeds maximum size' }
}
if (data.length > 0) {
const isBase64 = /^[A-Za-z0-9+/=]+$/.test(data)
const isJson = data.startsWith('{') || data.startsWith('[')
if (!isBase64 && !isJson) {
return { valid: false, reason: 'Invalid data format' }
}
}
return { valid: true }
}
wss.on('connection', (ws, req) => {
let currentRoom = null
let isAuthenticated = false
const rateLimiter = new SlidingWindowRateLimiter(RATE_LIMIT_WINDOW_MS, RATE_LIMIT_MAX_MESSAGES)
ws.on('message', async (data) => {
try {
const message = JSON.parse(data.toString())
if (!isAuthenticated) {
if (message.type !== 'auth') {
console.log('[WS] Rejecting - type is not auth:', message.type)
ws.close(4001, 'Authentication required')
return
}
if (message.key !== DRAW_INTERNAL_KEY) {
console.log(`[WS] Rejecting - Invalid key. Received: ${message.key}, Expected: ${DRAW_INTERNAL_KEY}`)
ws.close(4003, 'Invalid key')
return
}
isAuthenticated = true
ws.send(JSON.stringify({ type: 'auth', status: 'ok' }))
return
}
const rateCheck = rateLimiter.checkAndRecord()
if (!rateCheck.allowed) {
ws.send(JSON.stringify({
type: 'error',
message: 'Rate limit exceeded',
retryAfter: rateCheck.resetIn
}))
ws.close(4029, 'Rate limit exceeded')
return
}
if (rateLimiter.getUsageLevel() > 0.8) {
console.warn(`[WS] Client ${ws.clientId || 'unknown'} at ${Math.round(rateLimiter.getUsageLevel() * 100)}% rate limit`)
}
if (message.type === 'create') {
const { roomId, clientId } = message
if (clientId) ws.clientId = clientId
if (!roomId || typeof roomId !== 'string') {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid roomId' }))
return
}
if (!/^[a-zA-Z0-9-]+$/.test(roomId)) {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid roomId format' }))
return
}
if (getRoomCount() >= MAX_ROOMS) {
ws.send(JSON.stringify({ type: 'error', message: 'Server at capacity' }))
return
}
if (getRoom(roomId)) {
ws.send(JSON.stringify({ type: 'error', message: 'Room already exists' }))
return
}
sendDiscordMessage({
title: '🏠 New Room Created',
description: `Room ID: \`${roomId}\``,
color: 3447003
})
currentRoom = getOrCreateRoom(roomId)
currentRoom.addClient(ws)
ws.send(JSON.stringify({
type: 'joined',
roomId,
clients: currentRoom.getClientCount(),
isHost: true
}))
} else if (message.type === 'join') {
const { roomId, clientId } = message
if (clientId) ws.clientId = clientId
if (!roomId || typeof roomId !== 'string') {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid roomId' }))
return
}
if (!/^[a-zA-Z0-9-]+$/.test(roomId)) {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid roomId format' }))
return
}
const existingRoom = getRoom(roomId)
if (!existingRoom) {
ws.send(JSON.stringify({ type: 'error', message: 'Room not found' }))
return
}
currentRoom = existingRoom
currentRoom.addClient(ws)
const snapshot = await getSnapshot(roomId)
if (snapshot) {
let data = snapshot
let settings = null
if (snapshot.startsWith('{')) {
try {
const parsed = JSON.parse(snapshot)
if (parsed && typeof parsed === 'object') {
if (parsed.data) data = parsed.data
if (parsed.settings) settings = parsed.settings
}
} catch (e) {
}
}
ws.send(JSON.stringify({
type: 'snapshot',
data: data,
settings: settings
}))
} else {
if (currentRoom.hostWs && currentRoom.hostWs.readyState === 1) {
currentRoom.hostWs.send(JSON.stringify({
type: 'request_snapshot',
forClient: ws.clientId || 'guest'
}))
}
}
ws.send(JSON.stringify({
type: 'joined',
roomId,
clients: currentRoom.getClientCount(),
isHost: currentRoom.isHost(ws)
}))
currentRoom.broadcast(JSON.stringify({
type: 'peer-joined',
clients: currentRoom.getClientCount()
}), ws)
} else if (message.type === 'update') {
if (currentRoom) {
if (message.clientId) {
ws.clientId = message.clientId
}
const validation = validateBroadcastData(message.data)
if (!validation.valid) {
ws.send(JSON.stringify({ type: 'error', message: validation.reason }))
return
}
currentRoom.broadcast(JSON.stringify({
type: 'update',
data: message.data
}), ws)
}
} else if (message.type === 'room_settings') {
if (currentRoom) {
currentRoom.broadcast(JSON.stringify({
type: 'room_settings',
data: message.data
}), ws)
try {
let snapshot = await getSnapshot(currentRoom.id)
let data = snapshot
let settings = message.data
if (snapshot && snapshot.startsWith('{')) {
try {
const parsed = JSON.parse(snapshot)
if (parsed && typeof parsed === 'object') {
if (parsed.data) data = parsed.data
}
} catch (e) { }
}
const payload = JSON.stringify({
data: data,
settings: settings
})
await saveSnapshot(currentRoom.id, payload)
} catch (e) {
console.error('Failed to persist room settings', e)
}
}
} else if (message.type === 'awareness') {
if (currentRoom) {
if (message.clientId) {
ws.clientId = message.clientId
}
const validation = validateBroadcastData(message.data)
if (!validation.valid) {
ws.send(JSON.stringify({ type: 'error', message: validation.reason }))
return
}
currentRoom.broadcast(JSON.stringify({
type: 'awareness',
data: message.data
}), ws)
}
} else if (message.type === 'chat') {
if (currentRoom) {
if (message.clientId) {
ws.clientId = message.clientId
}
const validation = validateBroadcastData(message.data)
if (!validation.valid) {
ws.send(JSON.stringify({ type: 'error', message: validation.reason }))
return
}
currentRoom.broadcast(JSON.stringify({
type: 'chat',
data: message.data
}), ws)
}
} else if (message.type === 'chat_delete') {
if (currentRoom) {
if (message.clientId) {
ws.clientId = message.clientId
}
const validation = validateBroadcastData(message.data)
if (!validation.valid) {
ws.send(JSON.stringify({ type: 'error', message: validation.reason }))
return
}
currentRoom.broadcast(JSON.stringify({
type: 'chat_delete',
data: message.data
}), ws)
}
} else if (message.type === 'close_room') {
if (currentRoom) {
sendDiscordMessage({
title: '🛑 Room Closed by Host',
description: `Room ID: \`${currentRoom.id}\`\nClients connected: ${currentRoom.getClientCount()}`,
color: 15548997
})
currentRoom.closeRoom()
currentRoom = null
}
} else if (message.type === 'snapshot') {
if (currentRoom && message.data) {
const payload = JSON.stringify({
data: message.data,
settings: message.settings
})
await saveSnapshot(currentRoom.id, payload)
}
}
} catch (err) {
console.error('[WS] Error:', err.message)
ws.send(JSON.stringify({ type: 'error', message: 'Internal error' }))
}
})
ws.on('close', () => {
if (currentRoom) {
currentRoom.removeClient(ws)
if (currentRoom.getClientCount() === 0) {
} else {
currentRoom.broadcast(JSON.stringify({
type: 'peer-left',
clientId: ws.clientId,
clients: currentRoom.getClientCount()
}))
}
}
})
ws.on('error', (err) => {
console.error('[WS] Connection error:', err.message)
})
})
const gracefulShutdown = (signal) => {
console.log(`[DRAW:MAIN] ${signal} received, closing...`)
sendDiscordMessage({
title: `⛔ ${signal} Received`,
description: 'Server is shutting down...',
color: 15105570
})
closeAllRooms()
setTimeout(() => {
wss.close(() => {
server.close(() => {
process.exit(0)
})
})
}, 100)
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'))
process.on('SIGINT', () => gracefulShutdown('SIGINT'))
console.log('[DRAW:MAIN] WebSocket ready')