feat(identity): confirm the email address with a six-digit code from the message

This commit is contained in:
shira committed 2026-10-10 00:52:46 +03:00
1 parent c94434cd09
commit d365a05c96
87 files changed
+4764 -224

No files matched your search

@@ -175,7 +175,7 @@ export function ConfirmEmailForm({
</p>
) : (
<p className={styles.hint}>
В ссылке нет действующего токена. Укажите адрес, чтобы запросить новое письмо.
В ссылке нет действующего токена. Введите адрес, пароль и код из письма ниже.
</p>
)}
<TextLink to={paths.login}>Перейти ко входу</TextLink>
@@ -20,7 +20,11 @@ type RegisterFormProps = {
initialEmail?: string;
initialScenario?: Scenario | "";
onDraftChange?: (draft: RegistrationDraft) => void;
onAccepted: (draft: RegistrationDraft) => void;
/**
* Called after the server accepted the request. The password is passed once,
* for the code step held in memory by the caller; it is never stored here.
*/
onAccepted: (draft: RegistrationDraft, password: string) => void;
};
type FieldErrors = {
@@ -155,6 +159,7 @@ export function RegisterForm({
consent_c1: { text_version: consent.data.text_version, accepted: true as const },
};
idempotencyKey.current ??= createIdempotencyKey();
const submittedPassword = password;
try {
await registration.mutateAsync({
@@ -162,7 +167,7 @@ export function RegisterForm({
headers: { "Idempotency-Key": idempotencyKey.current },
});
setPassword("");
onAccepted({ email, scenario });
onAccepted({ email, scenario }, submittedPassword);
} catch (error: unknown) {
const result = registrationError(error);
setFormError(result.message);
@@ -0,0 +1 @@
export { VerificationCodeForm } from "./ui/verification-code-form";
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import {
codeConfirmationRefusal,
codeFieldError,
digitsOnly,
emailFieldError,
passwordFieldError,
resendCooldownSeconds,
resendLabel,
resendRefusal,
} from "./verification-code";
function apiError(code: string, retryAfterSeconds?: number): Error {
return Object.assign(new Error(code), { code, retryAfterSeconds });
}
describe("code input", () => {
it("keeps only ASCII digits and at most six of them, so a pasted group still fits", () => {
expect(digitsOnly("482 915")).toBe("482915");
expect(digitsOnly("код: 4829-15 и еще 99")).toBe("482915");
expect(digitsOnly("123")).toBe("");
expect(digitsOnly("")).toBe("");
});
it("accepts exactly six digits", () => {
expect(codeFieldError("000000")).toBeNull();
expect(codeFieldError("482915")).toBeNull();
expect(codeFieldError("48291")).not.toBeNull();
expect(codeFieldError("4829156")).not.toBeNull();
expect(codeFieldError("48291a")).not.toBeNull();
});
});
describe("registration fields", () => {
it("checks the address and the password bounds of the login", () => {
expect(emailFieldError("candidate@example.com")).toBeNull();
expect(emailFieldError("candidate")).not.toBeNull();
expect(passwordFieldError("correct horse battery staple")).toBeNull();
expect(passwordFieldError("")).not.toBeNull();
expect(passwordFieldError("p".repeat(129))).not.toBeNull();
expect(passwordFieldError("p".repeat(128))).toBeNull();
});
});
describe("confirmation refusals", () => {
it("gives every cause of an invalid code the same text and clears the code", () => {
const refusal = codeConfirmationRefusal(apiError("verification_token_invalid"));
expect(refusal.message).toContain("Код не подошел");
expect(refusal.message).toContain("После пяти неверных попыток");
expect(refusal.codeRefused).toBe(true);
expect(refusal.retryAfterSeconds).toBeUndefined();
});
it("passes the server wait on a rate limit, and keeps the code for other failures", () => {
expect(codeConfirmationRefusal(apiError("rate_limited", 42))).toMatchObject({
message: "Слишком много попыток. Подождите и повторите попытку.",
retryAfterSeconds: 42,
});
expect(codeConfirmationRefusal(apiError("rate_limited")).retryAfterSeconds).toBeUndefined();
expect(codeConfirmationRefusal(apiError("csrf_check_failed")).codeRefused).toBeUndefined();
expect(codeConfirmationRefusal(new Error("network")).message).toContain("Проверьте соединение");
});
it("maps a refused resend to its own copy and keeps the server wait", () => {
expect(resendRefusal(apiError("rate_limited", 17))).toEqual({
message: "Слишком много запросов. Подождите и повторите попытку.",
retryAfterSeconds: 17,
});
expect(resendRefusal(apiError("unknown")).message).toBe(
"Не удалось отправить код. Повторите попытку.",
);
});
});
describe("resend cooldown", () => {
it("shows the time left and the plain label once the wait is over", () => {
expect(resendCooldownSeconds).toBe(60);
expect(resendLabel(45)).toBe("Отправить код повторно через 45 с");
expect(resendLabel(0)).toBe("Отправить код повторно");
});
});
@@ -0,0 +1,113 @@
import { EmailAddress, VerificationCode } from "../../../shared/api/schemas";
/** Number of digits in the code of a verification message. */
export const verificationCodeLength = 6;
/**
* Wait before a repeated message after one was queued. It matches the
* default minimum interval between two verification messages to one address,
* so the button is not offered when the server would refuse it.
*/
export const resendCooldownSeconds = 60;
const refusedCodeMessage =
"Код не подошел. Проверьте код и пароль или запросите новый код. После пяти неверных попыток код перестает действовать.";
/** Keeps the ASCII digits of pasted or typed text, up to the code length. */
export function digitsOnly(raw: string): string {
return raw.replace(/\D/gu, "").slice(0, verificationCodeLength);
}
export function codeFieldError(code: string): string | null {
return VerificationCode.safeParse(code).success ? null : "Введите 6 цифр из письма.";
}
export function emailFieldError(email: string): string | null {
return EmailAddress.safeParse(email).success
? null
: "Введите корректный адрес электронной почты.";
}
/** Same bounds as the login password: 1 to 128 code points after NFKC. */
export function passwordFieldError(password: string): string | null {
const length = Array.from(password.normalize("NFKC")).length;
return length >= 1 && length <= 128
? null
: "Введите пароль регистрации длиной от 1 до 128 символов после нормализации.";
}
export type ApiRefusal = {
message: string;
/** Set when the server asked for a wait with Retry-After. */
retryAfterSeconds?: number;
/** Set when the code itself is refused, so the field should be cleared. */
codeRefused?: boolean;
};
function errorCode(error: unknown): string {
return error instanceof Error && "code" in error ? String(error.code) : "";
}
function retryAfter(error: unknown): number | undefined {
if (error instanceof Error && "retryAfterSeconds" in error) {
const value = error.retryAfterSeconds;
return typeof value === "number" && value > 0 ? value : undefined;
}
return undefined;
}
/**
* Maps a refused code confirmation to copy. Every cause of
* verification_token_invalid shows the same text, because the server gives
* the same answer for each of them.
*/
export function codeConfirmationRefusal(error: unknown): ApiRefusal {
switch (errorCode(error)) {
case "verification_token_invalid":
return { message: refusedCodeMessage, codeRefused: true };
case "rate_limited":
return {
message: "Слишком много попыток. Подождите и повторите попытку.",
...optionalWait(error),
};
case "validation_failed":
return {
message: "Проверьте введенные данные: код состоит из 6 цифр, адрес и пароль заполнены.",
};
case "csrf_check_failed":
return {
message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.",
};
default:
return { message: "Не удалось подтвердить почту. Проверьте соединение и повторите попытку." };
}
}
/** Maps a refused request for a new message to copy. */
export function resendRefusal(error: unknown): ApiRefusal {
switch (errorCode(error)) {
case "rate_limited":
return {
message: "Слишком много запросов. Подождите и повторите попытку.",
...optionalWait(error),
};
case "csrf_check_failed":
return {
message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.",
};
default:
return { message: "Не удалось отправить код. Повторите попытку." };
}
}
function optionalWait(error: unknown): { retryAfterSeconds?: number } {
const seconds = retryAfter(error);
return seconds === undefined ? {} : { retryAfterSeconds: seconds };
}
/** Button label that shows the time left before a new message can be asked for. */
export function resendLabel(secondsLeft: number): string {
return secondsLeft > 0
? `Отправить код повторно через ${secondsLeft} с`
: "Отправить код повторно";
}
@@ -0,0 +1,94 @@
.form {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.label {
font-weight: var(--font-weight-bold);
}
.input {
width: 100%;
min-height: 2.75rem;
padding: var(--space-2) var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
background: var(--color-surface);
}
/* The code is the one field the user types from the message, so it is large
and spaced; it still fits a 360 px viewport because it has no fixed width. */
.code-input {
width: 100%;
max-width: 18rem;
min-height: 3.25rem;
padding: var(--space-2) var(--space-3);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-s);
background: var(--color-surface);
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 1.75rem;
font-variant-numeric: tabular-nums;
letter-spacing: 0.3em;
}
.input[aria-invalid="true"],
.code-input[aria-invalid="true"] {
border-color: var(--color-danger);
}
.hint,
.error {
font-size: var(--font-size-s);
}
.hint {
color: var(--color-text-secondary);
}
.address {
overflow-wrap: anywhere;
}
.error,
.alert {
color: var(--color-danger);
}
.alert {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-danger);
background: var(--color-surface);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
}
.status {
min-height: 1.5em;
color: var(--color-text-secondary);
}
.notice {
padding: var(--space-4);
border-left: var(--line-strong) solid var(--color-accent);
background: var(--color-surface);
}
.resend {
display: grid;
gap: var(--space-3);
padding-top: var(--space-4);
border-top: var(--line-thin) solid var(--color-border-strong);
}
@@ -0,0 +1,74 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { VerificationCodeForm } from "./verification-code-form";
function render(props: Partial<Parameters<typeof VerificationCodeForm>[0]> = {}): string {
const queryClient = new QueryClient();
return renderToStaticMarkup(
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<VerificationCodeForm onConfirmed={() => undefined} {...props} />
</QueryClientProvider>
</MemoryRouter>,
);
}
describe("verification code form after registration", () => {
it("asks only for the code when the registration password is held in memory", () => {
const html = render({
initialEmail: "candidate@example.com",
password: "correct horse battery staple",
messageJustSent: true,
});
expect(html).toContain("candidate@example.com");
expect(html).not.toMatch(/type="password"/);
expect(html).not.toContain("Электронная почта");
expect(html).not.toContain("correct horse battery staple");
});
it("presents the code input for one-time codes and numeric keyboards", () => {
const html = render({ initialEmail: "candidate@example.com", password: "x" });
expect(html).toMatch(/<input[^>]*id="[^"]*-code"[^>]*>/);
expect(html).toContain('inputMode="numeric"');
expect(html).toContain('autoComplete="one-time-code"');
// No maxLength: the browser would cut "482 915" to "482 91" before the
// digits are kept, so the field keeps every character and digitsOnly trims it.
expect(html).not.toContain("maxLength");
expect(html).toContain("Код из письма");
expect(html).toContain("Подтвердить код");
});
it("starts the resend cooldown when a message was just queued", () => {
const html = render({
initialEmail: "candidate@example.com",
password: "x",
messageJustSent: true,
});
expect(html).toMatch(
/<button[^>]*disabled=""[^>]*>Отправить код повторно через 60 с<\/button>/,
);
});
it("offers the resend at once when the step was reopened later", () => {
const html = render({ initialEmail: "candidate@example.com", password: "x" });
expect(html).toMatch(/<button[^>]*>Отправить код повторно<\/button>/);
expect(html).not.toMatch(/Отправить код повторно через/);
});
});
describe("verification code form on the verification page", () => {
it("asks for the address, the password, and the code when nothing is in memory", () => {
const html = render();
expect(html).toContain("Электронная почта");
expect(html).toContain("Пароль, выбранный при регистрации");
expect(html.match(/type="password"/g)).toHaveLength(1);
expect(html).toContain("Код из письма");
});
});
@@ -0,0 +1,275 @@
import { useEffect, useId, useState, type ClipboardEvent, type FormEvent } from "react";
import {
useConfirmEmailByCode,
useResendEmailVerification,
} from "../../../shared/api/endpoints/identity/identity";
import { paths } from "../../../shared/config";
import { Button, ButtonLink } from "../../../shared/ui";
import {
codeConfirmationRefusal,
codeFieldError,
digitsOnly,
emailFieldError,
passwordFieldError,
resendCooldownSeconds,
resendLabel,
resendRefusal,
} from "../model/verification-code";
import styles from "./verification-code-form.module.css";
type FieldErrors = {
email?: string | undefined;
password?: string | undefined;
code?: string | undefined;
};
type VerificationCodeFormProps = {
/** Address of the registration. Typed by the user when the form is opened without it. */
initialEmail?: string;
/**
* Password of the registration, held in the parent's memory only. When it is
* absent, for example after a page reload, the form asks for it.
*/
password?: string | undefined;
/** A message was queued just now, so a new one waits for the cooldown. */
messageJustSent?: boolean;
onConfirmed: () => void;
};
/**
* Confirms the address with the six-digit code from the verification message.
* The success result and its copy match the link page, so the next step is
* the same: sign in with the password, then continue from the saved step.
*/
export function VerificationCodeForm({
initialEmail = "",
password: registrationPassword,
messageJustSent = false,
onConfirmed,
}: VerificationCodeFormProps) {
const id = useId();
const confirm = useConfirmEmailByCode({ mutation: { gcTime: 0 } });
const resend = useResendEmailVerification({ mutation: { gcTime: 0 } });
const [email, setEmail] = useState(initialEmail);
const [typedPassword, setTypedPassword] = useState("");
const [code, setCode] = useState("");
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const [formError, setFormError] = useState<string | null>(null);
const [confirmed, setConfirmed] = useState(false);
const [secondsLeft, setSecondsLeft] = useState(messageJustSent ? resendCooldownSeconds : 0);
const [resendMessage, setResendMessage] = useState("");
const asksForPassword = registrationPassword === undefined;
useEffect(() => {
if (secondsLeft <= 0) return;
const timer = window.setTimeout(() => setSecondsLeft((current) => current - 1), 1000);
return () => window.clearTimeout(timer);
}, [secondsLeft]);
function handlePaste(event: ClipboardEvent<HTMLInputElement>) {
event.preventDefault();
setCode(digitsOnly(event.clipboardData.getData("text")));
setFieldErrors((current) => ({ ...current, code: undefined }));
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (confirm.isPending) return;
const password = registrationPassword ?? typedPassword;
const errors: FieldErrors = {
email: emailFieldError(email) ?? undefined,
password: asksForPassword ? (passwordFieldError(password) ?? undefined) : undefined,
code: codeFieldError(code) ?? undefined,
};
setFieldErrors(errors);
setFormError(null);
if (errors.email || errors.password || errors.code) return;
try {
await confirm.mutateAsync({ data: { email, code, password } });
setCode("");
setTypedPassword("");
setConfirmed(true);
onConfirmed();
} catch (error: unknown) {
const refusal = codeConfirmationRefusal(error);
setFormError(refusal.message);
if (refusal.codeRefused) setCode("");
}
}
async function requestNewCode() {
if (resend.isPending || secondsLeft > 0) return;
const emailError = emailFieldError(email);
if (emailError) {
setFieldErrors((current) => ({ ...current, email: emailError }));
setResendMessage("");
return;
}
setResendMessage("");
try {
await resend.mutateAsync({ data: { email } });
setSecondsLeft(resendCooldownSeconds);
setResendMessage(
"Запрос принят. Если адрес можно зарегистрировать, новое письмо с кодом придет на почту.",
);
} catch (error: unknown) {
const refusal = resendRefusal(error);
if (refusal.retryAfterSeconds !== undefined) setSecondsLeft(refusal.retryAfterSeconds);
setResendMessage(refusal.message);
}
}
if (confirmed) {
return (
<div className={styles.form}>
<div className={styles.notice} role="status" aria-live="polite">
Почта подтверждена. Войдите с паролем, который вы выбрали при регистрации. После входа
сервис откроет сохраненный шаг.
</div>
<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>
</div>
);
}
const codeErrorId = `${id}-code-error`;
const emailErrorId = `${id}-email-error`;
const passwordErrorId = `${id}-password-error`;
return (
<div className={styles.form}>
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
{asksForPassword ? (
<>
<div className={styles.field}>
<label className={styles.label} htmlFor={`${id}-email`}>
Электронная почта
</label>
<input
className={styles.input}
id={`${id}-email`}
name="email"
type="email"
autoComplete="email"
maxLength={254}
value={email}
disabled={confirm.isPending}
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? emailErrorId : undefined}
onChange={(event) => {
setEmail(event.currentTarget.value);
setFieldErrors((current) => ({ ...current, email: undefined }));
}}
/>
{fieldErrors.email ? (
<p className={styles.error} id={emailErrorId}>
{fieldErrors.email}
</p>
) : null}
</div>
<div className={styles.field}>
<label className={styles.label} htmlFor={`${id}-password`}>
Пароль, выбранный при регистрации
</label>
<input
className={styles.input}
id={`${id}-password`}
name="password"
type="password"
autoComplete="new-password"
maxLength={512}
value={typedPassword}
disabled={confirm.isPending}
aria-invalid={Boolean(fieldErrors.password)}
aria-describedby={fieldErrors.password ? passwordErrorId : undefined}
onChange={(event) => {
setTypedPassword(event.currentTarget.value);
setFieldErrors((current) => ({ ...current, password: undefined }));
}}
/>
{fieldErrors.password ? (
<p className={styles.error} id={passwordErrorId}>
{fieldErrors.password}
</p>
) : null}
</div>
</>
) : (
<p className={styles.hint}>
Код отправлен на адрес <strong className={styles.address}>{email}</strong>. Введите его,
чтобы подтвердить почту.
</p>
)}
<div className={styles.field}>
<label className={styles.label} htmlFor={`${id}-code`}>
Код из письма
</label>
<input
className={styles["code-input"]}
id={`${id}-code`}
name="code"
type="text"
inputMode="numeric"
autoComplete="one-time-code"
value={code}
disabled={confirm.isPending}
aria-invalid={Boolean(fieldErrors.code)}
aria-describedby={fieldErrors.code ? codeErrorId : `${id}-code-hint`}
onChange={(event) => {
setCode(digitsOnly(event.currentTarget.value));
setFieldErrors((current) => ({ ...current, code: undefined }));
}}
onPaste={handlePaste}
/>
{fieldErrors.code ? (
<p className={styles.error} id={codeErrorId}>
{fieldErrors.code}
</p>
) : (
<p className={styles.hint} id={`${id}-code-hint`}>
Шесть цифр. Код действует 30 минут.
</p>
)}
</div>
{formError ? (
<p className={styles.alert} role="alert">
{formError}
</p>
) : null}
<div className={styles.actions}>
<Button type="submit" isBusy={confirm.isPending}>
{confirm.isPending ? "Проверяем код..." : "Подтвердить код"}
</Button>
</div>
<p className={styles.status} role="status" aria-live="polite">
{confirm.isPending ? "Проверяем код..." : ""}
</p>
</form>
<div className={styles.resend}>
<p className={styles.hint}>
Письмо не пришло? Проверьте папку «Спам» или запросите новый код.
</p>
<div className={styles.actions}>
<Button
type="button"
variant="secondary"
isBusy={resend.isPending}
disabled={secondsLeft > 0}
onClick={() => void requestNewCode()}
>
{resend.isPending ? "Отправляем..." : resendLabel(secondsLeft)}
</Button>
</div>
<p className={styles.status} role="status" aria-live="polite">
{resendMessage}
</p>
</div>
</div>
);
}