api/src/lib/auth.ts

32 lines · 1251 bytes

3 symbols in this file
 1/**
 2 * Bearer token check for /enrich/* routes.
 3 * The endpoints are public by default, but a request carrying the correct
 4 * "Authorization: Bearer $API_TOKEN" header is exempt from rate limiting.
 5 * When API_TOKEN is unset (e.g. self-hosted), no request is privileged.
 6 * Setting REQUIRE_AUTH turns the token into a hard gate (see authRequired).
 7 */
 8
 9// Compare two strings in constant time
10const constantTimeEqual = (left: string, right: string) => {
11  if (left.length !== right.length) return false
12  let diff = 0
13  for (let index = 0; index < left.length; index++) {
14    diff |= left.charCodeAt(index) ^ right.charCodeAt(index)
15  }
16  return diff === 0
17}
18
19// True when a valid bearer token is present (auth must be configured)
20export const hasValidToken = (
21  expected: string | undefined,
22  header: string | undefined,
23): boolean => {
24  if (!expected) return false
25  const match = /^Bearer\s+(\S+)$/i.exec(header ?? '')
26  return !!match && constantTimeEqual(match[1], expected)
27}
28
29// True when REQUIRE_AUTH is enabled, hard-gating enrich behind a valid token.
30// Off by default; needs API_TOKEN set too, else every request fails closed.
31export const authRequired = (value: string | undefined): boolean =>
32  /^(1|true|yes|on)$/i.test(value ?? '')