/** * API Key authentication middleware * * The API key is read from the environment variable API_KEY. * If API_KEY is not set the middleware is a no-op (useful in local dev). * * ─── HTTP (Express) ───────────────────────────────────────────────────────── * Clients must supply the key in ONE of the following ways: * • Header: x-api-key: * • Header: Authorization: Bearer * • Query: ?api_key= * * ─── WebSocket (Socket.IO) ────────────────────────────────────────────────── * Clients must supply the key in ONE of the following ways: * • io('', { auth: { apiKey: '' } }) * • io('', { extraHeaders: { 'x-api-key': '' } }) */ /** * Express middleware — runs on every HTTP request. */ const httpApiKeyMiddleware = (req, res, next) => { const apiKey = process.env.API_KEY // Key not configured → allow all (development mode) if (!apiKey) return next() // Skip preflight requests if (req.method === 'OPTIONS') return next() const headerKey = req.headers['x-api-key'] || (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim() const queryKey = req.query.api_key if (headerKey === apiKey || queryKey === apiKey) return next() return res .status(401) .json({ error: 'Unauthorized: invalid or missing API key' }) } /** * Socket.IO middleware — runs on every new connection handshake. */ const socketApiKeyMiddleware = (socket, next) => { const apiKey = process.env.API_KEY // Key not configured → allow all (development mode) if (!apiKey) return next() const fromAuth = socket.handshake.auth && socket.handshake.auth.apiKey const fromHeader = socket.handshake.headers && socket.handshake.headers['x-api-key'] if (fromAuth === apiKey || fromHeader === apiKey) return next() return next(new Error('Unauthorized: invalid or missing API key')) } module.exports = { httpApiKeyMiddleware, socketApiKeyMiddleware }