Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

8.5 KB
Raw Blame
import { i18n } from "@lingui/core";
import { ph, t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { useSelector } from "@tanstack/react-form";
import { useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useRouter, useSearch } from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import z from "zod";
import { Button } from "@reactive-resume/ui/components/button";
import { Checkbox } from "@reactive-resume/ui/components/checkbox";
import { FormControl, FormItem, FormLabel, FormMessage } from "@reactive-resume/ui/components/form";
import { Icon } from "@reactive-resume/ui/components/icon";
import { Input } from "@reactive-resume/ui/components/input";
import { OTPField } from "@reactive-resume/ui/components/otp-field";
import { toast } from "@reactive-resume/ui/components/toast";
import { authErrorMessage } from "../error";
import { getAuthRedirectOptions, getOAuthSignInOptions, isOAuthRedirect } from "../redirect";
import { authClient } from "@/libs/auth/client";
import { sessionQueryKey } from "@/libs/root-context";
import { useAppForm } from "@/libs/tanstack-form";

const totpSchema = z.object({
	code: z.string().length(6, { error: () => t`Enter the 6-digit code.` }),
	trustDevice: z.boolean(),
});

const backupCodeSchema = z.object({
	code: z
		.string()
		.trim()
		.min(1, { error: () => t`Enter a backup code.` }),
	trustDevice: z.boolean(),
});

type TwoFactorVerificationPageProps = {
	backupCode?: boolean;
};

function TwoFactorVerificationPage({ backupCode = false }: TwoFactorVerificationPageProps) {
	const router = useRouter();
	const queryClient = useQueryClient();
	const { callbackURL, reauthenticate } = useSearch({ from: "/auth" });
	const navigate = useNavigate();

	const form = useAppForm({
		defaultValues: { code: "", trustDevice: false },
		validators: { onSubmit: backupCode ? backupCodeSchema : totpSchema },
		onSubmit: async ({ value }) => {
			const toastId = toast.add({
				type: "loading",
				description: backupCode ? t`Verifying backup code…` : t`Verifying code…`,
			});
			const rawCode = value.code.trim().replaceAll("-", "");
			const code = backupCode ? `${rawCode.slice(0, 5)}-${rawCode.slice(5)}` : value.code;
			const options = { code, trustDevice: value.trustDevice, ...getOAuthSignInOptions(callbackURL) };
			let { data, error } = backupCode
				? await authClient.twoFactor.verifyBackupCode(options)
				: await authClient.twoFactor.verifyTotp(options);
			// New backup codes are all capitals; older ones mix cases. A lower-case code that didn't match gets one
			// retry in capitals; other failures (an expired challenge, rate limits) don't spend another attempt.
			if (error?.code === "INVALID_BACKUP_CODE" && backupCode && code !== code.toUpperCase())
				({ data, error } = await authClient.twoFactor.verifyBackupCode({ ...options, code: code.toUpperCase() }));

			if (error) {
				toast.add({
					type: "error",
					description: authErrorMessage(
						error,
						backupCode
							? t`Couldn't verify your backup code. Check the code and try again.`
							: t`Couldn't verify your code. Check the code and try again.`,
					),
					id: toastId,
				});
				if (error.code === "INVALID_TWO_FACTOR_COOKIE") {
					void navigate({ to: "/auth/login", search: { callbackURL, reauthenticate: true }, replace: true });
					return;
				}
				// A wrong code is cleared and the first box takes focus again, ready for the next try.
				form.setFieldValue("code", "");
				focusCode();
				return;
			}

			toast.close(toastId);
			if (isOAuthRedirect(data)) return;
			await queryClient.invalidateQueries({ queryKey: sessionQueryKey });
			await router.invalidate();
			void navigate(getAuthRedirectOptions(callbackURL));
		},
	});

	const isSubmitting = useSelector(form.store, (state) => state.isSubmitting);
	// Typing the code works at once: the first box (or the backup code field) has focus when the page opens.
	const codeRef = useRef<HTMLDivElement>(null);
	const focusCode = () => codeRef.current?.querySelector("input")?.focus();
	useEffect(() => {
		codeRef.current?.querySelector("input")?.focus();
	}, []);

	return (
		<>
			<div className="space-y-1 text-center">
				<h1 className="text-[30px] leading-9">
					{backupCode ? <Trans>Verify with a backup code</Trans> : <Trans>Two-step verification</Trans>}
				</h1>
				<div className="text-ink-3">
					{backupCode ? (
						<Trans>Enter one of your saved backup codes to access your account.</Trans>
					) : (
						<Trans>Enter the verification code from your authenticator app.</Trans>
					)}
				</div>
			</div>

			<form
				noValidate
				className="grid gap-6"
				onSubmit={(event) => {
					event.preventDefault();
					event.stopPropagation();
					void form.handleSubmit();
				}}
			>
				<form.Field name="code">
					{(field) => (
						<FormItem
							ref={codeRef}
							data-route-focus
							className="justify-self-center"
							hasError={field.state.meta.isTouched && field.state.meta.errors.length > 0}
						>
							<FormLabel className="sr-only">
								{backupCode ? <Trans>Backup code</Trans> : <Trans>Verification code</Trans>}
							</FormLabel>
							<FormControl
								render={
									backupCode ? (
										<Input
											type="text"
											maxLength={11}
											className="max-w-xs"
											name={field.name}
											value={field.state.value}
											onBlur={field.handleBlur}
											onChange={(event) => field.handleChange(event.target.value)}
										/>
									) : (
										<OTPField
											digitLabel={(position, total) =>
												t`Digit ${ph({ position: i18n.number(position) })} of ${ph({ total: i18n.number(total) })}`
											}
											length={6}
											autoSubmit
											name={field.name}
											value={field.state.value}
											onBlur={field.handleBlur}
											onValueChange={field.handleChange}
										/>
									)
								}
							/>
							<FormMessage errors={field.state.meta.errors} />
						</FormItem>
					)}
				</form.Field>

				<form.Field name="trustDevice">
					{(field) => (
						<FormItem className="flex items-center gap-2.5 justify-self-center">
							<FormControl
								render={<Checkbox name={field.name} checked={field.state.value} onCheckedChange={field.handleChange} />}
							/>
							<FormLabel>
								<Trans>Trust this device for 30 days</Trans>
							</FormLabel>
						</FormItem>
					)}
				</form.Field>

				<div className="flex gap-x-2">
					<Button
						variant="secondary"
						className="flex-1"
						nativeButton={false}
						render={
							<Link to={backupCode ? "/auth/verify-2fa" : "/auth/login"} search={{ callbackURL, reauthenticate }}>
								<Icon name="arrow-left" size={16} />
								{backupCode ? (
									<Trans comment="Secondary navigation button on backup-code verification screen">Go back</Trans>
								) : (
									<Trans comment="Secondary navigation button on 2FA verification screen">Back to sign in</Trans>
								)}
							</Link>
						}
					/>

					<Button type="submit" className="flex-1" disabled={isSubmitting}>
						<Icon name="check" size={16} />
						{backupCode ? (
							<Trans comment="Primary action button to submit backup code">Verify</Trans>
						) : (
							<Trans comment="Primary action button to submit 2FA code">Verify</Trans>
						)}
					</Button>
				</div>
			</form>

			{backupCode && (
				<details className="justify-self-center text-center text-sm text-ink-2">
					<summary className="cursor-pointer underline underline-offset-2">
						<Trans>No backup codes either?</Trans>
					</summary>
					<p className="mt-2 max-w-sm">
						<Trans>
							If you never verified your email address, a password reset turns two-step verification off. Otherwise a
							reset keeps it on, so ask the person who runs this Reactive Resume server to turn it off for your account.
							Then sign in with your password and turn it on again with a new authenticator.
						</Trans>
					</p>
				</details>
			)}

			{!backupCode && (
				<Button
					variant="link"
					nativeButton={false}
					className="h-auto justify-self-center p-0 text-sm"
					render={
						<Link to="/auth/verify-2fa-backup" search={{ callbackURL, reauthenticate }}>
							<Trans comment="Link to backup-code verification flow when authenticator app is unavailable">
								Lost access to your authenticator?
							</Trans>
						</Link>
					}
				/>
			)}
		</>
	);
}

export function VerifyTwoFactorPage() {
	return <TwoFactorVerificationPage />;
}

export function VerifyTwoFactorBackupPage() {
	return <TwoFactorVerificationPage backupCode />;
}