api/src/lib/auth.ts

32 lines · 1220 bytes

 1/**
 2 * Middleware to add basic bearer token auth to /enrich/* routes
 3 * To prevent abuse of endpoints which make third-party requests
 4 * It's off-by-default, and can be enabled by setting API_TOKEN
 5 * Works by checking the "Authorization: Bearer $API_TOKEN" header
 6 */
 7
 8import type { MiddlewareHandler } from 'hono'
 9import { ApiError } from '@/lib/errors'
10import type { HonoEnv } from '@/types'
11
12// Compare specified token against expected, using constant time
13const constantTimeEqual = (left: string, right: string) => {
14  if (left.length !== right.length) return false
15  let diff = 0
16  for (let index = 0; index < left.length; index++) {
17    diff |= left.charCodeAt(index) ^ right.charCodeAt(index)
18  }
19  return diff === 0
20}
21
22// If auth enabled, check specified header matches env var, otherwise respond 401
23export const requireBearer = (): MiddlewareHandler<HonoEnv> => async (c, next) => {
24  const expected = c.env.API_TOKEN
25  if (!expected) return next()
26  const header = c.req.header('authorization') ?? ''
27  const match = /^Bearer\s+(\S+)$/i.exec(header)
28  if (!match || !constantTimeEqual(match[1], expected)) {
29    throw new ApiError('UNAUTHORIZED', 'Invalid or missing bearer token', 401)
30  }
31  await next()
32}