All files / middleware internal-key.middleware.ts

100% Statements 18/18
100% Branches 14/14
100% Functions 3/3
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                              6x 6x   6x 2x     4x 4x 1x   3x 2x   1x       3x               2x 1x 1x 10x   1x    
import type { Context, Next } from "hono";
 
/**
 * Shared guard for every /api/internal/* request.
 *
 * The header must EQUAL the configured INTERNAL_API_KEY (constant-time
 * compare). Sub-routes still layer HMAC/JWT checks on top. The only bypass is
 * ENVIRONMENT === "local" with no key configured, matching the sub-routes'
 * local-dev convention. A deployed environment with no key configured fails
 * closed — nothing can be verified, so nothing passes.
 */
export async function internalKeyGuard(
	c: Context<{ Bindings: CloudflareBindings }>,
	next: Next,
) {
	const secret = c.env.INTERNAL_API_KEY;
	const isExplicitlyLocal = (c.env.ENVIRONMENT ?? "local") === "local";
 
	if (!secret && isExplicitlyLocal) {
		return next();
	}
 
	const token = c.req.header("X-Internal-API-Key");
	if (!token) {
		return unauthorized(c, "Missing X-Internal-API-Key header");
	}
	if (!secret || !secureCompare(token, secret)) {
		return unauthorized(c, "Invalid X-Internal-API-Key");
	}
	return next();
}
 
function unauthorized(c: Context, message: string) {
	return c.json(
		{ success: false, error: { code: "UNAUTHORIZED", message } },
		401,
	);
}
 
/** Constant-time string comparison (same shape as apikey.middleware.ts). */
function secureCompare(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;
}