import { timingSafeEqual } from 'node:crypto'; import { generateMagicLink } from '@/app/lib/magic-link'; import { hasBetterAuthCustomer, provisionCustomer } from '@/app/lib/lumen-auth'; import { isAdmin } from '@/app/lib/admin'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // First passkey for a studio admin. Called by us from a terminal with the // LUMEN_PASSKEY_SETUP_SECRET (kept in Bitwarden Secrets Manager). Returns a // single-use, 15-minute private link that opens /admin, where the admin saves a // passkey. After that, passkeys are the only way in. Nothing is emailed. export async function POST(request: Request) { const secret = process.env.LUMEN_PASSKEY_SETUP_SECRET ?? ''; const given = request.headers.get('x-setup-secret') ?? ''; const ok = secret.length >= 32 && given.length === secret.length && timingSafeEqual(Buffer.from(given), Buffer.from(secret)); if (!ok) return new Response(null, { status: 404 }); const input = await request.json().catch(() => null) as { email?: unknown } | null; const email = typeof input?.email === 'string' ? input.email.trim().toLowerCase() : ''; if (!isAdmin(email)) return Response.json({ error: 'Not a studio admin.' }, { status: 400 }); if (!await hasBetterAuthCustomer(email)) await provisionCustomer(email); const link = await generateMagicLink(email, '/admin'); if (!link) return Response.json({ error: 'Could not create the link.' }, { status: 503 }); return Response.json({ link }, { headers: { 'cache-control': 'no-store' } }); }