fix: agent-ws — safe socket.close() for non-WebSocket requests
HEAD/GET requests without WS upgrade caused 'socket.close is not a function' crash → 500 errors in logs. Wrap close() in try-catch. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -97,17 +97,22 @@ export const setupAgentWsRoute: FastifyPluginAsync = async (fastify) => {
|
|||||||
fastify.get('/ws/agent', { websocket: true }, async (connection: SocketStream, req) => {
|
fastify.get('/ws/agent', { websocket: true }, async (connection: SocketStream, req) => {
|
||||||
const socket = connection.socket as AgentSocket
|
const socket = connection.socket as AgentSocket
|
||||||
|
|
||||||
|
// Если соединение не WebSocket (HEAD/GET без Upgrade) — просто закрываем
|
||||||
|
const safeClose = (code: number, reason: string) => {
|
||||||
|
try { socket.close(code, reason) } catch { /* HTTP-сокет — игнорируем */ }
|
||||||
|
}
|
||||||
|
|
||||||
// Аутентификация по токену из заголовка
|
// Аутентификация по токену из заголовка
|
||||||
try {
|
try {
|
||||||
const authHeader = req.headers.authorization ?? ''
|
const authHeader = req.headers.authorization ?? ''
|
||||||
const token = authHeader.replace('Bearer ', '')
|
const token = authHeader.replace('Bearer ', '')
|
||||||
if (!token) { socket.close(1008, 'Unauthorized'); return }
|
if (!token) { safeClose(1008, 'Unauthorized'); return }
|
||||||
|
|
||||||
const payload = fastify.jwt.verify(token) as {
|
const payload = fastify.jwt.verify(token) as {
|
||||||
sub: string; role: string; workstation_id: string; hotel_slug: string
|
sub: string; role: string; workstation_id: string; hotel_slug: string
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.role !== 'agent') { socket.close(1008, 'Forbidden'); return }
|
if (payload.role !== 'agent') { safeClose(1008, 'Forbidden'); return }
|
||||||
|
|
||||||
socket.agentId = payload.sub
|
socket.agentId = payload.sub
|
||||||
socket.workstationId = payload.workstation_id
|
socket.workstationId = payload.workstation_id
|
||||||
@@ -115,7 +120,7 @@ export const setupAgentWsRoute: FastifyPluginAsync = async (fastify) => {
|
|||||||
socket.isAlive = true
|
socket.isAlive = true
|
||||||
|
|
||||||
} catch {
|
} catch {
|
||||||
socket.close(1008, 'Invalid token')
|
safeClose(1008, 'Invalid token')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user