All files / lib homeowner-auth.ts

57.14% Statements 20/35
60% Branches 24/40
57.14% Functions 4/7
55.88% Lines 19/34

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                1x 1x           20x 1x       19x 19x 31x     19x 2x   19x 3x           19x                                                                               1x     1x                                                                                                                                                   20x 20x   20x       34x 34x        
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 { 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 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,
		},
		session: {
			expiresIn: 60 * 60 * 24 * 30, // 30 days
			updateAge: 60 * 60 * 24, // Update session on daily activity
		},
		databaseHooks: {
			user: {
				create: {
					// Fires for email/password signup AND phone-OTP signup
					// (signUpOnVerification path). Best-effort, never throws.
					after: async (user: {
						id: string;
						name: string;
						email: string;
						phoneNumber?: string | null;
					}) => {
						const { handleHomeownerCreated } = await import(
							"./internal-notifications"
						);
						await handleHomeownerCreated(env, db, user);
					},
				},
			},
		},
		plugins: [
			phoneNumber({
				sendOTP: async ({ phoneNumber: phone, code }, _request) => {
					// Same WhatsApp delivery helper as pro auth. Logs to the
					// notificationDeliveryLog table for observability.
					const { sendWhatsAppOtp } = await import(
						"./communication/whatsapp-otp"
					);
					const { createDal } = await import("../dal");
					const dal = createDal(db);
					let deliveryErr: unknown;
					let deliveryResult:
						| { actualRecipient: string; provider: string }
						| undefined;
					try {
						deliveryResult = await sendWhatsAppOtp(env, phone, code, dal);
					} catch (err) {
						deliveryErr = err;
						console.error("[HO-AUTH] WhatsApp OTP failed:", err);
					}
					try {
						const { notificationDeliveryLog } = await import(
							"../db/schema/notifications"
						);
						await db.insert(notificationDeliveryLog).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;
}
 
export function _resetHoAuthCache(): void {
	_cachedHoAuth = null;
	_cachedHoEnvSecret = null;
}
 
export type HomeownerAuth = ReturnType<typeof createHomeownerAuth>;