All files / src/lib/api auth.ts

97.26% Statements 71/73
98.14% Branches 53/54
100% Functions 24/24
97.26% Lines 71/73

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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                      40x 40x                                                       94x   5x                     5x 5x 2x           3x       5x               5x 5x 5x       5x 3x           2x       3x         3x       3x     3x         3x       5x                 5x 5x 2x           3x         4x           4x 4x 1x   3x                 4x           4x 1x   3x           3x           5x                     5x 5x 2x           3x       4x           4x 4x 2x           2x       1x                     2x                   1x             1x           2x             4x       4x 1x   3x 3x       1x             4x                 4x 4x 2x           2x       4x                       4x 4x 2x           2x       1x             1x                         1x             1x                         2x            
// Auth API - Better Auth returns raw responses, not wrapped in our standard format
import {
	API_BASE_URL,
	ApiError,
	GENERIC_ERROR_MESSAGE,
	request,
	uploadFile,
} from "./base";
 
/** Safely parse JSON from a response, throwing ApiError on failure */
async function safeJson(response: Response): Promise<unknown> {
	try {
		return await response.json();
	} catch (err) {
		console.error("Failed to parse response JSON:", err);
		throw new ApiError("PARSE_ERROR", GENERIC_ERROR_MESSAGE, response.status);
	}
}
 
// Auth Types
export type User = {
	id: string;
	name: string;
	email: string;
	emailVerified: boolean;
	image?: string;
	phoneNumber?: string;
	createdAt: string;
	updatedAt: string;
	termsAcceptedAt: string | null;
	termsVersion: string | null;
};
 
export type Session = {
	id: string;
	userId: string;
	token: string;
	expiresAt: string;
};
 
export const authApi = {
	async signUp(email: string, password: string, name: string, termsAccepted?: boolean) {
		const response = await fetch(`${API_BASE_URL}/api/auth/sign-up/email`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
			body: JSON.stringify({
				email,
				password,
				name,
				terms_accepted: termsAccepted || false,
			}),
		});
		const data = (await safeJson(response)) as Record<string, string>;
		if (!response.ok) {
			throw new ApiError(
				data?.code || "AUTH_ERROR",
				data?.message || "Sign up failed",
				response.status,
			);
		}
		return data;
	},
 
	async signIn(email: string, password: string) {
		const response = await fetch(`${API_BASE_URL}/api/auth/sign-in/email`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
			body: JSON.stringify({ email, password }),
		});
		// Parse JSON inline with auth-specific fallback (safeJson uses
		// GENERIC_ERROR_MESSAGE which is too harsh for login failures)
		let data: Record<string, string> | null = null;
		try {
			data = (await response.json()) as Record<string, string>;
		} catch {
			// Non-JSON response — handled below
		}
		if (!response.ok) {
			throw new ApiError(
				data?.code || "AUTH_ERROR",
				data?.message || "Invalid email or password",
				response.status,
			);
		}
		return data as Record<string, string>;
	},
 
	async signOut() {
		const response = await fetch(`${API_BASE_URL}/api/auth/sign-out`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
		});
		return response.ok;
	},
 
	async getSession(): Promise<{ user: User; session: Session } | null> {
		const response = await fetch(`${API_BASE_URL}/api/auth/get-session`, {
			credentials: "include",
		});
		const data = (await safeJson(response)) as {
			user: User;
			session: Session;
		} | null;
		// Better Auth returns null when no session, or {user, session} when authenticated
		return data;
	},
 
	async forgotPassword(email: string) {
		const response = await fetch(`${API_BASE_URL}/api/auth/request-password-reset`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
			body: JSON.stringify({
				email,
				redirectTo: `${window.location.origin}/reset-password`,
			}),
		});
		const data = (await safeJson(response)) as Record<string, string>;
		if (!response.ok) {
			throw new ApiError(
				data?.code || "AUTH_ERROR",
				data?.message || "Failed to send reset email",
				response.status,
			);
		}
		return data;
	},
 
	// Check if a phone number is registered
	async checkPhone(phoneNumber: string): Promise<{ exists: boolean }> {
		const response = await fetch(`${API_BASE_URL}/api/auth/check-phone`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
			body: JSON.stringify({ phoneNumber }),
		});
		const data = (await safeJson(response)) as { exists: boolean; error?: string };
		if (!response.ok) {
			throw new ApiError("CHECK_PHONE_ERROR", data?.error || GENERIC_ERROR_MESSAGE, response.status);
		}
		return data;
	},
 
	// Design tradeoff: This endpoint reveals whether an email is registered, which
	// improves UX (directs existing users to login) but enables email enumeration.
	// Acceptable for this B2B marketplace; rate-limit in production if needed.
	async checkEmail(
		email: string,
	): Promise<{ exists: boolean; verified: boolean; proName?: string; provider?: string }> {
		const response = await fetch(`${API_BASE_URL}/api/auth/check-email`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
			body: JSON.stringify({ email }),
		});
		if (!response.ok) {
			throw new ApiError("CHECK_EMAIL_ERROR", GENERIC_ERROR_MESSAGE, response.status);
		}
		const data = (await safeJson(response)) as {
			exists: boolean;
			verified: boolean;
			proName?: string;
			provider?: string;
		};
		return data;
	},
 
	async resendVerification(email: string) {
		// Omit credentials — after sign-up the user has an unverified session cookie.
		// Sending it causes Better Auth to return EMAIL_MISMATCH (400).
		const response = await fetch(
			`${API_BASE_URL}/api/auth/send-verification-email`,
			{
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({
					email,
					callbackURL: `${window.location.origin}/verify-email`,
				}),
			},
		);
		const data = (await safeJson(response)) as Record<string, string>;
		if (!response.ok) {
			throw new ApiError(
				data?.code || "AUTH_ERROR",
				data?.message || "Failed to send verification email",
				response.status,
			);
		}
		return data;
	},
 
	async resetPassword(token: string, newPassword: string) {
		const response = await fetch(`${API_BASE_URL}/api/auth/reset-password`, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "include",
			body: JSON.stringify({ token, newPassword }),
		});
		const data = (await safeJson(response)) as Record<string, string>;
		if (!response.ok) {
			throw new ApiError(
				data?.code || "AUTH_ERROR",
				data?.message || "Failed to reset password",
				response.status,
			);
		}
		return data;
	},
 
	async getProfile() {
		return request<{
			id: string;
			name: string;
			email: string;
			phoneNumber: string | null;
			image: string | null;
			themePreference: string | null;
		}>("/api/user/me");
	},
 
	async updateProfile(data: { name?: string; phoneNumber?: string | null }) {
		return request<{
			id: string;
			name: string;
			email: string;
			phoneNumber: string | null;
			image: string | null;
		}>("/api/user/me", { method: "PUT", body: data });
	},
 
	async uploadAvatar(file: File) {
		return uploadFile<{ path: string; url: string }>(
			"/api/user/me/avatar",
			file,
		);
	},
 
	async removeAvatar() {
		return request<{ message: string }>("/api/user/me/avatar", {
			method: "DELETE",
		});
	},
 
	async updatePreferences(data: { themePreference: string }) {
		return request<{ themePreference: string | null }>(
			"/api/user/me/preferences",
			{ method: "PUT", body: data },
		);
	},
 
	async listAccounts(): Promise<{ providerId: string; accountId: string }[]> {
		const response = await fetch(
			`${API_BASE_URL}/api/auth/list-accounts`,
			{ credentials: "include" },
		);
		if (!response.ok) {
			throw new ApiError("AUTH_ERROR", "Failed to fetch account details", response.status);
		}
		const data = (await safeJson(response)) as { providerId: string; accountId: string }[] | null;
		return data || [];
	},
 
	async setPassword(newPassword: string) {
		return request<{ status: boolean }>("/api/user/me/set-password", {
			method: "POST",
			body: { newPassword },
		});
	},
 
	async changePassword(currentPassword: string, newPassword: string) {
		const response = await fetch(
			`${API_BASE_URL}/api/auth/change-password`,
			{
				method: "POST",
				headers: { "Content-Type": "application/json" },
				credentials: "include",
				body: JSON.stringify({ currentPassword, newPassword }),
			},
		);
		const data = (await safeJson(response)) as Record<string, string>;
		if (!response.ok) {
			throw new ApiError(
				data?.code || "AUTH_ERROR",
				data?.message || "Failed to change password",
				response.status,
			);
		}
		return data;
	},
 
	async changeEmail(newEmail: string) {
		const response = await fetch(
			`${API_BASE_URL}/api/auth/change-email`,
			{
				method: "POST",
				headers: { "Content-Type": "application/json" },
				credentials: "include",
				body: JSON.stringify({
					newEmail,
					callbackURL: `${window.location.origin}/verify-email`,
				}),
			},
		);
		const data = (await safeJson(response)) as Record<string, unknown>;
		if (!response.ok) {
			throw new ApiError(
				(data?.code as string) || "AUTH_ERROR",
				(data?.message as string) || "Failed to change email",
				response.status,
			);
		}
		return data;
	},
 
	async sendPhoneChangeOtp(phoneNumber: string) {
		return request<{ message: string }>("/api/user/me/change-phone", {
			method: "POST",
			body: { phoneNumber },
		});
	},
 
	async verifyPhoneChange(phoneNumber: string, code: string) {
		return request<{
			id: string;
			name: string;
			email: string;
			phoneNumber: string | null;
			image: string | null;
		}>("/api/user/me/change-phone/verify", {
			method: "POST",
			body: { phoneNumber, code },
		});
	},
 
	async sendEmailChangeOtp(email: string) {
		return request<{ message: string }>("/api/user/me/change-email", {
			method: "POST",
			body: { email },
		});
	},
 
	async verifyEmailChange(email: string, code: string) {
		return request<{
			id: string;
			name: string;
			email: string;
			phoneNumber: string | null;
			image: string | null;
		}>("/api/user/me/change-email/verify", {
			method: "POST",
			body: { email, code },
		});
	},
 
	async acceptTerms(termsVersion: string) {
		return request<{ success: true }>("/api/auth/accept-terms", {
			method: "PATCH",
			body: { terms_version: termsVersion },
		});
	},
};