-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
142 lines (119 loc) · 4.91 KB
/
Copy pathserver.ts
File metadata and controls
142 lines (119 loc) · 4.91 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
import { createServer } from "http"
import { parse } from "url"
import next from "next"
import { Server as SocketIOServer } from "socket.io"
import { prisma } from "./src/lib/prisma"
import fs from "fs"
import path from "path"
import { setSocketServer } from "./src/lib/socket-server"
const dev = process.env.NODE_ENV !== "production"
const hostname = "0.0.0.0" // Always listen on all interfaces for Docker compatibility
const port = parseInt(process.env.PORT || "3000", 10)
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const httpServer = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url!, true)
// Do not handle socket.io requests with Next.js
if (parsedUrl.pathname?.startsWith('/api/socket')) {
return
}
if (parsedUrl.pathname?.startsWith('/uploads/')) {
const uploadsDir = path.join(process.cwd(), 'public', 'uploads')
const requestedPath = path.join(process.cwd(), 'public', parsedUrl.pathname)
const relative = path.relative(uploadsDir, requestedPath)
// Prevent path traversal: ensure path is inside uploadsDir and not pointing to parent directories
if (relative.startsWith('..') || path.isAbsolute(relative)) {
res.statusCode = 403
res.end("Forbidden")
return
}
if (fs.existsSync(requestedPath)) {
const ext = path.extname(requestedPath).toLowerCase()
const mimeTypes: Record<string, string> = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
}
res.setHeader('Content-Type', mimeTypes[ext] || 'application/octet-stream')
fs.createReadStream(requestedPath).pipe(res)
return
}
}
await handle(req, res, parsedUrl)
} catch (err) {
console.error("Error handling request:", err)
res.statusCode = 500
res.end("Internal server error")
}
})
// Consolidated WebSocket Server on the default path
const io = new SocketIOServer(httpServer, {
path: "/api/socket",
cors: {
origin: true,
methods: ["GET", "POST"],
credentials: true
},
transports: ["websocket"],
allowEIO3: true,
serveClient: false,
cookie: false
})
setSocketServer(io)
io.use(async (socket, next) => {
try {
const sessionToken = socket.handshake.auth.sessionToken
if (!sessionToken) {
console.log("[WS-AUTH] Failed: No session token")
return next(new Error("No session token provided"))
}
const session = await prisma.session.findUnique({
where: { token: sessionToken },
include: { user: { select: { id: true, role: true } } }
})
if (!session || new Date(session.expiresAt) < new Date()) {
console.log("[WS-AUTH] Failed: Invalid or expired session")
return next(new Error("Invalid or expired session"))
}
socket.data.userId = session.user.id
socket.data.userRole = session.user.role
console.log(`[WS-AUTH] Success for user: ${session.user.id}`)
next()
} catch (error) {
console.error("Socket auth error:", error)
next(new Error("Authentication failed"))
}
})
io.on("connection", (socket) => {
const userId = socket.data.userId
const userRole = socket.data.userRole
console.log(`[WS] User connected: ${userId} (${userRole})`)
socket.join(`user:${userId}`)
if (userRole === "STAFF") {
socket.join("staff")
console.log(`[WS] User ${userId} joined staff room`)
}
socket.on("disconnect", (reason) => {
console.log(`[WS] User disconnected: ${userId} (${reason})`)
})
socket.on("ping", () => {
socket.emit("pong")
})
})
;(async () => {
try {
console.log("> Starting notification queue worker...")
const { initNotificationWorker } = await import("@/lib/queue/worker")
initNotificationWorker(io)
console.log("> Notification queue worker started successfully")
} catch (error) {
console.error("> FAILED to start notification queue worker:", error)
}
})()
httpServer.listen(port, () => {
console.log(`> Server ready on http://${hostname}:${port}`)
console.log(`> WebSockets active on the same port`)
})
})