import { betterAuth } from "better-auth"; import { getCloudflareContext } from "@opennextjs/cloudflare"; interface D1Statement { bind(...values: (string | number)[]): D1Statement; first(): Promise; } export type AuthDatabase = { prepare(query: string): D1Statement; batch(statements: D1Statement[]): Promise; }; export type ProviderIDs = { google: string; apple: string }; export function createResourceAuth(db: AuthDatabase, origin: string, secret: string, providers: ProviderIDs) { return betterAuth({ database: db as NonNullable[0]>["database"], baseURL: origin, appName: "AI Resource Pro", secret, user: { additionalFields: { provider: { type: ["google", "apple"], required: false, input: false }, }, }, advanced: { cookiePrefix: "airesourcepro", ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] } }, rateLimit: { enabled: true, storage: "database" }, account: { accountLinking: { enabled: false }, encryptOAuthTokens: true }, socialProviders: { google: { clientId: providers.google, mapProfileToUser: () => ({ provider: "google" }), }, apple: { clientId: providers.apple, async mapProfileToUser(profile) { if (profile.email || !profile.sub) return { provider: "apple" }; // Reuse only a verified address already bound to this Apple subject. const existing = await db.prepare(` SELECT "user".email FROM "account" JOIN "user" ON "user".id = "account"."userId" WHERE "account"."providerId" = 'apple' AND "account"."accountId" = ? AND "user"."emailVerified" = 1 `).bind(profile.sub).first<{ email: string }>(); return existing ? { provider: "apple", email: existing.email, emailVerified: true } : { provider: "apple" }; }, }, }, }); } function required(name: string) { const value = process.env[name]?.trim(); if (!value) throw new Error(`Auth setting ${name} is missing.`); return value; } export function resourceAuthSettings() { const { ACCOUNTS_DB } = getCloudflareContext().env as { ACCOUNTS_DB?: AuthDatabase }; if (!ACCOUNTS_DB) throw new Error("Cloudflare D1 account binding is unavailable."); const origin = process.env.AIRESOURCE_AUTH_ORIGIN || "https://airesourcepro.com"; const providers = { google: required("AIRESOURCE_GOOGLE_CLIENT_ID"), apple: required("AIRESOURCE_APPLE_CLIENT_ID"), }; return { db: ACCOUNTS_DB, origin, providers, secret: required("AIRESOURCE_BETTER_AUTH_SECRET") }; } export function resourceAuth() { const { db, origin, secret, providers } = resourceAuthSettings(); return createResourceAuth(db, origin, secret, providers); }