File size: 935 Bytes
e81f4e4 | 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 | import { timingSafeStringEqual } from "../../shared/crypto";
type AuthConfig = { api_keys?: readonly string[] | null | undefined };
// Accept the caller key from Bearer, x-api-key, x-goog-api-key, or ?key=.
export function authorized(
request: Request,
url: URL,
cfg: AuthConfig,
): boolean {
const keys = cfg.api_keys || [];
if (!keys.length) return true;
const h = request.headers;
const auth = h.get("authorization") || "";
const bearer = /^\s*Bearer\s+(.+?)\s*$/i.exec(auth);
const candidates = [
bearer?.[1] ? bearer[1] : null,
h.get("x-api-key"),
h.get("x-goog-api-key"),
url.searchParams.get("key"),
];
for (const raw of candidates) {
const candidate = String(raw || "").trim();
if (!candidate) continue;
let matched = false;
for (const configured of keys) {
matched =
timingSafeStringEqual(candidate, String(configured || "")) || matched;
}
if (matched) return true;
}
return false;
}
|