Lumen & Gesso / website · lumengesso.com / app / api / passkey-setup / route.ts
| 1 | import { timingSafeEqual } from 'node:crypto'; |
| 2 | import { generateMagicLink } from '@/app/lib/magic-link'; |
| 3 | import { hasBetterAuthCustomer, provisionCustomer } from '@/app/lib/lumen-auth'; |
| 4 | import { isAdmin } from '@/app/lib/admin'; |
| 5 | |
| 6 | export const runtime = 'nodejs'; |
| 7 | export const dynamic = 'force-dynamic'; |
| 8 | |
| 9 | // First passkey for a studio admin. Called by us from a terminal with the |
| 10 | // LUMEN_PASSKEY_SETUP_SECRET (kept in Bitwarden Secrets Manager). Returns a |
| 11 | // single-use, 15-minute private link that opens /admin, where the admin saves a |
| 12 | // passkey. After that, passkeys are the only way in. Nothing is emailed. |
| 13 | export async function POST(request: Request) { |
| 14 | const secret = process.env.LUMEN_PASSKEY_SETUP_SECRET ?? ''; |
| 15 | const given = request.headers.get('x-setup-secret') ?? ''; |
| 16 | const ok = secret.length >= 32 && given.length === secret.length |
| 17 | && timingSafeEqual(Buffer.from(given), Buffer.from(secret)); |
| 18 | if (!ok) return new Response(null, { status: 404 }); |
| 19 | const input = await request.json().catch(() => null) as { email?: unknown } | null; |
| 20 | const email = typeof input?.email === 'string' ? input.email.trim().toLowerCase() : ''; |
| 21 | if (!isAdmin(email)) return Response.json({ error: 'Not a studio admin.' }, { status: 400 }); |
| 22 | if (!await hasBetterAuthCustomer(email)) await provisionCustomer(email); |
| 23 | const link = await generateMagicLink(email, '/admin'); |
| 24 | if (!link) return Response.json({ error: 'Could not create the link.' }, { status: 503 }); |
| 25 | return Response.json({ link }, { headers: { 'cache-control': 'no-store' } }); |
| 26 | } |