import { createHash, timingSafeEqual } from "node:crypto"; import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; function tokenMatches(actual: string, expected: string) { const actualValue = createHash("sha256").update(actual).digest(); const expectedValue = createHash("sha256").update(expected).digest(); return timingSafeEqual(actualValue, expectedValue); } export function proxy(request: NextRequest) { if (request.nextUrl.pathname === "/api/health") return NextResponse.next(); const configuredToken = process.env.ORGANIZER_ACCESS_TOKEN?.trim(); if (!configuredToken) return NextResponse.next(); const authorization = request.headers.get("authorization") || ""; const suppliedToken = authorization.startsWith("Bearer ") ? authorization.slice(7) : ""; if (tokenMatches(suppliedToken, configuredToken)) return NextResponse.next(); return NextResponse.json( { error: "Unauthorized" }, { status: 401, headers: { "Cache-Control": "no-store", "WWW-Authenticate": "Bearer realm=\"Hobbs Family Organizer\"", }, }, ); } export const config = { matcher: ["/((?!api/health).*)"], };