Open History to see the last commit
1/** Admin-key gating + the JSON error envelope used by every API response. */
2
3export function jsonError(
4 status: number,
5 code: string,
6 message: string,
7): Response {
8 return Response.json({ error: { code, message } }, { status })
9}
10
11/**
12 * Admin requests present the key via `X-Admin-Key` or `Authorization:
13 * Bearer`. Always false when no ADMIN_KEY is configured — the admin surface
14 * fails closed.
15 */
16export function isAdminRequest(
17 request: Request,
18 adminKey: string | undefined,
19): boolean {
20 if (!adminKey) return false
21 const authorization = request.headers.get('authorization')
22 const bearer = authorization?.startsWith('Bearer ')
23 ? authorization.slice('Bearer '.length)
24 : null
25 const presented = request.headers.get('x-admin-key') ?? bearer
26 return presented !== null && sameKey(presented, adminKey)
27}
28
29/** Constant-time for a given key length, so timing does not leak a prefix. */
30function sameKey(presented: string, expected: string): boolean {
31 const a = new TextEncoder().encode(presented)
32 const b = new TextEncoder().encode(expected)
33 let diff = a.length ^ b.length
34 for (let i = 0; i < b.length; i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0)
35 return diff === 0
36}