Lumen & Gesso / website · lumengesso.com / app / lib / d1-auth.ts
| 1 | import { betterAuth } from 'better-auth'; |
| 2 | import { magicLink } from 'better-auth/plugins'; |
| 3 | import { passkey } from '@better-auth/passkey'; |
| 4 | |
| 5 | type D1Statement = { |
| 6 | bind(...values: string[]): D1Statement; |
| 7 | first<T>(): Promise<T | null>; |
| 8 | }; |
| 9 | export type AuthDatabase = { prepare(query: string): D1Statement }; |
| 10 | export type SendLink = (link: { email: string; url: string }) => Promise<void>; |
| 11 | |
| 12 | // Passkeys only. Nobody signs in with a password or by typing an email. |
| 13 | // The magic-link plugin stays only so order emails can carry a private, |
| 14 | // single-use link straight to that order (and the first-passkey setup link). |
| 15 | // There is no form anywhere that requests one. |
| 16 | export function createD1Auth(database: AuthDatabase, origin: string, secret: string, sendMagicLink: SendLink) { |
| 17 | return betterAuth({ |
| 18 | database: database as NonNullable<Parameters<typeof betterAuth>[0]>['database'], |
| 19 | baseURL: origin, |
| 20 | appName: 'Lumen & Gesso', |
| 21 | secret, |
| 22 | trustedOrigins: [origin], |
| 23 | rateLimit: { enabled: true, storage: 'database' }, |
| 24 | advanced: { |
| 25 | cookiePrefix: 'lumen', |
| 26 | ipAddress: { ipAddressHeaders: ['cf-connecting-ip'] }, |
| 27 | }, |
| 28 | account: { accountLinking: { enabled: false } }, |
| 29 | plugins: [ |
| 30 | magicLink({ expiresIn: 900, storeToken: 'hashed', disableSignUp: true, sendMagicLink }), |
| 31 | passkey({ |
| 32 | rpID: new URL(origin).hostname, |
| 33 | rpName: 'Lumen & Gesso', |
| 34 | origin, |
| 35 | authenticatorSelection: { residentKey: 'required', userVerification: 'required' }, |
| 36 | registration: { |
| 37 | // Someone without an account can create one with just a passkey (no email, no password). |
| 38 | // A signed-in person adding a passkey keeps their own account. |
| 39 | requireSession: false, |
| 40 | resolveUser: () => ({ id: crypto.randomUUID(), name: 'Lumen & Gesso', displayName: 'Lumen & Gesso' }), |
| 41 | afterVerification: async ({ user }) => { |
| 42 | const now = new Date().toISOString(); |
| 43 | const row = await database.prepare(` |
| 44 | INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt") |
| 45 | VALUES (?, '', ?, 1, ?, ?) ON CONFLICT (id) DO NOTHING RETURNING id |
| 46 | `).bind(user.id, `${user.id}@passkey.invalid`, now, now).first<{ id: string }>(); |
| 47 | return { userId: row?.id ?? user.id }; |
| 48 | }, |
| 49 | }, |
| 50 | }), |
| 51 | ], |
| 52 | }); |
| 53 | } |