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>
);
}
+26 -4
View File
@@ -1,6 +1,6 @@
import { useState } from "react";
import { RegisterForm, type RegistrationDraft } from "../../../features/register-account";
import { ResendVerificationForm } from "../../../features/resend-email-verification";
import { VerificationCodeForm } from "../../../features/verify-email-code";
import { Button, Page, Section, TextLink } from "../../../shared/ui";
import { paths } from "../../../shared/config";
import {
@@ -16,6 +16,11 @@ function scenarioLabel(scenario: RegistrationDraft["scenario"]): string {
export function RegisterPage() {
const [context, setContext] = useState<RegistrationContext>(readRegistrationContext);
// The registration password lives only in this component's memory and is
// never written to storage. A reload drops it, and the code step then asks
// for it again.
const [registrationPassword, setRegistrationPassword] = useState<string | undefined>();
const [messageJustSent, setMessageJustSent] = useState(false);
function saveDraft(draft: RegistrationDraft) {
const next = { ...draft, accepted: false };
@@ -23,15 +28,25 @@ export function RegisterPage() {
writeRegistrationContext(next);
}
function markAccepted(draft: RegistrationDraft) {
function markAccepted(draft: RegistrationDraft, password: string) {
const next = { ...draft, accepted: true };
setContext(next);
writeRegistrationContext(next);
setRegistrationPassword(password);
setMessageJustSent(true);
}
function finishConfirmation() {
setRegistrationPassword(undefined);
setMessageJustSent(false);
clearRegistrationContext();
}
function startAgain() {
clearRegistrationContext();
setContext({ email: "", scenario: "", accepted: false });
setRegistrationPassword(undefined);
setMessageJustSent(false);
}
return (
@@ -43,10 +58,17 @@ export function RegisterPage() {
<div>
<Section title="Запрос принят">
<p role="status" aria-live="polite">
Если для этого адреса требуется подтверждение, письмо будет отправлено. Выбранный
Если адрес можно зарегистрировать, письмо с кодом и ссылкой придет на него. Выбранный
сценарий: {scenarioLabel(context.scenario)}.
</p>
<ResendVerificationForm initialEmail={context.email} />
<Section title="Введите код из письма" headingLevel={3}>
<VerificationCodeForm
initialEmail={context.email}
password={registrationPassword}
messageJustSent={messageJustSent}
onConfirmed={finishConfirmation}
/>
</Section>
<TextLink to={paths.login}>Перейти ко входу</TextLink>
<Button type="button" variant="quiet" onClick={startAgain}>
Начать другую регистрацию
@@ -1,33 +1,33 @@
import { useCallback, useState } from "react";
import { ConfirmEmailForm } from "../../../features/confirm-email";
import { ResendVerificationForm } from "../../../features/resend-email-verification";
import { VerificationCodeForm } from "../../../features/verify-email-code";
import { Page, Section } from "../../../shared/ui";
import { clearRegistrationContext } from "../model/registration-context";
export function VerifyEmailPage() {
const [needsResend, setNeedsResend] = useState(false);
const requestResend = useCallback(() => setNeedsResend(true), []);
const linkReady = useCallback(() => setNeedsResend(false), []);
const [needsCode, setNeedsCode] = useState(false);
const requestCode = useCallback(() => setNeedsCode(true), []);
const linkReady = useCallback(() => setNeedsCode(false), []);
const finishConfirmation = useCallback(() => {
setNeedsResend(false);
setNeedsCode(false);
clearRegistrationContext();
}, []);
return (
<Page
title="Подтверждение почты"
lead="Подтвердите адрес ссылкой из письма и паролем регистрации."
lead="Подтвердите адрес ссылкой из письма или кодом из письма и паролем регистрации."
>
<Section title="Подтвердить адрес">
<ConfirmEmailForm
onResendNeeded={requestResend}
onResendNeeded={requestCode}
onTokenReady={linkReady}
onConfirmed={finishConfirmation}
/>
</Section>
{needsResend ? (
<Section title="Запросить новое письмо">
<ResendVerificationForm />
{needsCode ? (
<Section title="Введите код из письма">
<VerificationCodeForm onConfirmed={clearRegistrationContext} />
</Section>
) : null}
</Page>
@@ -37,6 +37,8 @@ export const getResendEmailVerificationResponseMock = (overrideResponse: Partial
export const getConfirmEmailResponseMock = (overrideResponse: Partial<Extract<EmailVerificationResult, object>> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), ...overrideResponse})
export const getConfirmEmailByCodeResponseMock = (overrideResponse: Partial<Extract<EmailVerificationResult, object>> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), ...overrideResponse})
export const getLoginResponseMock = (overrideResponse: Partial<Extract<Session, object>> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), ...overrideResponse})
export const getGetCurrentSessionResponseMock = (overrideResponse: Partial<Extract<Session, object>> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), ...overrideResponse})
@@ -92,6 +94,18 @@ export const getConfirmEmailMockHandler = (overrideResponse?: EmailVerificationR
}, options)
}
export const getConfirmEmailByCodeMockHandler = (overrideResponse?: EmailVerificationResult | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<EmailVerificationResult> | EmailVerificationResult), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/identity/email-verifications/code', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getConfirmEmailByCodeResponseMock(),
{ status: 200
})
}, options)
}
export const getLoginMockHandler = (overrideResponse?: Session | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<Session> | Session), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/identity/sessions', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
@@ -142,6 +156,7 @@ export const getIdentityMock = () => [
getRegisterAccountMockHandler(),
getResendEmailVerificationMockHandler(),
getConfirmEmailMockHandler(),
getConfirmEmailByCodeMockHandler(),
getLoginMockHandler(),
getGetCurrentSessionMockHandler(),
getLogoutMockHandler(),
@@ -25,9 +25,11 @@ import type {
import type {
Account,
ConfirmEmailByCodeHeaders,
ConfirmEmailHeaders,
ConsentPurpose,
ConsentText,
EmailVerificationCodeRequest,
EmailVerificationRequest,
EmailVerificationResendRequest,
EmailVerificationResult,
@@ -453,6 +455,101 @@ export const useConfirmEmail = <TError = ErrorType<Problem>,
> => {
return useMutation(getConfirmEmailMutationOptions(options), queryClient);
}
export const getConfirmEmailByCodeUrl = () => {
return `/api/v1/identity/email-verifications/code`
}
/**
* Public operation without a session. The verification message carries a six-digit code next to the link. The client sends the address, the code, and the password chosen for the registration that issued the code, so the user types only the code after registration. A reloaded page has no password in memory, so it asks for the address, the password, and the code together.
*
* The server finds the newest open verification token of the unverified account with this normalized address, whose registration is current and which carries a code. It compares the keyed digest of the code with the stored digest, checks the password against the token's pending password hash, and checks that the code has not expired. The code lives 30 minutes, or until the token ends if the token ends sooner. When all three checks pass, the server consumes the token, verifies the email, and applies the pending credentials in one transaction, exactly as the link confirmation does, and answers 200 with the same body. Success does not start a session.
*
* Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, or a code that was burned. This keeps the answer from showing which addresses have a pending registration. Every failed attempt of an open code counts against that token. The fifth failed attempt burns the token: the code and the link stop working, and the user must request a new message. A refused attempt changes nothing else.
*
* The same refusal is returned after the rate limits are checked. The operation is limited per client address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with Retry-After. A body that does not match the contract, such as a code that is not six digits, answers 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` otherwise.
* @summary Verify an email with the six-digit code from the verification message.
*/
export const confirmEmailByCode = async (emailVerificationCodeRequest: EmailVerificationCodeRequest,
headers?: ConfirmEmailByCodeHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<EmailVerificationResult> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<EmailVerificationResult>(getConfirmEmailByCodeUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(emailVerificationCodeRequest)
}
);}
export const getConfirmEmailByCodeMutationKey = () => ['confirmEmailByCode'] as const;
export const getConfirmEmailByCodeMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof confirmEmailByCode>>, TError,ConfirmEmailByCodeMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof confirmEmailByCode>>, TError,ConfirmEmailByCodeMutationVariables, TContext> => {
const mutationKey = getConfirmEmailByCodeMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof confirmEmailByCode>>, ConfirmEmailByCodeMutationVariables> = (props) => {
const {data,headers} = props ?? {};
return confirmEmailByCode(data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type ConfirmEmailByCodeMutationResult = NonNullable<Awaited<ReturnType<typeof confirmEmailByCode>>>
export type ConfirmEmailByCodeMutationBody = EmailVerificationCodeRequest
export type ConfirmEmailByCodeMutationError = ErrorType<Problem>
export type ConfirmEmailByCodeMutationVariables = {data: EmailVerificationCodeRequest;headers?: ConfirmEmailByCodeHeaders}
/**
* @summary Verify an email with the six-digit code from the verification message.
*/
export const useConfirmEmailByCode = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof confirmEmailByCode>>, TError,ConfirmEmailByCodeMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof confirmEmailByCode>>,
TError,
ConfirmEmailByCodeMutationVariables,
TContext
> => {
return useMutation(getConfirmEmailByCodeMutationOptions(options), queryClient);
}
export const getLoginUrl = () => {
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { getConfirmEmailByCodeUrl } from "./endpoints/identity/identity";
import { EmailVerificationCodeRequest, EmailVerificationResult } from "./schemas";
const request = {
email: "candidate@example.com",
code: "482915",
password: "password chosen during registration",
};
describe("generated email code confirmation request", () => {
it("requires the address, the six-digit code, and the registration password", () => {
expect(getConfirmEmailByCodeUrl()).toBe("/api/v1/identity/email-verifications/code");
expect(EmailVerificationCodeRequest.parse(request)).toEqual(request);
expect(EmailVerificationCodeRequest.safeParse({ ...request, code: "48291" }).success).toBe(
false,
);
expect(EmailVerificationCodeRequest.safeParse({ ...request, code: "48291a" }).success).toBe(
false,
);
expect(
EmailVerificationCodeRequest.safeParse({ email: request.email, code: request.code }).success,
).toBe(false);
});
it("returns the same result shape as the link confirmation", () => {
expect(
EmailVerificationResult.parse({
email_verified: true,
scenario: "employer",
onboarding_step: "employer_company",
}),
).toEqual({ email_verified: true, scenario: "employer", onboarding_step: "employer_company" });
});
});
@@ -0,0 +1,27 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const confirmEmailByCodeBodyEmailMin = 3;
export const confirmEmailByCodeBodyEmailMax = 254;
export const confirmEmailByCodeBodyCodeMin = 6;
export const confirmEmailByCodeBodyCodeMax = 6;
export const confirmEmailByCodeBodyCodeRegExp = new RegExp('^[0-9]{6}$');
export const confirmEmailByCodeBodyPasswordMax = 128;
export const ConfirmEmailByCodeBody = zod.object({
"email": zod.email().min(confirmEmailByCodeBodyEmailMin).max(confirmEmailByCodeBodyEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),
"code": zod.string().min(confirmEmailByCodeBodyCodeMin).max(confirmEmailByCodeBodyCodeMax).regex(confirmEmailByCodeBodyCodeRegExp).describe('Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code.'),
"password": zod.string().min(1).max(confirmEmailByCodeBodyPasswordMax).describe('Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist.')
}).describe('Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest.')
export type ConfirmEmailByCodeBody = zod.input<typeof ConfirmEmailByCodeBody>;
export type ConfirmEmailByCodeBodyOutput = zod.output<typeof ConfirmEmailByCodeBody>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const confirmEmailByCodeHeadersOriginMax = 2048;
export const ConfirmEmailByCodeHeaders = zod.object({
"Origin": zod.string().min(1).max(confirmEmailByCodeHeadersOriginMax).exactOptional()
})
export type ConfirmEmailByCodeHeaders = zod.input<typeof ConfirmEmailByCodeHeaders>;
export type ConfirmEmailByCodeHeadersOutput = zod.output<typeof ConfirmEmailByCodeHeaders>;
@@ -0,0 +1,27 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const emailVerificationCodeRequestEmailMin = 3;
export const emailVerificationCodeRequestEmailMax = 254;
export const emailVerificationCodeRequestCodeMin = 6;
export const emailVerificationCodeRequestCodeMax = 6;
export const emailVerificationCodeRequestCodeRegExp = new RegExp('^[0-9]{6}$');
export const emailVerificationCodeRequestPasswordMax = 128;
export const EmailVerificationCodeRequest = zod.object({
"email": zod.email().min(emailVerificationCodeRequestEmailMin).max(emailVerificationCodeRequestEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),
"code": zod.string().min(emailVerificationCodeRequestCodeMin).max(emailVerificationCodeRequestCodeMax).regex(emailVerificationCodeRequestCodeRegExp).describe('Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code.'),
"password": zod.string().min(1).max(emailVerificationCodeRequestPasswordMax).describe('Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist.')
}).describe('Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest.')
export type EmailVerificationCodeRequest = zod.input<typeof EmailVerificationCodeRequest>;
export type EmailVerificationCodeRequestOutput = zod.output<typeof EmailVerificationCodeRequest>;
@@ -8,9 +8,12 @@
export * from './account.zod';
export * from './accountScenario.zod';
export * from './confirmEmailBody.zod';
export * from './confirmEmailByCodeBody.zod';
export * from './confirmEmailByCodeHeaders.zod';
export * from './confirmEmailHeaders.zod';
export * from './consentPurpose.zod';
export * from './csrfToken.zod';
export * from './emailVerificationCodeRequest.zod';
export * from './emailVerificationRequest.zod';
export * from './emailVerificationResendRequest.zod';
export * from './emailVerificationResult.zod';
@@ -26,4 +29,5 @@ export * from './registerAccountHeaders.zod';
export * from './registrationRequest.zod';
export * from './resendEmailVerificationBody.zod';
export * from './session.zod';
export * from './verificationCode.zod';
export * from './verificationToken.zod';
@@ -0,0 +1,18 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const VerificationCodeMin = 6;
export const VerificationCodeMax = 6;
export const VerificationCodeRegExp = new RegExp('^[0-9]{6}$');
export const VerificationCode = zod.string().min(VerificationCodeMin).max(VerificationCodeMax).regex(VerificationCodeRegExp).describe('Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code.')
export type VerificationCode = zod.input<typeof VerificationCode>;
export type VerificationCodeOutput = zod.output<typeof VerificationCode>;