Become a Pro / website · becomeapro.ai / src / lib / d1-auth.ts
| 1 | import { betterAuth } from "better-auth"; |
| 2 | import { getCloudflareContext } from "@opennextjs/cloudflare"; |
| 3 | import { biolockSessions } from "./biolock/session-plugin"; |
| 4 | |
| 5 | interface D1Statement { |
| 6 | bind(...values: (string | number | null)[]): D1Statement; |
| 7 | first<T = unknown>(): Promise<T | null>; |
| 8 | all<T = unknown>(): Promise<{ results: T[] }>; |
| 9 | run(): Promise<unknown>; |
| 10 | } |
| 11 | export type AuthDatabase = { |
| 12 | prepare(query: string): D1Statement; |
| 13 | batch(statements: D1Statement[]): Promise<unknown>; |
| 14 | }; |
| 15 | |
| 16 | // Sign-in is BioLock only: this device's own fingerprint or face reader. Better Auth keeps the session. |
| 17 | export function createResourceAuth(db: AuthDatabase, origin: string, secret: string) { |
| 18 | return betterAuth({ |
| 19 | database: db as NonNullable<Parameters<typeof betterAuth>[0]>["database"], |
| 20 | baseURL: origin, |
| 21 | appName: "Become a Pro", |
| 22 | secret, |
| 23 | user: { |
| 24 | additionalFields: { |
| 25 | // Older accounts were made with Google or Apple; new ones are BioLock. |
| 26 | provider: { type: "string", required: false, input: false }, |
| 27 | }, |
| 28 | }, |
| 29 | advanced: { cookiePrefix: "airesourcepro", ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] } }, |
| 30 | rateLimit: { enabled: true, storage: "database" }, |
| 31 | account: { accountLinking: { enabled: false } }, |
| 32 | plugins: [biolockSessions()], |
| 33 | }); |
| 34 | } |
| 35 | |
| 36 | function required(name: string) { |
| 37 | const value = process.env[name]?.trim(); |
| 38 | if (!value) throw new Error(`Auth setting ${name} is missing.`); |
| 39 | return value; |
| 40 | } |
| 41 | |
| 42 | export function resourceAuthSettings() { |
| 43 | const { ACCOUNTS_DB } = getCloudflareContext().env as { ACCOUNTS_DB?: AuthDatabase }; |
| 44 | if (!ACCOUNTS_DB) throw new Error("Cloudflare D1 account binding is unavailable."); |
| 45 | const origin = process.env.AIRESOURCE_AUTH_ORIGIN || "https://becomeapro.ai"; |
| 46 | return { db: ACCOUNTS_DB, origin, secret: required("AIRESOURCE_BETTER_AUTH_SECRET") }; |
| 47 | } |
| 48 | |
| 49 | export function resourceAuth() { |
| 50 | const { db, origin, secret } = resourceAuthSettings(); |
| 51 | return createResourceAuth(db, origin, secret); |
| 52 | } |