import { betterAuth } from 'better-auth'; import { magicLink } from 'better-auth/plugins'; import { passkey } from '@better-auth/passkey'; type D1Statement = { bind(...values: string[]): D1Statement; first(): Promise; }; export type AuthDatabase = { prepare(query: string): D1Statement }; export type SendLink = (link: { email: string; url: string }) => Promise; // Passkeys only. Nobody signs in with a password or by typing an email. // The magic-link plugin stays only so order emails can carry a private, // single-use link straight to that order (and the first-passkey setup link). // There is no form anywhere that requests one. export function createD1Auth(database: AuthDatabase, origin: string, secret: string, sendMagicLink: SendLink) { return betterAuth({ database: database as NonNullable[0]>['database'], baseURL: origin, appName: 'Lumen & Gesso', secret, trustedOrigins: [origin], rateLimit: { enabled: true, storage: 'database' }, advanced: { cookiePrefix: 'lumen', ipAddress: { ipAddressHeaders: ['cf-connecting-ip'] }, }, account: { accountLinking: { enabled: false } }, plugins: [ magicLink({ expiresIn: 900, storeToken: 'hashed', disableSignUp: true, sendMagicLink }), passkey({ rpID: new URL(origin).hostname, rpName: 'Lumen & Gesso', origin, authenticatorSelection: { residentKey: 'required', userVerification: 'required' }, registration: { // Someone without an account can create one with just a passkey (no email, no password). // A signed-in person adding a passkey keeps their own account. requireSession: false, resolveUser: () => ({ id: crypto.randomUUID(), name: 'Lumen & Gesso', displayName: 'Lumen & Gesso' }), afterVerification: async ({ user }) => { const now = new Date().toISOString(); const row = await database.prepare(` INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt") VALUES (?, '', ?, 1, ?, ?) ON CONFLICT (id) DO NOTHING RETURNING id `).bind(user.id, `${user.id}@passkey.invalid`, now, now).first<{ id: string }>(); return { userId: row?.id ?? user.id }; }, }, }), ], }); }