import 'server-only'; import { getCloudflareContext } from '@opennextjs/cloudflare'; import { headers } from 'next/headers'; import { env } from './env'; import { sendEmail } from './email'; import { createD1Auth, type AuthDatabase, type SendLink } from './d1-auth'; type Customer = { id: string; email?: string; name?: string }; function authDatabase() { const { COMMERCE_DB } = getCloudflareContext().env as { COMMERCE_DB?: AuthDatabase }; if (!COMMERCE_DB) throw new Error('Lumen authentication database is missing.'); return COMMERCE_DB; } export function authOrigin() { return new URL(process.env.LUMEN_AUTH_ORIGIN || env.site.url()).origin; } async function deliverLink({ email, url }: Parameters[0]) { const safeUrl = url.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>'); await sendEmail({ to: email, subject: 'Your private Lumen & Gesso link', html: `

Open your private link to see your commissions, then save a passkey to get back any time.

Open Lumen & Gesso

This link expires in 15 minutes. You can ignore this message if you didn’t request it.

`, text: `Your private Lumen & Gesso link: ${url}\n\nThis link expires in 15 minutes.`, }); } export function lumenAuth(sendMagicLink: SendLink = deliverLink) { const secret = process.env.LUMENGESSO_BETTER_AUTH_SECRET; if (!secret || secret.length < 32) throw new Error('Lumen authentication signing secret is missing.'); const origin = authOrigin(); return createD1Auth(authDatabase(), origin, secret, sendMagicLink); } export async function getCustomerUser(): Promise { const requestHeaders = await headers(); if (!/(?:^|;\s*)(?:__Secure-)?lumen\.session_token=/.test(requestHeaders.get('cookie') ?? '')) return null; const session = await lumenAuth().api.getSession({ headers: requestHeaders }); return session?.user.emailVerified ? session.user : null; } export async function provisionCustomer(email: string): Promise { const now = new Date().toISOString(); const db = authDatabase(); const inserted = await db.prepare(` INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt") VALUES (?, '', ?, 0, ?, ?) ON CONFLICT (email) DO NOTHING RETURNING id `).bind(crypto.randomUUID(), email, now, now).first<{ id: string }>(); if (inserted) return inserted.id; const existing = await db.prepare('SELECT id FROM "user" WHERE email=?').bind(email).first<{ id: string }>(); if (!existing) throw new Error('Could not find or create the customer account.'); return existing.id; } export async function customerDetailsById(userId: string) { return authDatabase().prepare('SELECT name FROM "user" WHERE id=?').bind(userId).first<{ name: string }>(); } export async function hasBetterAuthCustomer(email: string) { return Boolean(await authDatabase().prepare('SELECT id FROM "user" WHERE email=?') .bind(email).first<{ id: string }>()); }