Branchwell

Become a Pro / website · becomeapro.ai / src / lib / d1-auth.ts

Raw 2.8 KB on 5069836c1e4c4e369ebe86b13dc7d299c5bed8c0
1import { betterAuth } from "better-auth";
2import { getCloudflareContext } from "@opennextjs/cloudflare";
3
4interface D1Statement {
5 bind(...values: (string | number)[]): D1Statement;
6 first<T = unknown>(): Promise<T | null>;
7}
8export type AuthDatabase = {
9 prepare(query: string): D1Statement;
10 batch(statements: D1Statement[]): Promise<unknown>;
11};
12
13export type ProviderIDs = { google: string; apple: string };
14
15export function createResourceAuth(db: AuthDatabase, origin: string, secret: string, providers: ProviderIDs) {
16 return betterAuth({
17 database: db as NonNullable<Parameters<typeof betterAuth>[0]>["database"],
18 baseURL: origin,
19 appName: "AI Resource Pro",
20 secret,
21 user: {
22 additionalFields: {
23 provider: { type: ["google", "apple"], required: false, input: false },
24 },
25 },
26 advanced: { cookiePrefix: "airesourcepro", ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] } },
27 rateLimit: { enabled: true, storage: "database" },
28 account: { accountLinking: { enabled: false }, encryptOAuthTokens: true },
29 socialProviders: {
30 google: {
31 clientId: providers.google,
32 mapProfileToUser: () => ({ provider: "google" }),
33 },
34 apple: {
35 clientId: providers.apple,
36 async mapProfileToUser(profile) {
37 if (profile.email || !profile.sub) return { provider: "apple" };
38 // Reuse only a verified address already bound to this Apple subject.
39 const existing = await db.prepare(`
40 SELECT "user".email FROM "account"
41 JOIN "user" ON "user".id = "account"."userId"
42 WHERE "account"."providerId" = 'apple' AND "account"."accountId" = ?
43 AND "user"."emailVerified" = 1
44 `).bind(profile.sub).first<{ email: string }>();
45 return existing
46 ? { provider: "apple", email: existing.email, emailVerified: true }
47 : { provider: "apple" };
48 },
49 },
50 },
51 });
52}
53
54function required(name: string) {
55 const value = process.env[name]?.trim();
56 if (!value) throw new Error(`Auth setting ${name} is missing.`);
57 return value;
58}
59
60export function resourceAuthSettings() {
61 const { ACCOUNTS_DB } = getCloudflareContext().env as { ACCOUNTS_DB?: AuthDatabase };
62 if (!ACCOUNTS_DB) throw new Error("Cloudflare D1 account binding is unavailable.");
63 const origin = process.env.AIRESOURCE_AUTH_ORIGIN || "https://airesourcepro.com";
64 const providers = {
65 google: required("AIRESOURCE_GOOGLE_CLIENT_ID"),
66 apple: required("AIRESOURCE_APPLE_CLIENT_ID"),
67 };
68 return { db: ACCOUNTS_DB, origin, providers, secret: required("AIRESOURCE_BETTER_AUTH_SECRET") };
69}
70
71export function resourceAuth() {
72 const { db, origin, secret, providers } = resourceAuthSettings();
73 return createResourceAuth(db, origin, secret, providers);
74}