import { isValidKey, getKeyInfo } from "../services/keys.js"; export function authMiddleware(req, res, next) { const header = req.headers.authorization; const xApiKey = req.headers["x-api-key"]; let key; if (header?.startsWith("Bearer ")) { key = header.slice(7); } else if (xApiKey) { key = xApiKey; } if (!key) { res.status(401).json({ error: "Missing API key. Use: Authorization: Bearer or X-API-Key: " }); return; } if (!isValidKey(key)) { res.status(403).json({ error: "Invalid API key" }); return; } // Attach key info to request for downstream use req.apiKeyInfo = getKeyInfo(key); next(); }