/** * Password gate helpers for dashboard access control. * * The gate cookie is an HMAC-SHA256 signature of the string "heartbeads-gate" * keyed by the dashboard password. This produces a static token that can be * validated by both Node.js (API routes) and Edge Runtime (middleware). * * Used by: * - app/api/auth/route.ts — generates and validates the cookie * - middleware.ts — validates cookie, Bearer token, and query param */ import { createHmac, timingSafeEqual } from "crypto"; export const COOKIE_NAME = "heartbeads_gate"; const HMAC_MESSAGE = "heartbeads-gate"; /** * Generate the gate token (HMAC-SHA256 of a fixed message, keyed by password). * This is the value stored in the httpOnly cookie. */ export function generateGateToken(password: string): string { return createHmac("sha256", password).update(HMAC_MESSAGE).digest("hex"); } /** * Validate a gate token against the password (Node.js crypto, constant-time). */ export function validateGateToken( token: string, password: string ): boolean { const expected = generateGateToken(password); if (token.length !== expected.length) return false; try { return timingSafeEqual(Buffer.from(token), Buffer.from(expected)); } catch { return false; } } /** * Constant-time password comparison (Node.js crypto). */ export function comparePassword( provided: string, expected: string ): boolean { if (provided.length !== expected.length) return false; try { return timingSafeEqual(Buffer.from(provided), Buffer.from(expected)); } catch { return false; } }