All files / src shared-auth-impl.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                           
import { logger } from "@snapback/infrastructure";
import { type BetterAuthAdapter, betterAuthAdapter } from "./better-auth-adapter";
import { AuthError, InsufficientRoleError, InsufficientScopesError } from "./errors";
import { mapUserToPlan } from "./plan";
import type { SnapbackAuth, SnapbackAuthContext, UserRole } from "./shared-auth";
 
export class SnapbackAuthImpl implements SnapbackAuth {
	constructor(private adapter: BetterAuthAdapter = betterAuthAdapter) {}
 
	async getContextFromRequest(req: Request): Promise<SnapbackAuthContext | null> {
		// Debug: Log incoming headers for auth debugging
		const cookieHeader = req.headers.get("cookie");
		const authHeader = req.headers.get("authorization");
		logger.info("[snapbackAuth] getContextFromRequest called", {
			url: req.url,
			hasCookie: !!cookieHeader,
			hasAuthHeader: !!authHeader,
			cookiePreview: cookieHeader?.substring(0, 100),
		});
 
		// 1) x-auth-context header (pre-injected, e.g. from middleware)
		const injected = req.headers.get("x-auth-context");
		if (injected) {
			try {
				logger.info("[snapbackAuth] Using injected x-auth-context header");
				return JSON.parse(injected) as SnapbackAuthContext;
			} catch {
				// ignore and fall through
			}
		}
 
		// 2) Session via cookies
		const richSession = await this.adapter.getRichSessionFromHeaders(req.headers);
		logger.info("[snapbackAuth] getRichSessionFromHeaders result", {
			hasSession: !!richSession?.session,
			hasUser: !!richSession?.user,
			sessionId: richSession?.session?.id,
			userId: richSession?.user?.id,
		});
		if (richSession?.session && richSession?.user) {
			return this.fromSession(richSession, "session");
		}
 
		// 3) Authorization: Bearer <token>
		if (authHeader?.startsWith("Bearer ")) {
			const token = authHeader.slice(7);
 
			// 3a) Try API key first
			const keyResult = await this.adapter.verifyApiKeyOrNull(token);
			if (keyResult) {
				return this.fromApiKey(keyResult);
			}
 
			// 3b) Try access token
			const tokenRichSession = await this.adapter.getRichSessionFromHeaders(
				new Headers({ Authorization: `Bearer ${token}` }),
			);
			if (tokenRichSession?.session && tokenRichSession?.user) {
				return this.fromSession(tokenRichSession, "accessToken");
			}
		}
 
		// 4) x-api-key header
		const apiKeyHeader = req.headers.get("x-api-key");
		if (apiKeyHeader) {
			const keyResult = await this.adapter.verifyApiKeyOrNull(apiKeyHeader);
			if (keyResult) {
				return this.fromApiKey(keyResult);
			}
		}
 
		return null;
	}
 
	async requireAuth(req: Request, options?: { roles?: UserRole[]; scopes?: string[] }): Promise<SnapbackAuthContext> {
		const ctx = await this.getContextFromRequest(req);
 
		if (!ctx) {
			throw new AuthError("Authentication required", 401, "UNAUTHENTICATED");
		}
 
		if (options?.roles && !options.roles.includes(ctx.role)) {
			throw new InsufficientRoleError(options.roles, ctx.role);
		}
 
		if (options?.scopes) {
			const scopes = ctx.apiKeyScopes ?? [];
			const hasAll = options.scopes.every((s) => scopes.includes(s));
			if (!hasAll) {
				throw new InsufficientScopesError(options.scopes, scopes);
			}
		}
 
		return ctx;
	}
 
	async getOrganizationContext(ctx: SnapbackAuthContext) {
		if (!ctx.orgId) {
			return null;
		}
 
		const org = await this.adapter.getOrganization(ctx.orgId);
 
		if (!org) {
			return null;
		}
 
		return {
			id: org.id,
			name: org.name,
			slug: org.slug,
			role: ctx.orgRole ?? "member",
		};
	}
 
	// ---------- mapping helpers ----------
 
	private async enrichOrgRole(userId: string, orgId?: string): Promise<"owner" | "admin" | "member" | undefined> {
		if (!orgId) {
			return undefined;
		}
 
		const membership = await this.adapter.getOrgMembership(userId, orgId);
 
		return membership?.role;
	}
 
	private async fromSession(
		sessionResult: { session: any; user: any },
		via: SnapbackAuthContext["authenticatedVia"],
	): Promise<SnapbackAuthContext> {
		const { session, user } = sessionResult;
		const plan = mapUserToPlan(user);
		const orgId = session.organizationId ?? undefined;
		const orgRole = await this.enrichOrgRole(user.id, orgId);
 
		// Get enriched auth state with error handling
		// Guard: Only call adapter methods if user.id is a valid string
		const hasValidUserId = user?.id && typeof user.id === "string";
 
		// ✅ FIX: Use user properties directly from the already-fetched session result.
		// Previously called adapter.isEmailVerified/isTwoFactorEnabled which internally
		// call auth.api.getUser (admin endpoint) without credentials → 401 UNAUTHORIZED.
		// Better Auth's getSession already returns these fields on the user object.
		const emailVerified = user?.emailVerified ?? false;
		const twoFactorEnabled = user?.twoFactorEnabled ?? false;
 
		// hasPasskey still needs a separate lookup (not included in getSession)
		const passkeyRegistered = hasValidUserId ? await this.adapter.hasPasskey(user.id).catch(() => false) : false;
 
		return {
			userId: user.id,
			email: user.email,
			role: (user.role as UserRole) ?? "user",
			orgId,
			orgRole,
			sessionId: session.id,
			expiresAt: new Date(session.expiresAt),
			authenticatedVia: via,
			plan,
			emailVerified,
			twoFactorEnabled,
			passkeyRegistered,
		};
	}
 
	private async fromApiKey(result: any): Promise<SnapbackAuthContext> {
		const plan = mapUserToPlan(result.user);
		const orgId = result.session.organizationId ?? undefined;
		const orgRole = await this.enrichOrgRole(result.user.id, orgId);
 
		// For API keys, we can check email verification but 2FA and passkey status are not essential
		// Guard: Only call adapter if user.id is a valid string
		const hasValidUserId = result?.user?.id && typeof result.user.id === "string";
		const emailVerified = hasValidUserId
			? await this.adapter.isEmailVerified(result.user.id).catch(() => undefined)
			: undefined;
 
		return {
			userId: result.user.id,
			email: result.user.email,
			role: (result.user.role as UserRole) ?? "user",
			orgId,
			orgRole,
			authenticatedVia: "apiKey",
			apiKeyId: result.apiKey.id,
			apiKeyScopes: result.apiKey.scopes ?? [],
			sessionId: result.session.id,
			expiresAt: new Date(result.session.expiresAt),
			plan,
			emailVerified,
			// twoFactorEnabled and passkeyRegistered remain undefined for API key auth
		};
	}
}
 
export const snapbackAuth = new SnapbackAuthImpl();