| /** | |
| * Auth Middleware | |
| * Validates X-API-Key header for protected routes | |
| * Lightweight to stay within 10ms CF Workers CPU budget | |
| */ | |
| import type { MiddlewareHandler } from 'hono'; | |
| import type { Env } from '../types/env'; | |
| export const authMiddleware: MiddlewareHandler<{ Bindings: Env }> = async (c, next) => { | |
| const apiKey = c.req.header('X-API-Key') ?? c.req.header('Authorization')?.replace('Bearer ', ''); | |
| if (!apiKey) { | |
| return c.json({ success: false, error: 'Missing API key. Provide X-API-Key header.' }, 401); | |
| } | |
| // Constant-time comparison to prevent timing attacks | |
| const expected = c.env.INTERNAL_API_SECRET; | |
| if (!safeCompare(apiKey, expected)) { | |
| return c.json({ success: false, error: 'Invalid API key.' }, 403); | |
| } | |
| await next(); | |
| }; | |
| function safeCompare(a: string, b: string): boolean { | |
| if (a.length !== b.length) return false; | |
| let result = 0; | |
| for (let i = 0; i < a.length; i++) { | |
| result |= (a.charCodeAt(i) ^ b.charCodeAt(i)); | |
| } | |
| return result === 0; | |
| } | |