-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
376 lines (328 loc) · 11.6 KB
/
server.ts
File metadata and controls
376 lines (328 loc) · 11.6 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
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { loadEnvConfig } from "@next/env";
loadEnvConfig(process.cwd());
import { Server } from "socket.io";
import mongoose from "mongoose";
import RoomModel from "./models/room";
import MessageModel from "./models/message";
import {
verifyPassword,
encryptMessage,
decryptMessage,
} from "./lib/encryption";
import { rateLimiter } from "./lib/rate-limiter";
import { setSocketIO } from "./lib/socket-instance";
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = parseInt(process.env.PORT || "3000", 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
// MongoDB Connection
if (process.env.MONGODB_URI) {
mongoose
.connect(process.env.MONGODB_URI)
.catch((err) => console.error("MongoDB connection error:", err));
} else {
console.error("MONGODB_URI is not defined");
}
app.prepare().then(() => {
const httpServer = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url!, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error occurred handling", req.url, err);
res.statusCode = 500;
res.end("internal server error");
}
});
const io = new Server(httpServer, {
path: "/api/socket",
addTrailingSlash: false,
cors: {
origin: process.env.NEXT_PUBLIC_APP_URL || `http://localhost:${port}`,
methods: ["GET", "POST"],
credentials: true,
},
transports: ["websocket", "polling"],
allowEIO3: true,
pingTimeout: 60000,
pingInterval: 25000,
});
// Store io instance globally for API routes
// @ts-ignore
global.io = io;
io.on("connection", (socket) => {
// Join room
socket.on("room:join", async ({ roomId, userId, username, password }) => {
try {
// Rate limiting: 20 join attempts per minute per socket
if (rateLimiter.isRateLimited(`join:${socket.id}`, 20, 60000)) {
socket.emit("error", {
message: "Too many join attempts. Please wait a moment.",
});
return;
}
const room = await RoomModel.findOne({ roomId, isActive: true });
if (!room) {
socket.emit("room:deleted", {
message: "Room not found or has been deleted.",
});
return;
}
if (room.isPrivate && password) {
const isValid = await verifyPassword(
password as string,
room.passwordHash || ""
);
if (!isValid) {
socket.emit("error", { message: "Incorrect password" });
return;
}
}
socket.join(roomId);
socket.data = { userId, username, roomId };
if (!room.participants.includes(userId)) {
await RoomModel.updateOne(
{ roomId },
{
$addToSet: { participants: userId },
lastActivity: new Date(),
}
);
}
const systemMessage = await MessageModel.create({
roomId,
userId: "system",
username: "System",
message: `${username} joined the room`,
type: "system",
timestamp: new Date(),
});
io.to(roomId).emit("user:joined", { userId, username });
io.to(roomId).emit("message:new", systemMessage.toObject());
const updatedRoom = await RoomModel.findOne({ roomId });
if (updatedRoom) {
io.to(roomId).emit("participants:update", updatedRoom.participants);
}
} catch (error) {
console.error("Error joining room:", error);
socket.emit("error", { message: "Failed to join room" });
}
});
// Leave room
socket.on("room:leave", async ({ roomId, userId }) => {
try {
socket.leave(roomId);
const room = await RoomModel.findOneAndUpdate(
{ roomId },
{
$pull: { participants: userId },
lastActivity: new Date(),
},
{ new: true }
);
if (room && socket.data.username) {
const systemMessage = await MessageModel.create({
roomId,
userId: "system",
username: "System",
message: `${socket.data.username} left the room`,
type: "system",
timestamp: new Date(),
});
io.to(roomId).emit("user:left", {
userId,
username: socket.data.username,
});
io.to(roomId).emit("message:new", systemMessage.toObject());
io.to(roomId).emit("participants:update", room.participants);
}
} catch (error) {
console.error("Error leaving room:", error);
}
});
// Send message
socket.on("message:send", async ({ roomId, userId, username, message }) => {
try {
// Rate limiting: 30 messages per minute per socket
if (rateLimiter.isRateLimited(`message:${socket.id}`, 30, 60000)) {
socket.emit("error", {
message: "Too many messages. Please slow down.",
});
return;
}
// Encrypt message before storing in database
const encryptedMessage = encryptMessage(message);
const newMessage = await MessageModel.create({
roomId,
userId,
username,
message: encryptedMessage,
type: "text",
timestamp: new Date(),
});
await RoomModel.updateOne({ roomId }, { lastActivity: new Date() });
// Decrypt message before broadcasting to users
const messageObj = newMessage.toObject();
messageObj.message = decryptMessage(messageObj.message);
io.to(roomId).emit("message:new", messageObj);
} catch (error) {
console.error("Error sending message:", error);
socket.emit("error", { message: "Failed to send message" });
}
});
// Update text content (live editing)
socket.on("text:change", async ({ roomId, textContent, userId }) => {
try {
await RoomModel.updateOne(
{ roomId },
{
textContent,
lastActivity: new Date(),
}
);
// Broadcast to ALL users in the room (including sender for confirmation)
io.to(roomId).emit("text:update", { textContent });
} catch (error) {
console.error("Error updating text:", error);
}
});
// Y.js collaborative editing events
// Store Y.js state per room in memory (in production, consider Redis)
const roomStates = new Map<string, Uint8Array>();
socket.on("yjs:update", async ({ roomId, update }) => {
try {
// Convert array back to Uint8Array
const updateArray = new Uint8Array(update);
// Store/merge the update with existing state
const currentState = roomStates.get(roomId);
if (currentState) {
// Merge updates (Y.js handles this automatically)
const Y = await import("yjs");
const doc = new Y.Doc();
Y.applyUpdate(doc, currentState);
Y.applyUpdate(doc, updateArray);
roomStates.set(roomId, Y.encodeStateAsUpdate(doc));
} else {
roomStates.set(roomId, updateArray);
}
// Broadcast update to all other clients in the room (excluding sender)
socket.to(roomId).emit("yjs:update", { update });
// Also update the text content in database for persistence
const Y = await import("yjs");
const doc = new Y.Doc();
Y.applyUpdate(doc, roomStates.get(roomId)!);
const ytext = doc.getText("content");
const textContent = ytext.toString();
await RoomModel.updateOne(
{ roomId },
{
textContent,
lastActivity: new Date(),
}
);
} catch (error) {
console.error("Error handling Y.js update:", error);
}
});
socket.on("yjs:sync-request", async ({ roomId }) => {
try {
// Send current state to the requesting client
const state = roomStates.get(roomId);
if (state) {
socket.emit("yjs:sync-response", { state: Array.from(state) });
} else {
// If no state exists, create from database content
const room = await RoomModel.findOne({ roomId });
if (room && room.textContent) {
const Y = await import("yjs");
const doc = new Y.Doc();
const ytext = doc.getText("content");
ytext.insert(0, room.textContent);
const stateVector = Y.encodeStateAsUpdate(doc);
roomStates.set(roomId, stateVector);
socket.emit("yjs:sync-response", {
state: Array.from(stateVector),
});
} else {
socket.emit("yjs:sync-response", { state: [] });
}
}
} catch (error) {
console.error("Error handling Y.js sync request:", error);
}
});
// Disconnect
socket.on("disconnect", async () => {
try {
if (socket.data.roomId && socket.data.userId) {
const { roomId, userId, username } = socket.data;
const room = await RoomModel.findOneAndUpdate(
{ roomId },
{
$pull: { participants: userId },
lastActivity: new Date(),
},
{ new: true }
);
if (room && username) {
const systemMessage = await MessageModel.create({
roomId,
userId: "system",
username: "System",
message: `${username} disconnected`,
type: "system",
timestamp: new Date(),
});
io.to(roomId).emit("user:left", { userId, username });
io.to(roomId).emit("message:new", systemMessage.toObject());
io.to(roomId).emit("participants:update", room.participants);
}
}
} catch (error) {
console.error("Error on disconnect:", error);
}
});
});
// Periodic cleanup service - runs every minute
const setupCleanupService = async () => {
const { CleanupService } = await import("./lib/cleanup-service");
const runCleanup = async () => {
// Callback to notify clients when a room is deleted
const notifyCallback = async (roomId: string) => {
if (io) {
io.to(roomId).emit("room:deleted", {
message: "This room has expired and been automatically deleted.",
});
// Disconnect all sockets in this room
const sockets = await io.in(roomId).fetchSockets();
for (const socket of sockets) {
socket.leave(roomId);
}
}
};
// Cleanup expired rooms
await CleanupService.cleanupExpiredRooms(notifyCallback);
// Optionally cleanup inactive rooms (24 hours of inactivity)
// await CleanupService.cleanupInactiveRooms(24, notifyCallback);
};
// Run cleanup every minute
setInterval(runCleanup, 60 * 1000);
// Run cleanup on startup
runCleanup();
};
setupCleanupService();
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
if (process.env.NODE_ENV !== "production") {
console.log(`Server ready on http://${hostname}:${port}`);
}
});
});