(req: Request, res: Response, next: NextFunction)
| 23 | } |
| 24 | |
| 25 | export function apiKeyAuth(req: Request, res: Response, next: NextFunction): void { |
| 26 | const validKeys = getValidKeys() |
| 27 | |
| 28 | // If no keys configured, allow all requests (local dev mode) |
| 29 | if (!validKeys) { |
| 30 | ;(req as any).apiKeyId = 'anonymous' |
| 31 | next() |
| 32 | return |
| 33 | } |
| 34 | |
| 35 | const authHeader = req.headers.authorization |
| 36 | if (!authHeader || !authHeader.startsWith('Bearer ')) { |
| 37 | res.status(401).json({ |
| 38 | error: 'Missing or invalid Authorization header. Use: Bearer <your-api-key>', |
| 39 | }) |
| 40 | return |
| 41 | } |
| 42 | |
| 43 | const key = authHeader.slice(7).trim() |
| 44 | if (!validKeys.has(key)) { |
| 45 | res.status(403).json({ error: 'Invalid API key' }) |
| 46 | return |
| 47 | } |
| 48 | |
| 49 | // Attach a key identifier for rate limiting (first 8 chars) |
| 50 | ;(req as any).apiKeyId = key.slice(0, 8) |
| 51 | next() |
| 52 | } |
nothing calls this directly
no test coverage detected