All files / src/components/auth PasswordForm.tsx

98.44% Statements 127/129
93.42% Branches 142/152
100% Functions 21/21
100% Lines 116/116

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                3x         2x 2x                 284x 284x   284x 284x 284x 284x 284x 284x 284x 284x     284x 284x 284x     284x 284x 284x   284x 284x   284x         284x         284x   284x       284x     284x 3x 3x 3x 30x 30x 1x 1x 1x   29x           284x 54x 54x         284x 3x 2x 2x 2x 2x 1x   1x   1x   2x       284x 46x 46x 46x 46x 46x   46x 45x 42x   41x 1x 1x     40x 1x       39x   39x 39x 39x 10x 10x 4x 1x 3x 1x 2x 1x   1x 1x   4x     6x 4x   29x   7x 7x 7x 1x 6x 1x 5x 1x   4x         21x     21x       21x 2x 2x 19x   18x 18x 18x 3x 3x   15x     1x   1x             36x         284x 8x                                             276x                     13x 2x                                 35x 3x                               44x 1x                                   15x 2x                                                                                                                                          
import { useState, useRef, useCallback, useEffect } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { useAuth } from "../../lib/auth-context";
import { authApi } from "../../lib/api";
import { queryClient } from "../../lib/query-client";
import { isValidEmail, isStrongPassword, isValidName } from "../../lib/validation";
import { PasswordStrength } from "../ui/password-strength";
 
const isLocalUrl = (url: string) => url.startsWith("/") && !url.startsWith("//");
 
// Client-side brute-force throttling (UX only — not a security boundary).
// This deters casual repeated attempts but can be bypassed by refreshing.
// Server-side rate limiting (rate-limit.middleware.ts) is the real defense.
const MAX_FAILED_ATTEMPTS = 5;
const COOLDOWN_SECONDS = 30;
 
interface PasswordFormProps {
	isSignUp: boolean;
	invitationToken?: string;
	redirect?: string;
}
 
export function PasswordForm({ isSignUp, invitationToken, redirect }: PasswordFormProps) {
	const { signIn, signUp } = useAuth();
	const navigate = useNavigate();
 
	const [name, setName] = useState("");
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [confirmPassword, setConfirmPassword] = useState("");
	const [isLoading, setIsLoading] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const [signUpSuccess, setSignUpSuccess] = useState(false);
	const [touched, setTouched] = useState({ name: false, email: false, password: false, confirm: false });
 
	// Bug 2: Brute-force throttling state
	const [failedAttempts, setFailedAttempts] = useState(0);
	const [cooldownRemaining, setCooldownRemaining] = useState(0);
	const cooldownTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
 
	// Bug 3: Unverified email state + resend
	const [showResendVerification, setShowResendVerification] = useState(false);
	const [resendingVerification, setResendingVerification] = useState(false);
	const [resendSuccess, setResendSuccess] = useState(false);
 
	const trimmedName = name.trim();
	const trimmedEmail = email.trim();
 
	const nameError = isSignUp && touched.name && !trimmedName
		? "Name is required"
		: isSignUp && touched.name && trimmedName && !isValidName(trimmedName)
			? "Please enter a valid name"
			: undefined;
	const emailError = touched.email && !trimmedEmail
		? "Email is required"
		: touched.email && trimmedEmail && !isValidEmail(trimmedEmail)
			? "Enter a valid email"
			: undefined;
	const passwordError = touched.password && !password.trim() ? "Password is required" : undefined;
	const confirmError =
		touched.confirm && confirmPassword.length > 0 && password !== confirmPassword
			? "Passwords do not match"
			: undefined;
 
	const isCoolingDown = cooldownRemaining > 0;
 
	// Bug 2: Start cooldown timer
	const startCooldown = useCallback(() => {
		setCooldownRemaining(COOLDOWN_SECONDS);
		Iif (cooldownTimerRef.current) clearInterval(cooldownTimerRef.current);
		cooldownTimerRef.current = setInterval(() => {
			setCooldownRemaining((prev) => {
				if (prev <= 1) {
					Eif (cooldownTimerRef.current) clearInterval(cooldownTimerRef.current);
					cooldownTimerRef.current = null;
					return 0;
				}
				return prev - 1;
			});
		}, 1000);
	}, []);
 
	// Cleanup cooldown timer on unmount
	useEffect(() => {
		return () => {
			if (cooldownTimerRef.current) clearInterval(cooldownTimerRef.current);
		};
	}, []);
 
	// Bug 3: Resend verification email
	const handleResendVerification = async () => {
		if (!email.trim()) return;
		setResendingVerification(true);
		setResendSuccess(false);
		try {
			await authApi.resendVerification(email.trim());
			setResendSuccess(true);
		} catch (resendErr) {
			console.error("Failed to resend verification:", resendErr);
			// Show generic success — don't reveal if email exists
			setResendSuccess(true);
		} finally {
			setResendingVerification(false);
		}
	};
 
	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		setTouched({ name: true, email: true, password: true, confirm: true });
		setError(null);
		setShowResendVerification(false);
		setResendSuccess(false);
 
		if (isSignUp && (!trimmedName || !isValidName(trimmedName))) return;
		if (!trimmedEmail || !isValidEmail(trimmedEmail)) return;
		if (!password.trim()) return;
 
		if (isSignUp && !isStrongPassword(password)) {
			setError("Please meet all password requirements");
			return;
		}
 
		if (isSignUp && password !== confirmPassword) {
			return;
		}
 
		// Bug 2: Check cooldown
		Iif (!isSignUp && isCoolingDown) return;
 
		setIsLoading(true);
		try {
			if (isSignUp) {
				const emailStatus = await authApi.checkEmail(trimmedEmail);
				if (emailStatus.exists) {
					if (emailStatus.provider === "google") {
						setError("This email is registered with Google. Use the Google button below to sign in.");
					} else if (emailStatus.provider === "facebook") {
						setError("This email is registered with Facebook. Use the Facebook button below to sign in.");
					} else if (emailStatus.verified) {
						setError("This email already has an account. Sign in instead.");
					} else {
						setError("This email already has an account but is not yet verified.");
						setShowResendVerification(true);
					}
					return;
				}
 
				await signUp(trimmedEmail, password, trimmedName);
				setSignUpSuccess(true);
			} else {
				const result = await signIn(trimmedEmail, password);
				// Reset failed attempts on success
				setFailedAttempts(0);
				queryClient.clear();
				if (invitationToken) {
					navigate({ to: "/accept-invitation", search: { token: invitationToken } });
				} else if (result.pendingInvitationToken) {
					navigate({ to: "/accept-invitation", search: { token: result.pendingInvitationToken } });
				} else if (redirect && isLocalUrl(redirect)) {
					navigate({ to: redirect as string });
				} else {
					navigate({ to: "/" });
				}
			}
		} catch (err: unknown) {
			const message =
				err instanceof Error ? err.message : "Something went wrong. Please try again.";
 
			// Bug 3: Detect unverified email error
			const isUnverified = message.toLowerCase().includes("not verified") ||
				message.toLowerCase().includes("email_not_verified") ||
				(err instanceof Error && "code" in err && (err as { code: string }).code === "EMAIL_NOT_VERIFIED");
 
			if (!isSignUp && isUnverified) {
				setError("Your email is not yet verified.");
				setShowResendVerification(true);
			} else if (!isSignUp) {
				// Bug 2: Track failed attempts for sign-in
				const newAttempts = failedAttempts + 1;
				setFailedAttempts(newAttempts);
				if (newAttempts >= MAX_FAILED_ATTEMPTS) {
					startCooldown();
					setError(`Too many failed attempts. Please wait ${COOLDOWN_SECONDS} seconds before trying again.`);
				} else {
					setError("Invalid email or password. Please try again.");
				}
			} else {
				const isNetworkError = err instanceof TypeError ||
					(err instanceof Error && err.message === "Failed to fetch");
				setError(
					isNetworkError
						? "Unable to connect. Please check your internet and try again."
						: message,
				);
			}
		} finally {
			setIsLoading(false);
		}
	};
 
	// Bug 3: Sign-up success screen with resend verification
	if (signUpSuccess) {
		return (
			<div className="text-center py-4 space-y-3">
				<p className="text-sm font-medium text-foreground">Check your email</p>
				<p className="text-sm text-muted-foreground">
					We&apos;ve sent a verification link to{" "}
					<span className="font-medium">{email}</span>.
				</p>
				{resendSuccess ? (
					<p className="text-sm text-green-600">Verification email sent! Check your inbox.</p>
				) : (
					<button
						type="button"
						onClick={handleResendVerification}
						disabled={resendingVerification}
						className="text-sm text-primary hover:underline disabled:opacity-50"
					>
						{resendingVerification ? "Sending..." : "Didn't receive it? Resend verification email"}
					</button>
				)}
			</div>
		);
	}
 
	return (
		<form onSubmit={handleSubmit} className="space-y-4" noValidate>
			{isSignUp && (
				<div>
					<label htmlFor="email-name" className="block text-sm font-medium text-foreground mb-1">
						Name
					</label>
					<input
						id="email-name"
						type="text"
						value={name}
						onChange={(e) => setName(e.target.value)}
						onBlur={() => setTouched(t => ({ ...t, name: true }))}
						placeholder="Your full name"
						disabled={isLoading}
						className={`w-full h-10 px-3 border rounded-md bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 ${nameError ? "border-red-500 focus:ring-red-500" : "border-input"}`}
					/>
					{nameError && <p className="mt-1 text-xs text-destructive">{nameError}</p>}
				</div>
			)}
 
			<div>
				<label htmlFor="email-address" className="block text-sm font-medium text-foreground mb-1">
					Email
				</label>
				<input
					id="email-address"
					type="email"
					value={email}
					onChange={(e) => setEmail(e.target.value)}
					onBlur={() => setTouched(t => ({ ...t, email: true }))}
					placeholder="you@example.com"
					disabled={isLoading}
					className={`w-full h-10 px-3 border rounded-md bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 ${emailError ? "border-red-500 focus:ring-red-500" : "border-input"}`}
				/>
				{emailError && <p className="mt-1 text-xs text-destructive">{emailError}</p>}
			</div>
 
			<div>
				<label htmlFor="email-password" className="block text-sm font-medium text-foreground mb-1">
					Password
				</label>
				<input
					id="email-password"
					type="password"
					value={password}
					onChange={(e) => setPassword(e.target.value)}
					onBlur={() => setTouched(t => ({ ...t, password: true }))}
					placeholder={isSignUp ? "Create a strong password" : "Your password"}
					disabled={isLoading}
					className={`w-full h-10 px-3 border rounded-md bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 ${passwordError ? "border-red-500 focus:ring-red-500" : "border-input"}`}
				/>
				{passwordError && <p className="mt-1 text-xs text-destructive">{passwordError}</p>}
				{isSignUp && <PasswordStrength password={password} />}
			</div>
 
			{isSignUp && (
				<div>
					<label htmlFor="email-confirm-password" className="block text-sm font-medium text-foreground mb-1">
						Confirm Password
					</label>
					<input
						id="email-confirm-password"
						type="password"
						value={confirmPassword}
						onChange={(e) => setConfirmPassword(e.target.value)}
						onBlur={() => setTouched(t => ({ ...t, confirm: true }))}
						placeholder="Re-enter your password"
						disabled={isLoading}
						className={`w-full h-10 px-3 border rounded-md bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 ${
							confirmError ? "border-destructive" : "border-input"
						}`}
					/>
					{confirmError && (
						<p className="mt-1 text-xs text-destructive">{confirmError}</p>
					)}
				</div>
			)}
 
			{!isSignUp && (
				<div className="text-right">
					<Link
						to="/auth/forgot-password"
						className="text-xs text-primary hover:underline"
					>
						Forgot password?
					</Link>
				</div>
			)}
 
			{error && (
				<p role="alert" className="text-sm text-destructive">{error}</p>
			)}
 
			{/* Bug 3: Resend verification for unverified sign-in */}
			{showResendVerification && (
				<div className="text-center">
					{resendSuccess ? (
						<p className="text-sm text-green-600">Verification email sent! Check your inbox.</p>
					) : (
						<button
							type="button"
							onClick={handleResendVerification}
							disabled={resendingVerification}
							className="text-sm text-primary hover:underline disabled:opacity-50"
						>
							{resendingVerification ? "Sending..." : "Resend verification email"}
						</button>
					)}
				</div>
			)}
 
			{/* Bug 2: Cooldown message */}
			{isCoolingDown && (
				<p className="text-sm text-amber-600">
					Please wait {cooldownRemaining}s before trying again.
				</p>
			)}
 
			<button
				type="submit"
				disabled={isLoading || isCoolingDown}
				className="w-full h-10 px-4 bg-primary text-primary-foreground text-sm font-medium rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
			>
				{isLoading
					? isSignUp
						? "Creating account..."
						: "Signing in..."
					: isSignUp
						? "Create Account"
						: "Login"}
			</button>
		</form>
	);
}