-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
453 lines (380 loc) · 16.5 KB
/
server.js
File metadata and controls
453 lines (380 loc) · 16.5 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
import { createServer } from 'http'
import next from 'next'
import { Server } from 'socket.io'
import { verifyJwtToken } from './lib/auth/jwt.js'
import { wsRateLimiter } from './lib/security/rate-limiter.ts'
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
// WebSocket Service Implementation
class WebSocketService {
constructor(server) {
this.io = new Server(server, {
cors: {
origin: process.env.NEXTAUTH_URL || 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true
},
transports: ['websocket', 'polling']
})
this.userSockets = new Map()
this.conversationRooms = new Map()
this.setupEventHandlers()
}
async authenticateSocket(socket) {
try {
const token = socket.handshake.auth.token ||
(socket.handshake.headers.authorization || socket.request.headers.authorization || '').replace('Bearer ', '')
if (!token) {
console.warn('WebSocket authentication failed: No token provided')
throw new Error('No authentication token provided')
}
// Validate token format
if (typeof token !== 'string' || token.length < 10) {
console.warn('WebSocket authentication failed: Invalid token format')
throw new Error('Invalid token format')
}
// Verify the JWT token generated by our auth endpoint
const session = await verifyJwtToken(token, process.env.AUTH_SECRET)
if (!session || !session.sub) {
console.warn('WebSocket authentication failed: Invalid session')
throw new Error('Invalid authentication token')
}
// Check if this is an anonymous user
const isAnonymous = session.sub && session.sub.startsWith('anon-')
console.log(`✅ WebSocket authentication successful for ${isAnonymous ? 'anonymous' : 'authenticated'} user: ${session.email || session.sub}`)
// Store user info for later use
socket.userId = session.sub
socket.userEmail = session.email
socket.userRole = session.role || (isAnonymous ? 'anonymous' : 'subscriber')
socket.isAnonymous = isAnonymous
return session
} catch (error) {
console.error('❌ Socket authentication failed:', error.message)
// SECURITY: Don't expose detailed error messages to clients
throw new Error('Authentication failed')
}
}
setupEventHandlers() {
// SECURITY: Rate limiting middleware - prevent connection flooding
this.io.use((socket, next) => {
const identifier = socket.handshake.address ||
socket.request.connection?.remoteAddress ||
'unknown'
if (wsRateLimiter.isRateLimited(identifier)) {
console.warn(`⚠️ WebSocket rate limit exceeded for ${identifier}`)
const error = new Error('Too many connection attempts')
error.data = { code: 'RATE_LIMIT_EXCEEDED', retryAfter: 60 }
return next(error)
}
next()
})
// Authentication middleware
this.io.use(async (socket, next) => {
try {
const session = await this.authenticateSocket(socket)
socket.userId = session.sub
socket.userEmail = session.email || session.sub
socket.sessionData = session
next()
} catch (error) {
console.error('WebSocket middleware authentication failed:', error.message)
// SECURITY: Generic error message to prevent information leakage
next(new Error('Connection failed'))
}
})
this.io.on('connection', (socket) => {
try {
console.log(`User connected: ${socket.userEmail} (${socket.userId})`)
// Store user socket mapping
this.userSockets.set(socket.userId, socket)
// Join user to their personal room for direct notifications
socket.join(`user:${socket.userId}`)
// Handle conversation joining with SECURITY validation
socket.on('join_conversation', (conversationId) => {
try {
// SECURITY: Input validation and sanitization
if (!conversationId || typeof conversationId !== 'string') {
socket.emit('error', { message: 'Invalid conversation ID' })
return
}
// SECURITY: Validate conversation ID format (alphanumeric + hyphens, max 100 chars)
const sanitizedId = conversationId.trim().substring(0, 100)
if (!/^[a-zA-Z0-9_-]+$/.test(sanitizedId)) {
console.warn(`⚠️ Invalid conversation ID format attempted by ${socket.userEmail}: ${conversationId}`)
socket.emit('error', { message: 'Invalid conversation ID format' })
return
}
socket.join(`conversation:${sanitizedId}`)
// Track users in conversation room
if (!this.conversationRooms.has(sanitizedId)) {
this.conversationRooms.set(sanitizedId, new Set())
}
this.conversationRooms.get(sanitizedId).add(socket.userId)
console.log(`User ${socket.userEmail} joined conversation: ${sanitizedId}`)
socket.emit('conversation_joined', { conversationId: sanitizedId })
} catch (error) {
console.error('Error joining conversation:', error)
socket.emit('error', { message: 'Failed to join conversation' })
}
})
// Handle conversation leaving with error handling
socket.on('leave_conversation', (conversationId) => {
try {
if (!conversationId || typeof conversationId !== 'string') {
socket.emit('error', { message: 'Invalid conversation ID' })
return
}
socket.leave(`conversation:${conversationId}`)
if (this.conversationRooms.has(conversationId)) {
this.conversationRooms.get(conversationId).delete(socket.userId)
if (this.conversationRooms.get(conversationId).size === 0) {
this.conversationRooms.delete(conversationId)
}
}
console.log(`User ${socket.userEmail} left conversation: ${conversationId}`)
socket.emit('conversation_left', { conversationId })
} catch (error) {
console.error('Error leaving conversation:', error)
socket.emit('error', { message: 'Failed to leave conversation' })
}
})
// Heartbeat/Keepalive handling for modern WebSocket connection
socket.on('ping', () => {
socket.emit('pong')
})
// Notification subscription management
socket.on('subscribe', ({ topic }) => {
socket.join(topic)
console.log(`Socket ${socket.id} subscribed to ${topic}`)
// Join user-specific notification channel
if (topic === 'user:notifications' && socket.userId) {
socket.join(`user:${socket.userId}:notifications`)
}
})
socket.on('unsubscribe', ({ topic }) => {
socket.leave(topic)
console.log(`Socket ${socket.id} unsubscribed from ${topic}`)
})
// Notification operations - Replace polling with push
socket.on('notification:get_count', async () => {
try {
// This would connect to your Firebase/database to get unread count
// For now, sending mock data
const unreadCount = Math.floor(Math.random() * 10)
socket.emit('notification:unread_count', unreadCount)
} catch (error) {
console.error('Error fetching notification count:', error)
}
})
socket.on('notification:mark_read', async ({ ids }) => {
try {
// Mark notifications as read in database
console.log(`Marking notifications as read: ${ids.join(', ')}`)
// Update database here
// Emit updated count
socket.emit('notification:unread_count', 0)
} catch (error) {
console.error('Error marking notifications as read:', error)
}
})
// Handle message sending with SECURITY validation
socket.on('send_message', async (messageData) => {
try {
const { conversationId, content, type = 'text' } = messageData
// SECURITY: Validate required fields
if (!conversationId || !content) {
socket.emit('error', { message: 'Missing required message data' })
return
}
// SECURITY: Validate and sanitize conversation ID
const sanitizedConvId = conversationId.toString().trim().substring(0, 100)
if (!/^[a-zA-Z0-9_-]+$/.test(sanitizedConvId)) {
socket.emit('error', { message: 'Invalid conversation ID' })
return
}
// SECURITY: Validate message type
const allowedTypes = ['text', 'image', 'file', 'system']
const sanitizedType = allowedTypes.includes(type) ? type : 'text'
// SECURITY: Sanitize and validate content (prevent XSS)
const sanitizedContent = content.toString().substring(0, 10000) // Max 10K chars
.replace(/[<>]/g, '') // Basic XSS prevention (use DOMPurify in production)
if (sanitizedContent.length === 0) {
socket.emit('error', { message: 'Invalid message content' })
return
}
// Create message object with server-side data
const message = {
id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
conversationId: sanitizedConvId,
senderId: socket.userId,
senderName: socket.userEmail,
content: sanitizedContent,
type: sanitizedType,
timestamp: new Date(),
status: 'sent'
}
// Broadcast to all users in the conversation
this.io.to(`conversation:${sanitizedConvId}`).emit('message_received', message)
console.log(`Message sent in conversation ${sanitizedConvId} by ${socket.userEmail}`)
} catch (error) {
console.error('Error handling message:', error)
socket.emit('error', { message: 'Failed to send message' })
}
})
// Handle typing indicators
socket.on('typing_start', (conversationId) => {
socket.to(`conversation:${conversationId}`).emit('user_typing', {
userId: socket.userId,
userEmail: socket.userEmail,
isTyping: true
})
})
socket.on('typing_stop', (conversationId) => {
socket.to(`conversation:${conversationId}`).emit('user_typing', {
userId: socket.userId,
userEmail: socket.userEmail,
isTyping: false
})
})
// Handle presence updates
socket.on('update_presence', (status) => {
socket.broadcast.emit('presence_update', {
userId: socket.userId,
userEmail: socket.userEmail,
isOnline: status === 'online',
lastSeen: new Date()
})
})
// NEW: Handle token refresh without disconnection - PREVENTS SUBSCRIPTION LOOPS
socket.on('auth:refresh', async ({ token }) => {
try {
console.log(`🔄 Token refresh request from ${socket.userEmail}`)
// SECURITY: Validate token format before processing
if (!token || typeof token !== 'string' || token.length < 10) {
throw new Error('Invalid token format')
}
// Validate new token using the same verification logic
const session = await verifyJwtToken(token, process.env.AUTH_SECRET)
// SECURITY FIX: Validate token expiry
const now = Math.floor(Date.now() / 1000)
if (!session.exp || session.exp < now) {
console.warn(`⚠️ Token refresh attempted with expired token for ${socket.userEmail}`)
throw new Error('Token has expired')
}
// SECURITY FIX: Validate token not issued in the future (clock skew protection)
if (session.iat && session.iat > now + 60) { // Allow 60 seconds clock skew
console.warn(`⚠️ Token refresh attempted with future-dated token for ${socket.userEmail}`)
throw new Error('Invalid token timestamp')
}
if (session && session.sub === socket.userId) {
// Update socket auth data without disconnection
socket.sessionData = session
socket.userEmail = session.email || socket.userEmail
socket.userRole = session.role || socket.userRole
// Confirm successful refresh to client
socket.emit('auth:refreshed', {
success: true,
message: 'Token refreshed successfully',
expiresIn: session.exp - now
})
console.log(`✅ Token refreshed successfully for ${socket.userEmail}`)
} else {
// Invalid token or user mismatch
console.warn(`❌ Token refresh failed for ${socket.userEmail}: Invalid token or user mismatch`)
socket.emit('auth:refreshed', {
success: false,
error: 'Invalid token or user mismatch'
})
// Force disconnection for security
setTimeout(() => {
socket.disconnect(true)
}, 1000)
}
} catch (error) {
console.error(`❌ Token refresh error for ${socket.userEmail}:`, error.message)
socket.emit('auth:refreshed', {
success: false,
error: 'Token validation failed'
})
// Force disconnection on validation failure
setTimeout(() => {
socket.disconnect(true)
}, 1000)
}
})
// Handle disconnection
socket.on('disconnect', (reason) => {
console.log(`User disconnected: ${socket.userEmail} (${reason})`)
// Remove from user sockets mapping
this.userSockets.delete(socket.userId)
// Remove from all conversation rooms
for (const [conversationId, users] of this.conversationRooms.entries()) {
if (users.has(socket.userId)) {
users.delete(socket.userId)
if (users.size === 0) {
this.conversationRooms.delete(conversationId)
}
}
}
// Broadcast offline status
socket.broadcast.emit('presence_update', {
userId: socket.userId,
userEmail: socket.userEmail,
isOnline: false,
lastSeen: new Date()
})
})
// Send connection confirmation
socket.emit('connected', {
message: 'WebSocket connected successfully',
userId: socket.userId,
userEmail: socket.userEmail
})
} catch (error) {
console.error('Error in connection handler:', error)
socket.emit('error', { message: 'Connection handler error' })
}
})
}
// Public API methods
sendToUser(userId, event, data) {
const socket = this.userSockets.get(userId)
if (socket) {
socket.emit(event, data)
return true
}
return false
}
sendToConversation(conversationId, event, data) {
this.io.to(`conversation:${conversationId}`).emit(event, data)
}
broadcast(event, data) {
this.io.emit(event, data)
}
getActiveUsers() {
return Array.from(this.userSockets.keys())
}
getConversationUsers(conversationId) {
return Array.from(this.conversationRooms.get(conversationId) || [])
}
}
// Start the server
app.prepare().then(() => {
const server = createServer((req, res) => {
handle(req, res)
})
// Initialize WebSocket service
const wsService = new WebSocketService(server)
// Make wsService available globally for API routes if needed
global.wsService = wsService
const port = process.env.PORT || 3000
server.listen(port, (err) => {
if (err) throw err
console.log(`🚀 Server ready on http://localhost:${port}`)
console.log(`📡 WebSocket server ready`)
})
}).catch((ex) => {
console.error('Error starting server:', ex)
process.exit(1)
})