All files / lib homeowner-auth.ts

34.54% Statements 19/55
59.18% Branches 29/49
33.33% Functions 3/9
33.96% Lines 18/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250                    1x 1x           23x 1x       22x 22x 37x     22x 2x   22x 3x             22x   23x                                                                                                                                                                                                                                                                                                                                                                           23x 23x   23x                                     40x 40x        
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { phoneNumber } from "better-auth/plugins";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import { hashPassword, verifyPassword } from "./password";
import { getOAuthClientIds } from "./env-config";
import { phoneToTempEmailLocalPart } from "./auth-helpers";
 
// Module-level cache for homeowner auth instance
let _cachedHoAuth: ReturnType<typeof betterAuth> | null = null;
let _cachedHoEnvSecret: string | null = null;
 
export function createHomeownerAuth(
	db: DrizzleD1Database<typeof schema>,
	env: CloudflareBindings,
) {
	if (_cachedHoAuth && _cachedHoEnvSecret === env.BETTER_AUTH_SECRET) {
		return _cachedHoAuth;
	}
 
	// Build trusted origins: marketplace domains + localhost for dev
	const trustedOrigins: string[] = [];
	if (env.ALLOWED_ORIGINS) {
		trustedOrigins.push(...env.ALLOWED_ORIGINS.split(",").map((o) => o.trim()));
	}
	// Marketplace origins (where homeowners interact)
	if (env.MARKETPLACE_URL) {
		trustedOrigins.push(env.MARKETPLACE_URL);
	}
	if (!env.ALLOWED_ORIGINS || env.ALLOWED_ORIGINS === "") {
		trustedOrigins.push(
			env.MARKETPLACE_URL || "http://localhost:8003",
			env.API_URL || env.BETTER_AUTH_URL || "http://localhost:8001",
		);
	}
 
	const marketplaceOrigin =
		env.MARKETPLACE_URL || trustedOrigins[0] || "http://localhost:8003";
 
	const auth = betterAuth({
		database: drizzleAdapter(db, {
			provider: "sqlite",
			schema: {
				user: schema.hoUsers,
				session: schema.hoSessions,
				account: schema.hoAccounts,
				verification: schema.hoVerifications,
			},
		}),
		secret: env.BETTER_AUTH_SECRET,
		baseURL: env.BETTER_AUTH_URL,
		basePath: "/api/homeowner/auth",
		trustedOrigins,
		advanced: {
			cookiePrefix: "ho",
			crossSubDomainCookies: (env.MARKETPLACE_URL && !new URL(env.MARKETPLACE_URL).hostname.includes('localhost'))
				? {
						enabled: true,
						domain: `.${new URL(env.MARKETPLACE_URL).hostname.split(".").slice(-2).join(".")}`,
					}
				: undefined,
		},
		account: {
			accountLinking: {
				enabled: true,
				trustedProviders: ["google", "facebook"],
			},
			// Better Auth defaults give the OAuth state cookie a 5-minute
			// maxAge while the DB verification row lives for 10 minutes
			// (better-auth 1.6.9 state.mjs:47 / oauth2/state.mjs:17). Users
			// who linger on Google's consent screen, hit 2FA, or use an
			// in-app browser that drops the cookie all land on
			// `?error=state_mismatch` even though the DB row is still valid.
			// Skipping the cookie defense-in-depth check keeps the DB-backed
			// state (32-char crypto random, single-use, 10-min TTL) as the
			// sole validator. PKCE still protects against code interception.
			skipStateCookieCheck: true,
		},
		emailAndPassword: {
			enabled: true,
			requireEmailVerification: false,
			minPasswordLength: 8,
			password: {
				hash: hashPassword,
				verify: verifyPassword,
			},
			sendResetPassword: async ({ user, url }) => {
				try {
					const resetUrl = transformToMarketplaceUrl(url, marketplaceOrigin, "reset-password");
					const { CommunicationGateway } = await import("./communication/gateway");
					const { createDal } = await import("../dal");
					const dal = createDal(db);
					const gateway = new CommunicationGateway(dal, env);
					await gateway.send({
						channel: "email",
						recipient: user.email,
						eventType: "password_reset",
						transactional: true,
						content: {
							template: "password-reset",
							subject: "Reset your Interioring password",
							props: { resetLink: resetUrl, userName: user.name },
						},
					});
				} catch (err) {
					console.error("[HO-AUTH] Failed to send password reset:", err);
				}
			},
		},
		emailVerification: {
			sendVerificationEmail: async ({ user, url }) => {
				try {
					const verifyUrl = transformToMarketplaceUrl(url, marketplaceOrigin, "verify-email");
					const { CommunicationGateway } = await import("./communication/gateway");
					const { createDal } = await import("../dal");
					const dal = createDal(db);
					const gateway = new CommunicationGateway(dal, env);
					await gateway.send({
						channel: "email",
						recipient: user.email,
						eventType: "email_verification",
						transactional: true,
						content: {
							template: "email-verification",
							subject: "Welcome to Interioring! Verify your email",
							props: { verificationLink: verifyUrl, userName: user.name },
						},
					});
				} catch (err) {
					console.error("[HO-AUTH] Failed to send verification email:", err);
				}
			},
			sendOnSignUp: true,
			autoSignInAfterVerification: true,
		},
		session: {
			expiresIn: 60 * 60 * 24 * 30, // 30 days
			updateAge: 60 * 60 * 24, // Update session on daily activity
		},
		socialProviders: {
			...(env.GOOGLE_CLIENT_SECRET
				? {
						google: {
							clientId: getOAuthClientIds().google,
							clientSecret: env.GOOGLE_CLIENT_SECRET,
							prompt: "select_account",
						},
					}
				: {}),
			...(env.FACEBOOK_APP_SECRET
				? {
						facebook: {
							clientId: getOAuthClientIds().facebook,
							clientSecret: env.FACEBOOK_APP_SECRET,
						},
					}
				: {}),
		},
		plugins: [
			phoneNumber({
				sendOTP: async ({ phoneNumber: phone, code }, _request) => {
					// Same WhatsApp delivery helper as pro auth. Logs to the
					// communicationLog table for observability.
					const { sendWhatsAppOtp } = await import("./communication/whatsapp-otp");
					let deliveryErr: unknown;
					let deliveryResult:
						| { actualRecipient: string; provider: string }
						| undefined;
					try {
						deliveryResult = await sendWhatsAppOtp(env, phone, code);
					} catch (err) {
						deliveryErr = err;
						console.error("[HO-AUTH] WhatsApp OTP failed:", err);
					}
					try {
						const { communicationLog } = await import(
							"../db/schema/notifications"
						);
						await db.insert(communicationLog).values({
							channel: "whatsapp",
							recipient: phone,
							actualRecipient: deliveryResult?.actualRecipient ?? phone,
							eventType: "otp_verification",
							status: deliveryErr ? "failed" : "sent",
							provider: deliveryResult?.provider ?? "whatsapp_cloud_api",
							environment: env.ENVIRONMENT ?? "local",
							transactional: true,
							contentSummary: JSON.stringify({ codeLength: code.length }),
							previewText: `Your verification code is ${code}`,
							errorMessage:
								deliveryErr instanceof Error
									? deliveryErr.message
									: deliveryErr
										? "WhatsApp OTP delivery failed"
										: undefined,
						});
					} catch (logErr) {
						console.error("[HO-AUTH] OTP log failed:", logErr);
					}
					if (deliveryErr) {
						throw deliveryErr;
					}
				},
				signUpOnVerification: {
					// Temp email distinguishes homeowner phone-signups from pro
					// phone-signups in the email column.
					getTempEmail: (phone: string) =>
						`${phoneToTempEmailLocalPart(phone)}@phone.homeowner.interioring.com`,
					getTempName: (_phone: string) => "New Homeowner",
				},
				otpLength: 6,
				expiresIn: 300,
			}),
		],
		// Relaxed rate limits in dev/local
		rateLimit:
			!env.ENVIRONMENT || env.ENVIRONMENT === "local" || env.ENVIRONMENT === "dev"
				? { window: 10, max: 200 }
				: undefined,
	});
 
	_cachedHoAuth = auth as unknown as ReturnType<typeof betterAuth>;
	_cachedHoEnvSecret = env.BETTER_AUTH_SECRET;
 
	return _cachedHoAuth;
}
 
function transformToMarketplaceUrl(
	apiUrl: string,
	marketplaceOrigin: string,
	type: "verify-email" | "reset-password",
): string {
	try {
		const url = new URL(apiUrl);
		const token = url.searchParams.get("token");
		if (!token) return apiUrl;
		return `${marketplaceOrigin}/account/${type}?token=${encodeURIComponent(token)}`;
	} catch {
		return apiUrl;
	}
}
 
export function _resetHoAuthCache(): void {
	_cachedHoAuth = null;
	_cachedHoEnvSecret = null;
}
 
export type HomeownerAuth = ReturnType<typeof createHomeownerAuth>;