| import { FastifyRequest, FastifyReply } from 'fastify'; | |
| /** | |
| * Middleware to verify JWT token. | |
| * Throws an error if the token is invalid or missing. | |
| */ | |
| export const verifyJwt = async (request: FastifyRequest, reply: FastifyReply) => { | |
| try { | |
| // EventSource (SSE) cannot send custom headers — accept JWT as ?token= query param fallback | |
| const queryToken = (request.query as Record<string, string>)?.token; | |
| if (queryToken && !request.headers.authorization) { | |
| request.headers.authorization = `Bearer ${queryToken}`; | |
| } | |
| await request.jwtVerify(); | |
| } catch (err) { | |
| reply.code(401).send({ error: 'Unauthorized', message: 'Invalid or missing token' }); | |
| throw err; | |
| } | |
| }; | |