All files / src/lib auth-context.tsx

100% Statements 104/104
92.98% Branches 53/57
100% Functions 19/19
100% Lines 101/101

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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340                                                                            5x     63x                 63x 27x 27x 25x   17x 17x 17x   17x           17x 19x 17x 1x               1x                 16x       17x   17x 1x 1x       1x 1x                   1x       1x   1x     15x 13x 13x   15x 14x     15x                 8x                   1x                     63x 26x       63x 26x 26x 2x 2x                 11x 2x 1x       26x 26x 26x       63x 63x 50x 4x         3x 3x 3x 3x 3x   3x 3x 1x     3x 1x   1x               1x       2x       1x               1x     3x 3x         50x 50x 50x     63x         5x       5x 1x       4x 4x 4x 4x     4x 3x         3x 2x 2x   3x 2x 2x     3x                   4x     63x       1x     63x 2x 2x 2x   2x 2x                     63x                               66x 66x 2x   63x    
import {
	createContext,
	useContext,
	useState,
	useEffect,
	useCallback,
	useRef,
	type ReactNode,
} from "react";
import { authApi, proApi, type User } from "./api";
import { ApiError } from "./api/base";
import { queryClient } from "./query-client";
 
type AuthState = {
	user: User | null;
	isLoading: boolean;
	isAuthenticated: boolean;
	isAdmin: boolean;
	isSuperAdmin: boolean;
	hasProAccess: boolean;
};
 
type AuthContextType = AuthState & {
	signIn: (
		email: string,
		password: string,
		options?: { skipStateUpdate?: boolean },
	) => Promise<{
		isAdmin: boolean;
		isSuperAdmin: boolean;
		hasProAccess: boolean;
		pendingInvitationToken?: string;
	}>;
	signUp: (email: string, password: string, name: string, termsAccepted?: boolean) => Promise<void>;
	signOut: () => Promise<void>;
	refreshSession: () => Promise<void>;
};
 
const AuthContext = createContext<AuthContextType | null>(null);
 
export function AuthProvider({ children }: { children: ReactNode }) {
	const [state, setState] = useState<AuthState>({
		user: null,
		isLoading: true,
		isAuthenticated: false,
		isAdmin: false,
		isSuperAdmin: false,
		hasProAccess: false,
	});
 
	const refreshSession = useCallback(async () => {
		try {
			const session = await authApi.getSession();
			if (session?.user) {
				// Fetch roles and pro in parallel (instead of serial)
				let isAdmin = false;
				let isSuperAdmin = false;
				let hasProAccess = false;
 
				const [rolesResult, proResult] = await Promise.allSettled([
					proApi.getMyRoles(),
					proApi.getMyPro(),
				]);
 
				// If both calls failed with 401, session is stale — treat as logged out
				const is401 = (r: PromiseSettledResult<unknown>) =>
					r.status === "rejected" && r.reason instanceof ApiError && r.reason.status === 401;
				if (is401(rolesResult) && is401(proResult)) {
					setState({
						user: null,
						isLoading: false,
						isAuthenticated: false,
						isAdmin: false,
						isSuperAdmin: false,
						hasProAccess: false,
					});
					return;
				}
 
				// Issue #581: if the API explicitly reports that this user's pro
				// access has been revoked (e.g. owner deactivated their seat),
				// surface a clear logged-out state with a notice instead of
				// loading an empty dashboard. Skip when the user is a platform
				// admin — they don't need a pro to use the portal.
				const isAccessRevoked =
					proResult.status === "rejected" &&
					proResult.reason instanceof ApiError &&
					proResult.reason.code === "ACCESS_REVOKED";
				const willBeAdmin =
					rolesResult.status === "fulfilled" &&
					!!rolesResult.value.data?.isAdmin;
				if (isAccessRevoked && !willBeAdmin) {
					try {
						await authApi.signOut();
					} catch {
						// best-effort sign-out; we still clear local state below
					}
					queryClient.clear();
					setState({
						user: null,
						isLoading: false,
						isAuthenticated: false,
						isAdmin: false,
						isSuperAdmin: false,
						hasProAccess: false,
					});
					// Redirect to the sign-in page with a clear reason. The auth
					// page maps ?error=access_revoked to a friendly banner.
					Eif (
						typeof window !== "undefined" &&
						!window.location.pathname.startsWith("/auth/")
					) {
						window.location.href = "/auth/sign-in?error=access_revoked";
					}
					return;
				}
 
				if (rolesResult.status === "fulfilled") {
					isAdmin = rolesResult.value.data?.isAdmin ?? false;
					isSuperAdmin = rolesResult.value.data?.isSuperAdmin ?? false;
				}
				if (proResult.status === "fulfilled") {
					hasProAccess = !!proResult.value.data?.proId;
				}
 
				setState({
					user: session.user,
					isLoading: false,
					isAuthenticated: true,
					isAdmin,
					isSuperAdmin,
					hasProAccess,
				});
			} else {
				setState({
					user: null,
					isLoading: false,
					isAuthenticated: false,
					isAdmin: false,
					isSuperAdmin: false,
					hasProAccess: false,
				});
			}
		} catch {
			setState({
				user: null,
				isLoading: false,
				isAuthenticated: false,
				isAdmin: false,
				isSuperAdmin: false,
				hasProAccess: false,
			});
		}
	}, []);
 
	useEffect(() => {
		refreshSession();
	}, [refreshSession]);
 
	// Listen for 401 events dispatched by the query client
	useEffect(() => {
		const guestPaths = ["/login", "/register", "/forgot-password", "/reset-password", "/verify-email", "/accept-invitation", "/auth/sign-in", "/auth/sign-up", "/auth/forgot-password", "/auth/reset-password"];
		const handleSessionExpired = () => {
			queryClient.clear();
			setState({
				user: null,
				isLoading: false,
				isAuthenticated: false,
				isAdmin: false,
				isSuperAdmin: false,
				hasProAccess: false,
			});
			// Only redirect if not already on a guest page (prevents reload loop)
			const isGuestPage = guestPaths.some((p) => window.location.pathname.startsWith(p));
			if (!isGuestPage) {
				window.location.href = "/login";
			}
		};
 
		window.addEventListener("auth:session-expired", handleSessionExpired);
		return () =>
			window.removeEventListener("auth:session-expired", handleSessionExpired);
	}, []);
 
	// Cross-tab session detection: revalidate session when tab becomes visible
	const isValidatingRef = useRef(false);
	useEffect(() => {
		const handleVisibilityChange = async () => {
			if (
				document.visibilityState === "visible" &&
				state.isAuthenticated &&
				!isValidatingRef.current
			) {
				isValidatingRef.current = true;
				const controller = new AbortController();
				const timeout = setTimeout(() => controller.abort(), 5000);
				try {
					const sessionPromise = authApi.getSession();
					// Race the session check against the abort signal
					const abortPromise = new Promise<null>((_, reject) => {
						controller.signal.addEventListener("abort", () =>
							reject(new DOMException("Aborted", "AbortError")),
						);
					});
					const session = await Promise.race([sessionPromise, abortPromise]);
					Eif (!session?.user) {
						// Session expired or logged out from another tab
						setState({
							user: null,
							isLoading: false,
							isAuthenticated: false,
							isAdmin: false,
							isSuperAdmin: false,
							hasProAccess: false,
						});
						window.location.href = "/login";
					}
				} catch (err) {
					// On timeout (AbortError), don't log out — just skip refresh
					if (err instanceof DOMException && err.name === "AbortError") {
						// Timeout — skip validation silently
					} else {
						// Session check failed — treat as expired
						setState({
							user: null,
							isLoading: false,
							isAuthenticated: false,
							isAdmin: false,
							isSuperAdmin: false,
							hasProAccess: false,
						});
						window.location.href = "/login";
					}
				} finally {
					clearTimeout(timeout);
					isValidatingRef.current = false;
				}
			}
		};
 
		document.addEventListener("visibilitychange", handleVisibilityChange);
		return () =>
			document.removeEventListener("visibilitychange", handleVisibilityChange);
	}, [state.isAuthenticated]);
 
	const signIn = async (
		email: string,
		password: string,
		options?: { skipStateUpdate?: boolean },
	) => {
		await authApi.signIn(email, password);
 
		// When skipStateUpdate is true, just authenticate without updating React state.
		// The caller handles navigation and state refresh (e.g., invitation flow).
		if (options?.skipStateUpdate) {
			return { isAdmin: false, isSuperAdmin: false, hasProAccess: false };
		}
 
		// Fetch session, then roles + pro in parallel
		const session = await authApi.getSession();
		let isAdmin = false;
		let isSuperAdmin = false;
		let hasProAccess = false;
		let pendingInvitationToken: string | undefined;
 
		if (session?.user) {
			const [rolesResult, proResult] = await Promise.allSettled([
				proApi.getMyRoles(),
				proApi.getMyPro(),
			]);
 
			if (rolesResult.status === "fulfilled") {
				isAdmin = rolesResult.value.data?.isAdmin ?? false;
				isSuperAdmin = rolesResult.value.data?.isSuperAdmin ?? false;
			}
			if (proResult.status === "fulfilled") {
				hasProAccess = !!proResult.value.data?.proId;
				pendingInvitationToken = proResult.value.data?.pendingInvitation?.token;
			}
 
			setState({
				user: session.user,
				isLoading: false,
				isAuthenticated: true,
				isAdmin,
				isSuperAdmin,
				hasProAccess,
			});
		}
 
		return { isAdmin, isSuperAdmin, hasProAccess, pendingInvitationToken };
	};
 
	const signUp = async (email: string, password: string, name: string, termsAccepted?: boolean) => {
		// Note: We don't set isLoading here because that would cause GuestGuard
		// to show a spinner, which unmounts the RegisterPage and loses its state.
		// The register page manages its own loading state instead.
		await authApi.signUp(email, password, name, termsAccepted);
	};
 
	const signOut = async () => {
		setState((s) => ({ ...s, isLoading: true }));
		try {
			await authApi.signOut();
		} finally {
			queryClient.clear();
			setState({
				user: null,
				isLoading: false,
				isAuthenticated: false,
				isAdmin: false,
				isSuperAdmin: false,
				hasProAccess: false,
			});
		}
	};
 
	return (
		<AuthContext.Provider
			value={{
				...state,
				signIn,
				signUp,
				signOut,
				refreshSession,
			}}
		>
			{children}
		</AuthContext.Provider>
	);
}
 
export function useAuth() {
	const context = useContext(AuthContext);
	if (!context) {
		throw new Error("useAuth must be used within an AuthProvider");
	}
	return context;
}