All files / src better-auth-adapter.ts

0% Statements 0/132
0% Branches 0/1
0% Functions 0/1
0% Lines 0/132

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                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { logger } from "@snapback/infrastructure";
import type { Session } from "better-auth/types";
import { auth } from "./auth";
 
/**
 * Adapter for Better Auth API calls to provide a stable interface
 * and avoid direct dependencies on Better Auth internals in our implementation
 *
 * Note: Type assertions are used for plugin APIs (organization, passkey, apiKey)
 * because Better Auth's InferAPI doesn't always correctly infer plugin types.
 * See: https://www.better-auth.com/docs/concepts/typescript
 */
 
// Type-safe access to auth API with plugin methods
// Better Auth's InferAPI doesn't properly expose plugin APIs in all cases
const api = auth.api as typeof auth.api & {
	verifyApiKey?: (params: { key: string }) => Promise<any>;
	getUser?: (params: { query: { id: string } }) => Promise<any>;
	organization?: {
		get?: (params: { organizationId: string }) => Promise<any>;
		getMembership?: (params: { userId: string; organizationId: string }) => Promise<any>;
	};
	passkey?: {
		listPasskeys?: (params: { userId: string }) => Promise<any[]>;
	};
};
 
export interface BetterAuthAdapter {
	getSessionFromHeaders(headers: Headers): Promise<Session | null>;
	verifyApiKeyOrNull(key: string): Promise<any | null>;
	getOrganization(organizationId: string): Promise<any | null>;
	getOrgMembership(userId: string, organizationId: string): Promise<any | null>;
 
	/**
	 * Returns a session + user object with any enriched flags that Better Auth
	 * already exposes (emailVerified, two-factor enabled, etc).
	 */
	getRichSessionFromHeaders(headers: Headers): Promise<{
		session: any | null;
		user: any | null;
	}>;
 
	/**
	 * Returns whether email is verified for the user id.
	 * Implement using existing Better Auth user data shape.
	 */
	isEmailVerified(userId: string): Promise<boolean>;
 
	/**
	 * Returns whether 2FA is enabled for the user id.
	 * Implement using the twoFactor plugin tables/API.
	 */
	isTwoFactorEnabled(userId: string): Promise<boolean>;
 
	/**
	 * Returns whether at least one passkey is registered for the user id.
	 * Implement using the passkey plugin.
	 */
	hasPasskey(userId: string): Promise<boolean>;
}
 
export const betterAuthAdapter: BetterAuthAdapter = {
	async getSessionFromHeaders(headers: Headers): Promise<Session | null> {
		try {
			const result = await api.getSession({ headers });
			// Better Auth returns { session, user } - extract session
			return (result as any)?.session || null;
		} catch (error) {
			console.error("[BetterAuthAdapter] getSessionFromHeaders error:", error);
			return null;
		}
	},
 
	async verifyApiKeyOrNull(key: string): Promise<any | null> {
		try {
			// Using the verified public method from Better Auth docs
			if (!api.verifyApiKey) {
				return null;
			}
			return await api.verifyApiKey({ key });
		} catch (error) {
			console.error("[BetterAuthAdapter] verifyApiKeyOrNull error:", error);
			return null;
		}
	},
 
	// Organization methods - only if actually needed
	async getOrganization(organizationId: string) {
		if (!api.organization?.get) {
			return null;
		}
 
		try {
			return await api.organization.get({ organizationId });
		} catch (error) {
			console.error("[BetterAuthAdapter] getOrganization error:", error);
			return null;
		}
	},
 
	async getOrgMembership(userId: string, organizationId: string) {
		if (!api.organization?.getMembership) {
			return null;
		}
 
		try {
			return await api.organization.getMembership({
				userId,
				organizationId,
			});
		} catch (error) {
			console.error("[BetterAuthAdapter] getOrgMembership error:", error);
			return null;
		}
	},
 
	async getRichSessionFromHeaders(headers: Headers): Promise<{
		session: any | null;
		user: any | null;
	}> {
		// Debug: Log cookie names
		const cookieNames: string[] = [];
		headers.forEach((value, key) => {
			if (key.toLowerCase() === "cookie") {
				// Extract individual cookie names
				const cookies = value.split(";").map((c) => c.trim().split("=")[0]);
				cookieNames.push(...cookies);
			}
		});
		logger.info("[BetterAuthAdapter] getRichSessionFromHeaders called", {
			cookieNames,
			headerCount: Array.from(headers.entries()).length,
		});
 
		try {
			const result = await api.getSession({ headers });
 
			// Better Auth returns { session, user } object
			const sessionData = result as any;
			logger.info("[BetterAuthAdapter] getSession result", {
				hasSession: !!sessionData?.session,
				hasUser: !!sessionData?.user,
				sessionId: sessionData?.session?.id,
				userId: sessionData?.user?.id,
				fullResult: JSON.stringify(sessionData).substring(0, 500),
			});
			return {
				session: sessionData?.session || null,
				user: sessionData?.user || null,
			};
		} catch (error) {
			logger.error(
				"[BetterAuthAdapter] getRichSessionFromHeaders error:",
				error instanceof Error
					? { message: error.message, stack: error.stack, name: error.name }
					: String(error),
			);
			return {
				session: null,
				user: null,
			};
		}
	},
 
	async isEmailVerified(userId: string): Promise<boolean> {
		// Guard against undefined/invalid userId
		if (!userId || typeof userId !== "string") {
			return false;
		}
 
		try {
			// Get user directly from Better Auth API
			if (!api.getUser) {
				return false;
			}
			const user = await api.getUser({ query: { id: userId } });
			return user?.emailVerified ?? false;
		} catch (error) {
			console.error("[BetterAuthAdapter] isEmailVerified error:", error);
			return false;
		}
	},
 
	async isTwoFactorEnabled(userId: string): Promise<boolean> {
		// Guard against undefined/invalid userId
		if (!userId || typeof userId !== "string") {
			return false;
		}
 
		try {
			// Check if user has two-factor enabled using Better Auth's twoFactor plugin
			if (!api.getUser) {
				return false;
			}
			const user = await api.getUser({ query: { id: userId } });
			return user?.twoFactorEnabled ?? false;
		} catch (error) {
			console.error("[BetterAuthAdapter] isTwoFactorEnabled error:", error);
			return false;
		}
	},
 
	async hasPasskey(userId: string): Promise<boolean> {
		try {
			// Check if user has any passkeys registered using Better Auth's passkey plugin
			if (!api.passkey?.listPasskeys) {
				return false;
			}
 
			const passkeys = await api.passkey.listPasskeys({ userId });
			return Array.isArray(passkeys) && passkeys.length > 0;
		} catch (error) {
			console.error("[BetterAuthAdapter] hasPasskey error:", error);
			return false;
		}
	},
};