This repository was archived by the owner on Jul 15, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
457 lines (402 loc) · 13.3 KB
/
Copy pathserver.mjs
File metadata and controls
457 lines (402 loc) · 13.3 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
import "dotenv/config";
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { Server } from "socket.io";
import jwt from "jsonwebtoken";
import fs from "fs";
import path from "path";
import { PrismaClient } from "@prisma/client";
import * as Sentry from "@sentry/node";
const dev = process.env.NODE_ENV !== "production";
const hostname = "0.0.0.0";
const port = parseInt(process.env.PORT || "3000", 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
throw new Error("JWT_SECRET is required");
}
if (process.env.SENTRY_DSN) {
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || "development",
tracesSampleRate: Number(process.env.SENTRY_TRACES_SAMPLE_RATE || "0.1"),
});
}
function log(level, message, context = undefined) {
const payload = {
ts: new Date().toISOString(),
level,
message,
...(context ? { context } : {}),
};
const line = JSON.stringify(payload);
if (level === "error") {
console.error(line);
} else if (level === "warn") {
console.warn(line);
} else {
console.log(line);
}
}
process.on("uncaughtException", (error) => {
log("error", "uncaughtException", { error: error.message });
if (process.env.SENTRY_DSN) Sentry.captureException(error);
});
process.on("unhandledRejection", (reason) => {
log("error", "unhandledRejection", {
reason: reason instanceof Error ? reason.message : String(reason),
});
if (process.env.SENTRY_DSN) {
Sentry.captureException(
reason instanceof Error ? reason : new Error(String(reason)),
);
}
});
const prisma = new PrismaClient();
const UPLOAD_ROOT = path.resolve(
process.cwd(),
process.env.UPLOAD_DIR || "uploads",
);
function applySecurityHeaders(res) {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
res.setHeader(
"Permissions-Policy",
"camera=(), geolocation=(), microphone=(self)",
);
res.setHeader("Cross-Origin-Resource-Policy", "same-site");
res.setHeader(
"Content-Security-Policy",
"default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; " +
"img-src 'self' data: blob:; media-src 'self' blob:; " +
"font-src 'self' https://fonts.gstatic.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://static.cloudflareinsights.com; " +
"connect-src 'self' ws: wss: https://cloudflareinsights.com stun: turn: turns:",
);
if (process.env.NODE_ENV === "production") {
res.setHeader(
"Strict-Transport-Security",
"max-age=31536000; includeSubDomains; preload",
);
}
}
// Active call state (only 1 at a time)
let activeCall = null; // { callerId, calleeId, logId, startedAt }
app.prepare().then(() => {
const server = createServer((req, res) => {
applySecurityHeaders(res);
const parsedUrl = parse(req.url, true);
// Serve uploaded files from ./uploads directory
if (parsedUrl.pathname && parsedUrl.pathname.startsWith("/uploads/")) {
const relativePath = decodeURIComponent(
parsedUrl.pathname.slice("/uploads/".length),
);
const normalizedRelativePath = path
.normalize(relativePath)
.replace(/^([/\\])+/, "");
const filePath = path.resolve(UPLOAD_ROOT, normalizedRelativePath);
// Block path traversal and invalid paths
if (
!relativePath ||
relativePath.includes("\0") ||
!filePath.startsWith(UPLOAD_ROOT + path.sep)
) {
res.writeHead(403);
res.end("Forbidden");
return;
}
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
const ext = path.extname(filePath).toLowerCase();
const contentTypes = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".mp4": "video/mp4",
".pdf": "application/pdf",
".txt": "text/plain",
};
res.writeHead(200, {
"Content-Type": contentTypes[ext] || "application/octet-stream",
});
fs.createReadStream(filePath).pipe(res);
return;
}
}
handle(req, res, parsedUrl);
});
// Socket.io
const io = new Server(server, {
cors: {
origin: true,
credentials: true,
},
pingInterval: 25000,
pingTimeout: 20000,
connectTimeout: 45000,
});
globalThis.__felfelIo = io;
// Track online users
const onlineUsers = new Map(); // userId -> socketId
// Auth middleware
io.use((socket, next) => {
try {
const token = socket.handshake.auth?.token;
const normalizedToken =
typeof token === "string" && token.trim() ? token.trim() : "";
if (!normalizedToken) {
const cookieHeader = socket.handshake.headers?.cookie || "";
const tokenMatch = cookieHeader.match(/(?:^|;\s*)token=([^;]+)/);
if (!tokenMatch) {
log("warn", "socket.auth.failed", { reason: "no_token" });
return next(new Error("No token"));
}
const rawToken = tokenMatch[1];
const decodedToken = decodeURIComponent(rawToken);
const decoded = jwt.verify(decodedToken, JWT_SECRET);
socket.user = decoded;
} else {
socket.user = jwt.verify(normalizedToken, JWT_SECRET);
}
next();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
log("warn", "socket.auth.error", { error: errorMessage });
if (process.env.SENTRY_DSN) Sentry.captureException(err);
next(new Error(`Auth error: ${errorMessage}`));
}
});
io.on("connection", (socket) => {
const userId = socket.user.id;
const username = socket.user.username;
const joinedRooms = new Set();
log("info", "socket.connected", { userId, username });
// Track online
onlineUsers.set(userId, socket.id);
socket.join(`user:${userId}`);
io.emit("user:online", userId);
// SuperAdmin monitoring room
if (socket.user.isSuperAdmin) {
socket.join("superadmin");
// Send current active call info
if (activeCall) {
socket.emit("call:started", activeCall);
}
// Send online users count
socket.emit("admin:onlineCount", onlineUsers.size);
}
// --- Room management ---
socket.on("room:join", async (roomId) => {
if (!roomId || typeof roomId !== "string") return;
const membership = await prisma.roomMember.findUnique({
where: { userId_roomId: { userId, roomId } },
});
if (!membership) {
return socket.emit("error", "Forbidden");
}
joinedRooms.add(roomId);
socket.join(`room:${roomId}`);
});
socket.on("room:leave", (roomId) => {
joinedRooms.delete(roomId);
socket.leave(`room:${roomId}`);
});
// --- Messages ---
socket.on("message:send", async (data) => {
if (!data?.roomId || typeof data.roomId !== "string") return;
const membership = await prisma.roomMember.findUnique({
where: { userId_roomId: { userId, roomId: data.roomId } },
});
if (!membership) {
return socket.emit("error", "Forbidden");
}
log("info", "socket.message.send", { userId, roomId: data.roomId });
// Broadcast to room members
io.to(`room:${data.roomId}`).emit("message:new", {
...data,
userId,
username,
createdAt: new Date().toISOString(),
});
log("info", "socket.message.broadcast", { roomId: data.roomId });
});
socket.on("message:typing", async (roomId) => {
if (!roomId || typeof roomId !== "string") return;
if (!joinedRooms.has(roomId)) return;
const membership = await prisma.roomMember.findUnique({
where: { userId_roomId: { userId, roomId } },
});
if (!membership) return;
socket.to(`room:${roomId}`).emit("message:typing", username);
});
socket.on("message:read", async ({ messageId, roomId }) => {
if (!roomId || typeof roomId !== "string") return;
if (!joinedRooms.has(roomId)) return;
if (!messageId || typeof messageId !== "string") return;
const membership = await prisma.roomMember.findUnique({
where: { userId_roomId: { userId, roomId } },
});
if (!membership) return;
try {
const message = await prisma.message.findUnique({
where: { id: messageId },
select: { id: true, roomId: true, readBy: true },
});
if (!message || message.roomId !== roomId) return;
const readByUsers = (message.readBy || "")
.split(/[,\s;]+/)
.map((item) => item.trim())
.filter(Boolean);
const readBySet = new Set(readByUsers);
readBySet.add(userId);
const nextReadBy = Array.from(readBySet).join(",");
if (nextReadBy !== (message.readBy || "")) {
await prisma.message.update({
where: { id: messageId },
data: { readBy: nextReadBy },
});
}
io.to(`room:${roomId}`).emit("message:read", {
messageId,
userId,
readBy: nextReadBy,
});
} catch (error) {
log("warn", "socket.message.read.error", {
messageId,
roomId,
error: error instanceof Error ? error.message : String(error),
});
}
});
// --- Voice Calls (1 at a time) ---
socket.on("call:initiate", async ({ calleeId }) => {
if (activeCall) {
return socket.emit(
"call:error",
"A call is already active. Please wait.",
);
}
if (!calleeId || typeof calleeId !== "string") {
return socket.emit("call:error", "Invalid callee");
}
const privateRoom = await prisma.room.findFirst({
where: {
type: "PRIVATE",
AND: [
{ members: { some: { userId } } },
{ members: { some: { userId: calleeId } } },
],
},
select: { id: true },
});
if (!privateRoom) {
return socket.emit("call:error", "No private room with target user");
}
const logId = `call-${Date.now()}`; // simplified ID
activeCall = {
callerId: userId,
calleeId,
logId,
callerName: username,
startedAt: new Date().toISOString(),
};
socket.emit("call:initiated", {
logId,
calleeId,
});
// Notify callee
io.to(`user:${calleeId}`).emit("call:incoming", {
callerId: userId,
callerName: username,
logId,
});
// Notify superadmin
io.to("superadmin").emit("call:started", activeCall);
});
socket.on("call:accept", ({ logId }) => {
if (activeCall && activeCall.logId === logId) {
if (![activeCall.callerId, activeCall.calleeId].includes(userId))
return;
activeCall.status = "ACTIVE";
io.to(`user:${activeCall.callerId}`).emit("call:accepted", { logId });
io.to("superadmin").emit("call:updated", {
...activeCall,
status: "ACTIVE",
});
}
});
socket.on("call:end", ({ logId }) => {
if (
!activeCall ||
![activeCall.callerId, activeCall.calleeId].includes(userId)
)
return;
endCall(logId, "ENDED");
});
socket.on("call:reject", ({ logId }) => {
if (
!activeCall ||
![activeCall.callerId, activeCall.calleeId].includes(userId)
)
return;
endCall(logId, "REJECTED");
});
// WebRTC signaling
socket.on("call:signal", ({ targetUserId, signal }) => {
if (!activeCall) return;
const inCall = [activeCall.callerId, activeCall.calleeId];
if (!inCall.includes(userId) || !inCall.includes(targetUserId)) return;
io.to(`user:${targetUserId}`).emit("call:signal", {
fromUserId: userId,
signal,
});
});
// SuperAdmin: terminate call
socket.on("call:terminate", ({ logId }) => {
if (!socket.user.isSuperAdmin) {
return socket.emit("error", "Forbidden");
}
endCall(logId, "TERMINATED");
});
// Disconnect
socket.on("disconnect", () => {
onlineUsers.delete(userId);
io.emit("user:offline", userId);
io.to("superadmin").emit("admin:onlineCount", onlineUsers.size);
// End call if participant disconnects
if (
activeCall &&
(activeCall.callerId === userId || activeCall.calleeId === userId)
) {
endCall(activeCall.logId, "ENDED");
}
});
});
function endCall(logId, status) {
if (activeCall && activeCall.logId === logId) {
const endedCall = {
...activeCall,
status,
endedAt: new Date().toISOString(),
};
io.to(`user:${activeCall.callerId}`).emit("call:ended", {
logId,
status,
});
io.to(`user:${activeCall.calleeId}`).emit("call:ended", {
logId,
status,
});
io.to("superadmin").emit("call:ended", endedCall);
activeCall = null;
}
}
server.listen(port, hostname, () => {
log("info", "server.started", { url: `http://${hostname}:${port}` });
});
});