const { ApiError } = require("../utils/errors"); function extractBearerToken(authorizationHeader) { if (!authorizationHeader || typeof authorizationHeader !== "string") { return ""; } const match = authorizationHeader.match(/^Bearer\s+(.+)$/i); return match ? match[1].trim() : ""; } function apiKeyAuth(req, _res, next) { const configuredKey = String(process.env.API_KEY || "").trim(); if (!configuredKey) { return next(new ApiError(500, "API key is not configured on server")); } const apiKeyFromHeader = String(req.headers["x-api-key"] || "").trim(); const apiKeyFromBearer = extractBearerToken(req.headers.authorization); const providedKey = apiKeyFromHeader || apiKeyFromBearer; if (!providedKey) { return next(new ApiError(401, "API key is required")); } if (providedKey !== configuredKey) { return next(new ApiError(401, "Invalid API key")); } return next(); } module.exports = { apiKeyAuth, };