import { Request, Response, NextFunction } from 'express'; import { jwtVerify } from 'jose'; export interface AuthRequest extends Request { userId?: string; userRole?: string; } const secret = () => new TextEncoder().encode(process.env.JWT_SECRET ?? 'fallback-dev-secret'); export async function requireAuth(req: AuthRequest, res: Response, next: NextFunction): Promise { const header = req.headers.authorization; if (!header?.startsWith('Bearer ')) { res.status(401).json({ error: 'Unauthorized' }); return; } try { const token = header.slice(7); const { payload } = await jwtVerify(token, secret()); req.userId = payload.userId as string; req.userRole = payload.role as string; next(); } catch { res.status(401).json({ error: 'Invalid or expired token' }); } }