fix architecture and write new tests
This commit is contained in:
+30
-3
@@ -1,11 +1,13 @@
|
||||
import http from 'http'
|
||||
import { Server as SocketIOServer } from 'socket.io'
|
||||
import type { Socket } from 'socket.io'
|
||||
import cron from 'node-cron'
|
||||
import jwt from 'jsonwebtoken'
|
||||
import { redis } from './lib/redis'
|
||||
import { prisma } from './lib/prisma'
|
||||
import { assertStorageConfiguration } from './lib/storage'
|
||||
import { createApp, corsOrigins } from './app'
|
||||
import { verifyAnyActorToken } from './security/tokens'
|
||||
import { getSessionCookieName } from './security/sessionCookies'
|
||||
import { sendNotification } from './services/notificationService'
|
||||
import {
|
||||
runTrialExpirationJob,
|
||||
@@ -24,12 +26,37 @@ const io = new SocketIOServer(server, {
|
||||
cors: { origin: corsOrigins, credentials: true, methods: ['GET', 'POST'] },
|
||||
})
|
||||
|
||||
|
||||
function readCookieFromHeader(cookieHeader: string | undefined, name: string): string | null {
|
||||
if (!cookieHeader) return null
|
||||
|
||||
for (const chunk of cookieHeader.split(';')) {
|
||||
const [rawName, ...rawValue] = chunk.trim().split('=')
|
||||
if (rawName === name) return decodeURIComponent(rawValue.join('='))
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function getSocketSessionToken(socket: Socket): string | undefined {
|
||||
const explicitToken = socket.handshake.auth?.token
|
||||
if (typeof explicitToken === 'string' && explicitToken.trim()) return explicitToken.trim()
|
||||
|
||||
const cookieHeader = socket.request.headers.cookie
|
||||
return (
|
||||
readCookieFromHeader(cookieHeader, getSessionCookieName('employee')) ??
|
||||
readCookieFromHeader(cookieHeader, getSessionCookieName('admin')) ??
|
||||
readCookieFromHeader(cookieHeader, getSessionCookieName('renter')) ??
|
||||
undefined
|
||||
)
|
||||
}
|
||||
|
||||
// Authenticate socket connections via JWT before joining user rooms
|
||||
io.use((socket, next) => {
|
||||
const token = socket.handshake.auth?.token as string | undefined
|
||||
const token = getSocketSessionToken(socket)
|
||||
if (!token) return next() // unauthenticated connections allowed; they just don't join rooms
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; type: string }
|
||||
const payload = verifyAnyActorToken(token)
|
||||
;(socket as any).authenticatedUserId = payload.sub
|
||||
next()
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user