seahaven-ap/packages/api/src/auth/origin-verify.ts

19 lines
647 B
TypeScript
Raw Normal View History

import { timingSafeEqual } from "node:crypto";
import type { Context } from "hono";
export const ORIGIN_VERIFY_HEADER = "x-origin-verify";
export function originVerifyHeader(c: Context): string {
return c.req.header(ORIGIN_VERIFY_HEADER)?.trim() ?? "";
}
/** When a secret is configured, only CloudFront's origin header is accepted. */
export function cloudFrontOriginAllowed(c: Context, secret: string | undefined): boolean {
if (!secret) return true;
const provided = originVerifyHeader(c);
const a = Buffer.from(provided);
const b = Buffer.from(secret);
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}