File size: 1,006 Bytes
dd480ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 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;
}