-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
281 lines (242 loc) · 11.2 KB
/
server.ts
File metadata and controls
281 lines (242 loc) · 11.2 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
// Load environment variables from .env file
import "dotenv/config";
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { Server } from "socket.io";
import { RoomManager } from "./src/lib/services/roomManager";
import {
sanitizeUsername,
secureLogger,
validateCurrentTime,
validatePermissions,
validatePlaybackRate,
validateRoomId,
validateUserId,
validateVideoEventType,
} from "./src/lib/utils/security";
import { checkRateLimit, socketRateLimiter } from "./src/lib/middleware/rateLimiter";
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = parseInt(process.env.SERVER_PORT || "3000");
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const httpServer = createServer(async(req, res) => {
const parsedUrl = parse(req.url || "/", true);
await handle(req, res, parsedUrl);
});
// Define allowed origins based on environment
const allowedOrigins = [process.env.NEXT_PUBLIC_ORIGIN || "http://localhost:3000"];
const io = new Server(httpServer, {
cors: {
origin: (origin, callback) => {
// Allow requests with no origin (mobile apps, curl, etc.) in development
if (!origin && process.env.NODE_ENV !== "production") {
return callback(null, true);
}
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
secureLogger.error("CORS blocked origin:", origin);
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET", "POST"],
credentials: true,
},
});
const roomManager = new RoomManager();
const userRoomMap = new Map<string, { roomId: string; userId: string; username: string }>();
io.on("connection", socket => {
secureLogger.info("Client connected:", socket.id);
// Rate limiting middleware for socket events
socket.use(async(packet, next) => {
try {
const clientIp = socket.handshake.address;
await checkRateLimit(socketRateLimiter, clientIp);
next();
} catch (error) {
secureLogger.error("Rate limit exceeded for", socket.handshake.address);
socket.emit("error", "Rate limit exceeded. Please slow down.");
// Don't call next() to block the event
}
});
socket.on("join-room", async(roomId: unknown, userId: unknown, username: unknown) => {
try {
// Validate and sanitize inputs to prevent NoSQL injection and XSS
const validRoomId = validateRoomId(roomId);
const validUserId = validateUserId(userId);
const validUsername = sanitizeUsername(username);
// Check if user is already in the room to avoid duplicate joins
const existingRoom = await roomManager.getRoom(validRoomId);
if (existingRoom && existingRoom.participants.some(p => p.id === validUserId)) {
// User already in room, just send current state
socket.join(validRoomId);
userRoomMap.set(socket.id, {
roomId: validRoomId,
userId: validUserId,
username: validUsername,
});
socket.emit("room-state", existingRoom);
return;
}
const room = await roomManager.addParticipant(
validRoomId,
validUserId,
validUsername,
);
if (!room) {
socket.emit("error", "Room not found");
return;
}
// Store user-room mapping for disconnect handling
userRoomMap.set(socket.id, {
roomId: validRoomId,
userId: validUserId,
username: validUsername,
});
secureLogger.roomAction("User joined", validRoomId, validUserId);
socket.join(validRoomId);
// Send updated room state to all participants in the room
io.to(validRoomId).emit("room-state", room);
} catch (error) {
secureLogger.error("Error joining room:", error);
socket.emit("error", "Failed to join room");
}
});
socket.on("leave-room", async(roomId: unknown, userId: unknown, username: unknown) => {
try {
// Validate and sanitize inputs
const validRoomId = validateRoomId(roomId);
const validUserId = validateUserId(userId);
const _validUsername = sanitizeUsername(username);
await roomManager.removeParticipant(validRoomId, validUserId);
const updatedRoom = await roomManager.getRoom(validRoomId);
socket.leave(validRoomId);
userRoomMap.delete(socket.id);
if (updatedRoom) {
// Broadcast updated room state to remaining participants
io.to(validRoomId).emit("room-state", updatedRoom);
}
secureLogger.roomAction("User left", validRoomId, validUserId);
} catch (error) {
secureLogger.error("Error leaving room:", error);
}
});
socket.on(
"video-event",
async(
roomId: unknown,
eventType: unknown,
currentTime: unknown,
userId: unknown,
playbackRate?: unknown,
) => {
try {
// Validate and sanitize all inputs to prevent injection attacks
const validRoomId = validateRoomId(roomId);
const validEventType = validateVideoEventType(eventType);
const validCurrentTime = validateCurrentTime(currentTime);
const validUserId = validateUserId(userId);
const validPlaybackRate = validatePlaybackRate(playbackRate);
secureLogger.debug(
`[Server] Received video-event: ${validEventType} in room: ${validRoomId}, playbackRate: ${validPlaybackRate}`,
);
const room = await roomManager.getRoom(validRoomId);
if (!room) {
secureLogger.debug("[Server] Room not found");
socket.emit("error", "Room not found");
return;
}
// Check permissions - owners always have full control
const isOwner = room.ownerId === validUserId;
secureLogger.debug(`[Server] Is owner: ${isOwner}`);
if (!isOwner) {
if (
(validEventType === "play" || validEventType === "pause") &&
!room.permissions.canPlay
) {
secureLogger.debug(`User denied ${validEventType} - no permission`);
return;
}
if (validEventType === "seek" && !room.permissions.canSeek) {
secureLogger.debug("User denied seek - no permission");
return;
}
} else {
secureLogger.debug(`Owner performing ${validEventType} - always allowed`);
}
const videoState = await roomManager.updateVideoState(
validRoomId,
validEventType,
validCurrentTime,
validPlaybackRate,
);
if (videoState) {
io.to(validRoomId).emit("video-sync", videoState);
secureLogger.roomAction(
`Video ${validEventType} at ${validCurrentTime}s, rate ${validPlaybackRate}x`,
validRoomId,
validUserId,
);
}
} catch (error) {
secureLogger.error("Error handling video event:", error);
socket.emit("error", "Invalid video event parameters");
}
},
);
socket.on("permissions-update", async(roomId: unknown, permissions: unknown) => {
try {
// Validate and sanitize inputs
const validRoomId = validateRoomId(roomId);
const validPermissions = validatePermissions(permissions);
secureLogger.debug("[Server] Received permissions update for room:", validRoomId);
const updatedRoom = await roomManager.updatePermissions(
validRoomId,
validPermissions,
);
if (updatedRoom) {
secureLogger.debug("[Server] Broadcasting room-state to room");
io.to(validRoomId).emit("room-state", updatedRoom);
secureLogger.roomAction("Permissions updated", validRoomId);
} else {
secureLogger.debug("[Server] Failed to update permissions - room not found");
}
} catch (error) {
secureLogger.error("Error updating permissions:", error);
socket.emit("error", "Invalid permissions parameters");
}
});
socket.on("disconnect", async() => {
secureLogger.info("Client disconnected:", socket.id);
// Handle unexpected disconnection
const userRoom = userRoomMap.get(socket.id);
if (userRoom) {
const { roomId, userId } = userRoom;
try {
secureLogger.debug("Removing participant from room");
await roomManager.removeParticipant(roomId, userId);
const updatedRoom = await roomManager.getRoom(roomId);
if (updatedRoom) {
secureLogger.debug(
`Broadcasting updated room state with ${updatedRoom.participants.length} participants`,
);
// Broadcast updated room state to remaining participants
io.to(roomId).emit("room-state", updatedRoom);
}
userRoomMap.delete(socket.id);
secureLogger.roomAction("User disconnected", roomId, userId);
} catch (error) {
secureLogger.error("Error handling disconnect:", error);
}
}
});
});
httpServer.listen(port, () => {
secureLogger.info(
`> Server ready on ${process.env.NEXT_PUBLIC_ORIGIN || `http://${hostname}:${port}`}`,
);
});
});