feat(auth): add registration and verification browser flow

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:02:16 +03:00
1 parent 391af7a1ef
commit b2322bc178
41 files changed
+2144 -81

No files matched your search

+237
View File
@@ -0,0 +1,237 @@
import { expect, test, type Page } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("registration, email confirmation, and onboarding", () => {
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token) {
throw new Error("The local registration mailbox fixture is not configured.");
}
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
const body = (await response.json()) as InboxResponse;
return body.messages;
}
async function waitForMessage(email: string, afterId?: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const messages = await readInbox(email);
const matching = messages.filter((message) => message.id !== afterId).at(-1);
if (matching) return matching;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the expected message.");
}
function tokenFromMessage(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function openVerificationLink(page: Page, token: string): Promise<void> {
const target = new URL("/verify-email", process.env.E2E_BASE_URL);
target.hash = `token=${token}`;
try {
await page.goto(target.toString());
} catch {
throw new Error("Could not open the verification page.");
}
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
const fragmentWasRemoved = await page.evaluate(() => window.location.hash === "");
expect(fragmentWasRemoved).toBe(true);
}
async function checkResponsiveKeyboardFlow(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
await page.keyboard.press("Tab");
const hasVisibleKeyboardFocus = await page.evaluate(() => {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false;
const style = getComputedStyle(active);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasVisibleKeyboardFocus).toBe(true);
expect(hasHorizontalOverflow).toBe(false);
}
}
async function captureReviewScreenshot(
page: Page,
scenario: "candidate" | "employer",
state: "registration-accepted" | "email-confirmed",
): Promise<void> {
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
const screenshotPath = `${artifactsDirectory}/${scenario}-${state}.png`;
await page.screenshot({ path: screenshotPath, animations: "disabled" });
}
async function completeScenario(page: Page, scenario: "candidate" | "employer") {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
const email = `auth-${crypto.randomUUID()}@example.test`;
const password = "correct horse battery staple 2026";
const scenarioLabel = scenario === "candidate" ? "Кандидат" : "Работодатель";
const nextStep = scenario === "candidate" ? "Согласия" : "Компания и команда";
await page.goto("/register");
await expect(
page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
).toBeVisible();
await expect(page.getByText(/C4/)).toHaveCount(0);
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: new RegExp(scenarioLabel) }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await checkResponsiveKeyboardFlow(page);
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
await expect(
page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
).toBeVisible();
const registrationContextIsNonSecret = await page.evaluate(() => {
const raw = sessionStorage.getItem("lincodex-registration-context");
if (!raw) return false;
try {
const context: unknown = JSON.parse(raw);
if (typeof context !== "object" || context === null) return false;
return Object.keys(context).every((key) => ["email", "scenario", "accepted"].includes(key));
} catch {
return false;
}
});
expect(registrationContextIsNonSecret).toBe(true);
await page.reload();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
await expect(
page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
).toBeVisible();
await captureReviewScreenshot(page, scenario, "registration-accepted");
const originalMessage = await waitForMessage(email);
const originalToken = tokenFromMessage(originalMessage);
await openVerificationLink(page, originalToken);
await page.route("**/api/v1/identity/email-verifications", (route) =>
route.fulfill({
status: 400,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:verification_token_expired",
title: "Verification token expired",
status: 400,
code: "verification_token_expired",
detail: "Request a new verification link.",
}),
}),
);
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByRole("alert")).toContainText("Срок действия ссылки истек");
await page.unroute("**/api/v1/identity/email-verifications");
await page.waitForTimeout(1100);
const resendResponse = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verification-requests" &&
response.request().method() === "POST",
);
await page.getByLabel("Адрес для письма").fill(email);
await page.getByRole("button", { name: "Отправить письмо повторно" }).click();
expect((await resendResponse).status()).toBe(202);
await expect(page.getByText(/^Запрос принят\./)).toBeVisible();
const resentMessage = await waitForMessage(email, originalMessage.id);
await openVerificationLink(page, tokenFromMessage(resentMessage));
const rejectedConfirmation = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
response.request().method() === "POST",
);
await page.getByLabel("Пароль, выбранный при регистрации").fill("incorrect password test");
await page.getByRole("button", { name: "Подтвердить почту" }).click();
const rejectedResult = await rejectedConfirmation;
const rejectedProblem = (await rejectedResult.json()) as { code?: string };
expect(rejectedResult.status()).toBe(400);
expect(rejectedProblem.code === "verification_token_invalid").toBe(true);
const rejectedToken = String(rejectedResult.request().postDataJSON().token ?? "");
expect(rejectedToken.length > 0).toBe(true);
await expect(page.getByRole("alert")).toContainText("Не удалось подтвердить почту");
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await expect(page.getByLabel("Адрес для письма")).toBeVisible();
const fragmentAfterRejectedPassword = await page.evaluate(() => window.location.hash === "");
expect(fragmentAfterRejectedPassword).toBe(true);
const successfulConfirmation = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
response.request().method() === "POST",
);
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
const retriedToken = String(
(await successfulConfirmation).request().postDataJSON().token ?? "",
);
expect(retriedToken === rejectedToken).toBe(true);
const fragmentAfterPasswordRetry = await page.evaluate(() => window.location.hash === "");
expect(fragmentAfterPasswordRetry).toBe(true);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await captureReviewScreenshot(page, scenario, "email-confirmed");
const registrationContextWasCleared = await page.evaluate(
() => sessionStorage.getItem("lincodex-registration-context") === null,
);
expect(registrationContextWasCleared).toBe(true);
const noSessionResponse = page.waitForResponse(
(response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current",
);
await page.goto(scenario === "candidate" ? "/candidate" : "/employer");
expect((await noSessionResponse).status()).toBe(401);
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: nextStep })).toBeVisible();
const restoredSessionResponse = page.waitForResponse(
(response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current",
);
await page.reload();
expect((await restoredSessionResponse).status()).toBe(200);
await expect(page.getByRole("heading", { name: nextStep })).toBeVisible();
await checkResponsiveKeyboardFlow(page);
}
test("candidate registration resumes at the saved candidate step", async ({ page }) => {
await completeScenario(page, "candidate");
});
test("employer registration resumes at the saved company step", async ({ page }) => {
await completeScenario(page, "employer");
});
});
@@ -0,0 +1,13 @@
import { Navigate } from "react-router-dom";
import { getOnboardingDestination } from "../../entities/session";
import { PlaceholderPage } from "../../pages/placeholder";
import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity";
export function CandidateHomeRoute() {
const session = useGetCurrentSession();
if (!session.data) return <PlaceholderPage screen="candidateHome" />;
if (session.data.account.onboarding_step !== "completed") {
return <Navigate to={getOnboardingDestination(session.data.account)} replace />;
}
return <PlaceholderPage screen="candidateHome" />;
}
+26 -1
View File
@@ -2,6 +2,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity";
import { createQueryClient } from "../providers/query-client";
import { routes } from "./routes";
@@ -15,8 +16,32 @@ async function render(path: string): Promise<string | Response> {
return context;
}
const router = createStaticRouter(handler.dataRoutes, context);
const queryClient = createQueryClient();
const scenario = path.startsWith("/employer") ? "employer" : "candidate";
if (path.startsWith("/candidate") || path.startsWith("/employer")) {
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
account: {
id: "11111111-1111-4111-8111-111111111111",
email: "person@example.test",
email_verified: true,
scenario,
onboarding_step:
path === "/candidate/onboarding"
? "candidate_consents"
: path === "/candidate/profile"
? "candidate_profile"
: path === "/candidate/assessment"
? "candidate_assessment"
: scenario === "candidate"
? "completed"
: "employer_company",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
});
}
return renderToString(
<QueryClientProvider client={createQueryClient()}>
<QueryClientProvider client={queryClient}>
<StaticRouterProvider router={router} context={context} hydrate={false} />
</QueryClientProvider>,
);
+66 -42
View File
@@ -1,4 +1,7 @@
import { redirect, type RouteObject } from "react-router-dom";
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { SessionGate } from "../../entities/session";
import { NotFoundPage } from "../../pages/not-found";
import { PlaceholderPage } from "../../pages/placeholder";
import { StatusPage } from "../../pages/status";
@@ -9,11 +12,11 @@ import { EmployerShell } from "../../widgets/employer-shell";
import { PublicShell } from "../../widgets/public-shell";
import { RootLayout } from "../ui/root-layout";
import { RouteErrorPage } from "../ui/route-error-page";
import { CandidateHomeRoute } from "./candidate-home-route";
/**
* Route tree with three groups: public pages, the candidate cabinet, and the
* employer cabinet. Each group has its own shell and its own not-found page.
* Access control is not implemented yet; the server will enforce it.
* Route tree with public pages and role-specific cabinets. Protected shells
* restore the server session before they render any cabinet child.
*/
export const routes: RouteObject[] = [
{
@@ -24,9 +27,9 @@ export const routes: RouteObject[] = [
element: <PublicShell />,
children: [
{ index: true, element: <WelcomePage /> },
{ path: paths.login, element: <PlaceholderPage screen="login" /> },
{ path: paths.register, element: <PlaceholderPage screen="register" /> },
{ path: paths.verifyEmail, element: <PlaceholderPage screen="verifyEmail" /> },
{ path: paths.login, element: <LoginPage /> },
{ path: paths.register, element: <RegisterPage /> },
{ path: paths.verifyEmail, element: <VerifyEmailPage /> },
{ path: paths.support, element: <PlaceholderPage screen="support" /> },
{ path: paths.status, element: <StatusPage /> },
{ path: "*", element: <NotFoundPage /> },
@@ -36,27 +39,38 @@ export const routes: RouteObject[] = [
path: paths.candidate.root,
element: <CandidateShell />,
children: [
{ index: true, element: <PlaceholderPage screen="candidateHome" /> },
{
path: paths.candidate.onboarding,
element: <PlaceholderPage screen="candidateOnboarding" />,
},
{ path: paths.candidate.profile, element: <PlaceholderPage screen="candidateProfile" /> },
{
path: paths.candidate.assessment,
element: <PlaceholderPage screen="candidateAssessment" />,
},
{ path: paths.candidate.results, element: <PlaceholderPage screen="candidateResults" /> },
{
path: paths.candidate.invitations,
element: <PlaceholderPage screen="candidateInvitations" />,
},
{ path: paths.candidate.privacy, element: <PlaceholderPage screen="candidatePrivacy" /> },
{
path: "*",
element: (
<NotFoundPage homePath={paths.candidate.root} homeLabel="В кабинет кандидата" />
),
element: <SessionGate scenario="candidate" />,
children: [
{ index: true, element: <CandidateHomeRoute /> },
{ path: paths.candidate.onboarding, element: <CandidateOnboardingPage /> },
{
path: paths.candidate.profile,
element: <PlaceholderPage screen="candidateProfile" />,
},
{
path: paths.candidate.assessment,
element: <PlaceholderPage screen="candidateAssessment" />,
},
{
path: paths.candidate.results,
element: <PlaceholderPage screen="candidateResults" />,
},
{
path: paths.candidate.invitations,
element: <PlaceholderPage screen="candidateInvitations" />,
},
{
path: paths.candidate.privacy,
element: <PlaceholderPage screen="candidatePrivacy" />,
},
{
path: "*",
element: (
<NotFoundPage homePath={paths.candidate.root} homeLabel="В кабинет кандидата" />
),
},
],
},
],
},
@@ -64,23 +78,33 @@ export const routes: RouteObject[] = [
path: paths.employer.root,
element: <EmployerShell />,
children: [
// The employer flow starts with the company profile.
{ index: true, loader: () => redirect(paths.employer.company) },
{ path: paths.employer.company, element: <PlaceholderPage screen="employerCompany" /> },
{ path: paths.employer.needs, element: <PlaceholderPage screen="employerNeeds" /> },
{
path: paths.employer.candidates,
element: <PlaceholderPage screen="employerCandidates" />,
},
{
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
},
{
path: "*",
element: (
<NotFoundPage homePath={paths.employer.company} homeLabel="В кабинет работодателя" />
),
element: <SessionGate scenario="employer" />,
children: [
{ index: true, loader: () => redirect(paths.employer.company) },
{
path: paths.employer.company,
element: <PlaceholderPage screen="employerCompany" />,
},
{ path: paths.employer.needs, element: <PlaceholderPage screen="employerNeeds" /> },
{
path: paths.employer.candidates,
element: <PlaceholderPage screen="employerCandidates" />,
},
{
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
},
{
path: "*",
element: (
<NotFoundPage
homePath={paths.employer.company}
homeLabel="В кабинет работодателя"
/>
),
},
],
},
],
},
+2
View File
@@ -0,0 +1,2 @@
export { getOnboardingDestination } from "./model/onboarding-destination";
export { SessionGate } from "./ui/session-gate";
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { Account } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { getOnboardingDestination } from "./onboarding-destination";
function account(
scenario: Account["scenario"],
onboarding_step: Account["onboarding_step"],
): Pick<Account, "scenario" | "onboarding_step"> {
return { scenario, onboarding_step };
}
describe("getOnboardingDestination", () => {
it.each([
["candidate", "candidate_consents", paths.candidate.onboarding],
["candidate", "candidate_profile", paths.candidate.profile],
["candidate", "candidate_questionnaire", paths.candidate.onboarding],
["candidate", "candidate_assessment", paths.candidate.assessment],
["candidate", "completed", paths.candidate.root],
["employer", "employer_company", paths.employer.company],
["employer", "completed", paths.employer.root],
["candidate", "employer_company", paths.candidate.onboarding],
] as const)("routes %s at %s to the saved step", (scenario, step, expected) => {
expect(getOnboardingDestination(account(scenario, step))).toBe(expected);
});
});
@@ -0,0 +1,25 @@
import type { Account } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
/** Resolve the next page from the server-owned onboarding state. */
export function getOnboardingDestination(
account: Pick<Account, "scenario" | "onboarding_step">,
): string {
if (account.scenario === "employer") {
return account.onboarding_step === "completed" ? paths.employer.root : paths.employer.company;
}
switch (account.onboarding_step) {
case "candidate_consents":
case "candidate_questionnaire":
return paths.candidate.onboarding;
case "candidate_profile":
return paths.candidate.profile;
case "candidate_assessment":
return paths.candidate.assessment;
case "employer_company":
return paths.candidate.onboarding;
case "completed":
return paths.candidate.root;
}
}
@@ -0,0 +1,57 @@
import { ApiRequestError } from "../../../shared/api";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import type { Account } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { ButtonLink, ErrorState, ForbiddenState, LoadingState } from "../../../shared/ui";
import { Navigate, Outlet } from "react-router-dom";
type SessionGateProps = {
scenario: Account["scenario"];
};
/** Restores the HttpOnly-cookie session and keeps its CSRF token in query memory. */
export function SessionGate({ scenario }: SessionGateProps) {
const session = useGetCurrentSession();
if (session.isPending) {
return <LoadingState label="Проверяем вход..." />;
}
if (session.isError) {
if (session.error instanceof ApiRequestError && session.error.status === 401) {
return <Navigate to={paths.login} replace />;
}
if (session.error instanceof ApiRequestError && session.error.status === 403) {
return (
<ForbiddenState
error={session.error}
title="Не удалось проверить вход"
description="Обновите страницу и войдите снова."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
);
}
if (session.data.account.scenario !== scenario) {
return (
<ForbiddenState
title="Этот раздел недоступен для вашего сценария"
description="Войдите в кабинет, связанный с выбранным при регистрации сценарием."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
return <Outlet />;
}
@@ -0,0 +1 @@
export { ConfirmEmailForm } from "./ui/confirm-email-form";
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from "vitest";
import {
consumeVerificationToken,
watchVerificationTokenChanges,
type VerificationLinkBrowser,
} from "./consume-verification-token";
function historyRecorder() {
const replaceState = vi.fn();
return { history: { state: { key: "route" }, replaceState }, replaceState };
}
describe("consumeVerificationToken", () => {
it("returns a valid token and removes the fragment while preserving the path and query", () => {
const { history, replaceState } = historyRecorder();
const token = "A".repeat(64);
expect(
consumeVerificationToken(
{ hash: `#token=${token}`, pathname: "/verify-email", search: "?source=mail" },
history,
),
).toBe(token);
expect(replaceState).toHaveBeenCalledWith(history.state, "", "/verify-email?source=mail");
});
it("clears malformed and missing tokens without returning them", () => {
for (const hash of ["#token=short", "#other=value", ""]) {
const { history, replaceState } = historyRecorder();
expect(
consumeVerificationToken({ hash, pathname: "/verify-email", search: "" }, history),
).toBeNull();
expect(replaceState).toHaveBeenCalledWith(history.state, "", "/verify-email");
}
});
it("consumes and removes each new link fragment opened on the same page", () => {
let hash = "";
const listeners = new Set<() => void>();
const state = { key: "route" };
const browser: VerificationLinkBrowser = {
location: {
get hash() {
return hash;
},
pathname: "/verify-email",
search: "",
},
history: {
state,
replaceState: vi.fn((_state, _title, url) => {
hash = new URL(String(url), "https://app.test").hash;
}),
},
addEventListener: vi.fn((_type, listener) => listeners.add(listener)),
removeEventListener: vi.fn((_type, listener) => listeners.delete(listener)),
};
const onTokenChange = vi.fn();
const stopWatching = watchVerificationTokenChanges(browser, onTokenChange);
const firstToken = "A".repeat(64);
const secondToken = "B".repeat(64);
hash = `#token=${firstToken}`;
for (const listener of listeners) listener();
expect(onTokenChange).toHaveBeenLastCalledWith(firstToken);
expect(hash).toBe("");
hash = `#token=${secondToken}`;
for (const listener of listeners) listener();
expect(onTokenChange).toHaveBeenLastCalledWith(secondToken);
expect(hash).toBe("");
stopWatching();
expect(listeners.size).toBe(0);
});
});
@@ -0,0 +1,35 @@
import { VerificationToken } from "../../../shared/api/schemas";
type BrowserLocation = Pick<Location, "hash" | "pathname" | "search">;
type BrowserHistory = Pick<History, "state" | "replaceState">;
export type VerificationLinkBrowser = {
location: BrowserLocation;
history: BrowserHistory;
addEventListener: (type: "hashchange", listener: () => void) => void;
removeEventListener: (type: "hashchange", listener: () => void) => void;
};
/** Read the token once, then remove the full fragment from the visible history entry. */
export function consumeVerificationToken(
location: BrowserLocation,
history: BrowserHistory,
): string | null {
const fragment = location.hash.startsWith("#") ? location.hash.slice(1) : location.hash;
const rawToken = new URLSearchParams(fragment).get("token");
history.replaceState(history.state, "", `${location.pathname}${location.search}`);
return rawToken && VerificationToken.safeParse(rawToken).success ? rawToken : null;
}
/** Listen for a verification link opened in the same tab after the first fragment was consumed. */
export function watchVerificationTokenChanges(
browser: VerificationLinkBrowser,
onTokenChange: (token: string | null) => void,
): () => void {
const handleHashChange = () => {
if (!browser.location.hash) return;
onTokenChange(consumeVerificationToken(browser.location, browser.history));
};
browser.addEventListener("hashchange", handleHashChange);
return () => browser.removeEventListener("hashchange", handleHashChange);
}
@@ -0,0 +1,66 @@
.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);
}
.input[aria-invalid="true"] {
border-color: var(--color-danger);
}
.hint,
.error {
font-size: var(--font-size-s);
}
.hint {
color: var(--color-text-secondary);
}
.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);
}
@@ -0,0 +1,242 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type FormEvent } from "react";
import { useConfirmEmail } from "../../../shared/api/endpoints/identity/identity";
import { Button, ButtonLink, TextLink } from "../../../shared/ui";
import { paths } from "../../../shared/config";
import {
consumeVerificationToken,
watchVerificationTokenChanges,
} from "../model/consume-verification-token";
import styles from "./confirm-email-form.module.css";
function confirmationError(error: unknown): { message: string; expired: boolean } {
const code = error instanceof Error && "code" in error ? String(error.code) : "";
if (code === "verification_token_expired") {
return { message: "Срок действия ссылки истек. Запросите новое письмо.", expired: true };
}
if (code === "verification_token_invalid") {
return {
message:
"Не удалось подтвердить почту. Проверьте введенные данные и попробуйте еще раз или запросите новое письмо.",
expired: false,
};
}
if (code === "rate_limited") {
return { message: "Слишком много попыток. Подождите и повторите попытку.", expired: false };
}
if (code === "csrf_check_failed") {
return {
message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.",
expired: false,
};
}
return {
message: "Не удалось подтвердить почту. Проверьте соединение и повторите попытку.",
expired: false,
};
}
type ConfirmEmailFormProps = {
onResendNeeded: () => void;
onTokenReady: () => void;
onConfirmed: () => void;
};
export function ConfirmEmailForm({
onResendNeeded,
onTokenReady,
onConfirmed,
}: ConfirmEmailFormProps) {
const tokenRef = useRef<string | null>(null);
const initialFragmentConsumedRef = useRef(false);
const tokenGenerationRef = useRef(0);
const {
isPending: isConfirmPending,
mutateAsync,
reset,
} = useConfirmEmail({
mutation: { gcTime: 0 },
});
const [ready, setReady] = useState(false);
const [hasToken, setHasToken] = useState(false);
const [password, setPassword] = useState("");
const [passwordError, setPasswordError] = useState<string | null>(null);
const [formError, setFormError] = useState<string | null>(null);
const [confirmed, setConfirmed] = useState(false);
const handleTokenChange = useCallback(
(token: string | null) => {
tokenGenerationRef.current += 1;
tokenRef.current = token;
reset();
setHasToken(token !== null);
setPassword("");
setPasswordError(null);
setFormError(null);
setConfirmed(false);
if (token) onTokenReady();
else onResendNeeded();
},
[onResendNeeded, onTokenReady, reset],
);
useLayoutEffect(() => {
if (!initialFragmentConsumedRef.current) {
initialFragmentConsumedRef.current = true;
tokenRef.current = consumeVerificationToken(window.location, window.history);
setHasToken(tokenRef.current !== null);
setReady(true);
if (tokenRef.current) onTokenReady();
else onResendNeeded();
}
return watchVerificationTokenChanges(window, handleTokenChange);
}, [handleTokenChange, onResendNeeded, onTokenReady]);
useEffect(
() => () => {
tokenGenerationRef.current += 1;
reset();
},
[reset],
);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const token = tokenRef.current;
if (!token || isConfirmPending) return;
const generation = tokenGenerationRef.current;
const passwordLength = Array.from(password.normalize("NFKC")).length;
if (passwordLength < 1 || passwordLength > 128) {
setPasswordError(
"Введите пароль регистрации длиной от 1 до 128 символов после нормализации.",
);
setFormError(null);
return;
}
setPasswordError(null);
setFormError(null);
try {
await mutateAsync({ data: { token, password } });
if (generation !== tokenGenerationRef.current) return;
reset();
tokenRef.current = null;
setHasToken(false);
setPassword("");
setConfirmed(true);
onConfirmed();
} catch (error: unknown) {
if (generation !== tokenGenerationRef.current) return;
reset();
const result = confirmationError(error);
setFormError(result.message);
if (result.expired) {
tokenRef.current = null;
setHasToken(false);
setPassword("");
onResendNeeded();
} else if (
error instanceof Error &&
"code" in error &&
error.code === "verification_token_invalid"
) {
setPassword("");
onResendNeeded();
}
}
}
if (!ready) {
return (
<p className={styles.status} role="status">
Открываем безопасную ссылку...
</p>
);
}
if (confirmed) {
return (
<div className={styles.form}>
<div className={styles.notice} role="status" aria-live="polite">
Почта подтверждена. Войдите с паролем, который вы выбрали при регистрации. После входа
сервис откроет сохраненный шаг.
</div>
<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>
</div>
);
}
if (!hasToken) {
return (
<div className={styles.form}>
{formError ? (
<p className={styles.alert} role="alert">
{formError}
</p>
) : (
<p className={styles.hint}>
В ссылке нет действующего токена. Укажите адрес, чтобы запросить новое письмо.
</p>
)}
<TextLink to={paths.login}>Перейти ко входу</TextLink>
</div>
);
}
return (
<div className={styles.form}>
{formError ? (
<p className={styles.alert} role="alert">
{formError}
</p>
) : null}
<form onSubmit={(event) => void submit(event)} noValidate>
<div className={styles.form}>
<div className={styles.field}>
<label className={styles.label} htmlFor="verification-password">
Пароль, выбранный при регистрации
</label>
<input
className={styles.input}
id="verification-password"
name="password"
type="password"
autoComplete="new-password"
required
maxLength={512}
value={password}
disabled={isConfirmPending}
aria-invalid={Boolean(passwordError)}
aria-describedby={
passwordError ? "verification-password-error" : "verification-password-hint"
}
onChange={(event) => {
setPassword(event.currentTarget.value);
setPasswordError(null);
setFormError(null);
}}
/>
{passwordError ? (
<p className={styles.error} id="verification-password-error">
{passwordError}
</p>
) : (
<p className={styles.hint} id="verification-password-hint">
Для подтверждения нужно ввести пароль, указанный в этой регистрации.
</p>
)}
</div>
<div className={styles.actions}>
<Button type="submit" isBusy={isConfirmPending}>
{isConfirmPending ? "Подтверждаем..." : "Подтвердить почту"}
</Button>
<TextLink to={paths.login}>Уже подтвердили? Войти</TextLink>
</div>
<p className={styles.status} role="status" aria-live="polite">
{isConfirmPending ? "Проверяем ссылку..." : ""}
</p>
</div>
</form>
</div>
);
}
@@ -0,0 +1,2 @@
export { RegisterForm } from "./ui/register-form";
export type { RegistrationDraft } from "./ui/register-form";
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { validateNewPassword, validateRegistration } from "./validation";
describe("registration validation", () => {
it("counts NFKC-normalized Unicode code points", () => {
expect(validateNewPassword("😀".repeat(15))).toBeUndefined();
expect(validateNewPassword("12345678901234")).toContain("не менее 15");
expect(validateNewPassword("😀".repeat(129))).toContain("не более 128");
});
it("requires a valid address, scenario, and separately accepted consent", () => {
expect(
validateRegistration({
email: "person@example.test",
password: "a secure phrase with enough length",
scenario: "candidate",
acceptedConsent: true,
}),
).toEqual({});
expect(
validateRegistration({
email: "not-an-email",
password: "a secure phrase with enough length",
scenario: "",
acceptedConsent: false,
}),
).toEqual({
email: "Введите корректный адрес электронной почты.",
scenario: "Выберите сценарий.",
consent: "Подтвердите согласие после прочтения текста.",
});
});
});
@@ -0,0 +1,43 @@
import { EmailAddress } from "../../../shared/api/schemas";
export type RegistrationErrors = {
email?: string;
password?: string;
scenario?: string;
consent?: string;
};
/** Apply the server's NFKC and Unicode code-point length rules before sending. */
export function validateNewPassword(password: string): string | undefined {
const length = Array.from(password.normalize("NFKC")).length;
if (length < 15) {
return "Введите не менее 15 символов после нормализации.";
}
if (length > 128) {
return "Введите не более 128 символов после нормализации.";
}
return undefined;
}
export function validateRegistration(input: {
email: string;
password: string;
scenario: string;
acceptedConsent: boolean;
}): RegistrationErrors {
const errors: RegistrationErrors = {};
if (!EmailAddress.safeParse(input.email).success) {
errors.email = "Введите корректный адрес электронной почты.";
}
const passwordError = validateNewPassword(input.password);
if (passwordError) {
errors.password = passwordError;
}
if (input.scenario !== "candidate" && input.scenario !== "employer") {
errors.scenario = "Выберите сценарий.";
}
if (!input.acceptedConsent) {
errors.consent = "Подтвердите согласие после прочтения текста.";
}
return errors;
}
@@ -0,0 +1,150 @@
.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);
}
.input[aria-invalid="true"] {
border-color: var(--color-danger);
}
.hint,
.error,
.choice-description {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.error {
color: var(--color-danger);
}
.choices {
display: grid;
gap: var(--space-3);
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.choices legend {
padding-inline: var(--space-2);
font-weight: var(--font-weight-bold);
}
.choice {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: var(--space-3);
align-items: start;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
cursor: pointer;
}
.choice input {
width: 1.1rem;
height: 1.1rem;
margin-top: 0.2rem;
accent-color: var(--color-accent);
}
.choice-body {
display: grid;
gap: var(--space-1);
}
.consent {
display: grid;
gap: var(--space-3);
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.consent-title {
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.consent-text {
max-height: 16rem;
overflow: auto;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-canvas);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.consent-choice {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: var(--space-3);
align-items: start;
}
.consent-choice input {
width: 1.1rem;
height: 1.1rem;
margin-top: 0.2rem;
accent-color: var(--color-accent);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
}
.notice {
padding: var(--space-4);
border-left: var(--line-strong) solid var(--color-accent);
background: var(--color-surface);
}
.notice p + p {
margin-top: var(--space-2);
}
.alert {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-danger);
background: var(--color-surface);
color: var(--color-text);
}
.status {
min-height: 1.5em;
color: var(--color-text-secondary);
}
@media (width >= 48rem) {
.consent-text {
max-height: 20rem;
}
}
@@ -0,0 +1,369 @@
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import {
useGetConsentText,
useRegisterAccount,
} from "../../../shared/api/endpoints/identity/identity";
import type { Account } from "../../../shared/api/schemas";
import { Button, ErrorState, LoadingState, TextLink } from "../../../shared/ui";
import { paths } from "../../../shared/config";
import { validateRegistration } from "../model/validation";
import styles from "./register-form.module.css";
type Scenario = Account["scenario"];
export type RegistrationDraft = {
email: string;
scenario: Scenario | "";
};
type RegisterFormProps = {
initialEmail?: string;
initialScenario?: Scenario | "";
onDraftChange?: (draft: RegistrationDraft) => void;
onAccepted: (draft: RegistrationDraft) => void;
};
type FieldErrors = {
email?: string;
password?: string;
scenario?: string;
consent?: string;
};
function createIdempotencyKey(): string {
return window.crypto.randomUUID();
}
function registrationError(error: unknown): {
message: string;
refreshConsent: boolean;
clearIdempotencyKey: boolean;
} {
if (!(error instanceof Error) || !("code" in error)) {
return {
message: "Не удалось отправить запрос. Повторите попытку.",
refreshConsent: false,
clearIdempotencyKey: false,
};
}
const code = String(error.code);
if (code === "validation_failed" && "fieldErrors" in error) {
const fields = error.fieldErrors as readonly { pointer?: string }[];
if (fields.some((field) => field.pointer === "/consent_c1/text_version")) {
return {
message: "Текст согласия обновился. Прочитайте новую версию и подтвердите ее.",
refreshConsent: true,
clearIdempotencyKey: true,
};
}
if (fields.some((field) => field.pointer === "/password")) {
return {
message: "Этот пароль не подходит. Выберите другой пароль и повторите попытку.",
refreshConsent: false,
clearIdempotencyKey: false,
};
}
}
if (code === "rate_limited") {
return {
message: "Слишком много запросов. Подождите и попробуйте снова.",
refreshConsent: false,
clearIdempotencyKey: false,
};
}
if (code === "idempotency_key_reused") {
return {
message: "Не удалось повторить запрос. Отправьте форму еще раз.",
refreshConsent: false,
clearIdempotencyKey: true,
};
}
if (code === "csrf_check_failed") {
return {
message: "Не удалось проверить источник запроса. Обновите страницу и попробуйте снова.",
refreshConsent: false,
clearIdempotencyKey: false,
};
}
return {
message: "Не удалось отправить запрос. Повторите попытку.",
refreshConsent: false,
clearIdempotencyKey: false,
};
}
function errorId(id: string, name: keyof FieldErrors): string {
return `${id}-${name}-error`;
}
export function RegisterForm({
initialEmail = "",
initialScenario = "",
onDraftChange,
onAccepted,
}: RegisterFormProps) {
const id = useId();
const consent = useGetConsentText("c1");
const registration = useRegisterAccount({ mutation: { gcTime: 0 } });
const idempotencyKey = useRef<string | null>(null);
const [email, setEmail] = useState(initialEmail);
const [password, setPassword] = useState("");
const [scenario, setScenario] = useState<Scenario | "">(initialScenario);
const [acceptedVersion, setAcceptedVersion] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
const [formError, setFormError] = useState<string | null>(null);
const previousConsentVersion = useRef<string | undefined>(undefined);
const currentConsentVersion = consent.data?.text_version;
useEffect(() => {
if (
currentConsentVersion &&
previousConsentVersion.current &&
currentConsentVersion !== previousConsentVersion.current
) {
idempotencyKey.current = null;
setAcceptedVersion(null);
setFormError("Текст согласия обновился. Прочитайте новую версию и подтвердите ее.");
}
if (currentConsentVersion) previousConsentVersion.current = currentConsentVersion;
}, [currentConsentVersion]);
function changed() {
idempotencyKey.current = null;
setFieldErrors({});
setFormError(null);
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (registration.isPending || !consent.data || consent.isError) return;
const errors = validateRegistration({
email,
password,
scenario,
acceptedConsent: Boolean(consent.data && acceptedVersion === consent.data.text_version),
});
setFieldErrors(errors);
setFormError(null);
if (Object.keys(errors).length > 0 || !scenario) return;
const body = {
email,
password,
scenario,
consent_c1: { text_version: consent.data.text_version, accepted: true as const },
};
idempotencyKey.current ??= createIdempotencyKey();
try {
await registration.mutateAsync({
data: body,
headers: { "Idempotency-Key": idempotencyKey.current },
});
setPassword("");
onAccepted({ email, scenario });
} catch (error: unknown) {
const result = registrationError(error);
setFormError(result.message);
if (result.clearIdempotencyKey) idempotencyKey.current = null;
if (result.refreshConsent) {
setAcceptedVersion(null);
await consent.refetch();
}
}
}
return (
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
{consent.isPending ? <LoadingState label="Загружаем текст согласия..." /> : null}
{consent.isError ? (
<ErrorState
error={consent.error}
isRetrying={consent.isRefetching}
onRetry={() => void consent.refetch()}
title="Не удалось загрузить текст согласия"
/>
) : null}
<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"
required
maxLength={254}
value={email}
disabled={registration.isPending}
aria-invalid={Boolean(fieldErrors.email)}
aria-describedby={fieldErrors.email ? errorId(id, "email") : undefined}
onChange={(event) => {
changed();
const nextEmail = event.currentTarget.value;
setEmail(nextEmail);
onDraftChange?.({ email: nextEmail, scenario });
}}
/>
{fieldErrors.email ? (
<p className={styles.error} id={errorId(id, "email")}>
{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"
required
maxLength={512}
value={password}
disabled={registration.isPending}
aria-invalid={Boolean(fieldErrors.password)}
aria-describedby={`${id}-password-hint${fieldErrors.password ? ` ${errorId(id, "password")}` : ""}`}
onChange={(event) => {
changed();
setPassword(event.currentTarget.value);
}}
/>
<p className={styles.hint} id={`${id}-password-hint`}>
От 15 до 128 символов после нормализации. Допустима фраза из нескольких слов.
</p>
{fieldErrors.password ? (
<p className={styles.error} id={errorId(id, "password")}>
{fieldErrors.password}
</p>
) : null}
</div>
<fieldset
className={styles.choices}
aria-describedby={fieldErrors.scenario ? errorId(id, "scenario") : undefined}
>
<legend>Сценарий</legend>
{(
[
["candidate", "Кандидат", "Ищу работу и хочу подтвердить навыки."],
["employer", "Работодатель", "Представляю компанию и ищу кандидатов."],
] as const
).map(([value, label, description]) => (
<label className={styles.choice} key={value} htmlFor={`${id}-${value}`}>
<input
id={`${id}-${value}`}
name="scenario"
type="radio"
value={value}
checked={scenario === value}
required
disabled={registration.isPending}
onChange={() => {
changed();
setScenario(value);
onDraftChange?.({ email, scenario: value });
}}
/>
<span className={styles["choice-body"]}>
<span className={styles.label}>{label}</span>
<span className={styles["choice-description"]}>{description}</span>
</span>
</label>
))}
{fieldErrors.scenario ? (
<p className={styles.error} id={errorId(id, "scenario")}>
{fieldErrors.scenario}
</p>
) : null}
</fieldset>
{consent.data ? (
<section className={styles.consent} aria-labelledby={`${id}-consent-title`}>
<h2 className={styles["consent-title"]} id={`${id}-consent-title`}>
Согласие C1 на обработку персональных данных
</h2>
<p className={styles.hint}>Версия текста: {consent.data.text_version}</p>
<div
className={styles["consent-text"]}
role="region"
tabIndex={0}
aria-label="Полный текст согласия C1"
>
{consent.data.text}
</div>
<label className={styles["consent-choice"]} htmlFor={`${id}-consent`}>
<input
id={`${id}-consent`}
name="consent_c1"
type="checkbox"
checked={Boolean(currentConsentVersion && acceptedVersion === currentConsentVersion)}
required
disabled={registration.isPending}
aria-invalid={Boolean(
fieldErrors.consent ||
(acceptedVersion && acceptedVersion !== currentConsentVersion),
)}
aria-describedby={
fieldErrors.consent
? errorId(id, "consent")
: acceptedVersion && acceptedVersion !== currentConsentVersion
? `${id}-consent-version-error`
: undefined
}
onChange={(event) => {
changed();
setAcceptedVersion(
event.currentTarget.checked ? (currentConsentVersion ?? null) : null,
);
idempotencyKey.current = null;
}}
/>
<span>Я прочитал(а) текст согласия C1 и принимаю его.</span>
</label>
{acceptedVersion && acceptedVersion !== currentConsentVersion ? (
<p className={styles.error} id={`${id}-consent-version-error`}>
Текст согласия изменился. Прочитайте новую версию и подтвердите ее.
</p>
) : null}
{fieldErrors.consent ? (
<p className={styles.error} id={errorId(id, "consent")}>
{fieldErrors.consent}
</p>
) : null}
</section>
) : null}
{formError ? (
<p className={styles.alert} role="alert">
{formError}
</p>
) : null}
{consent.isError && consent.error ? (
<p className={styles.hint}>Без опубликованного текста C1 отправить регистрацию нельзя.</p>
) : null}
<div className={styles.actions}>
<Button
type="submit"
disabled={!consent.data || consent.isError}
isBusy={registration.isPending}
>
{registration.isPending ? "Отправляем..." : "Создать аккаунт"}
</Button>
<TextLink to={paths.login}>Уже есть аккаунт? Войти</TextLink>
</div>
<p className={styles.status} role="status" aria-live="polite">
{registration.isPending ? "Отправляем запрос на регистрацию..." : ""}
</p>
</form>
);
}
@@ -0,0 +1 @@
export { ResendVerificationForm } from "./ui/resend-verification-form";
@@ -0,0 +1,48 @@
.form {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.field {
display: grid;
gap: var(--space-2);
}
.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);
}
.input[aria-invalid="true"] {
border-color: var(--color-danger);
}
.error,
.message {
font-size: var(--font-size-s);
}
.error {
color: var(--color-danger);
}
.message {
min-height: 1.5em;
color: var(--color-text-secondary);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
}
@@ -0,0 +1,87 @@
import { useId, useState, type FormEvent } from "react";
import { useResendEmailVerification } from "../../../shared/api/endpoints/identity/identity";
import { EmailAddress } from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui";
import styles from "./resend-verification-form.module.css";
type ResendVerificationFormProps = {
initialEmail?: string;
};
export function ResendVerificationForm({ initialEmail = "" }: ResendVerificationFormProps) {
const id = useId();
const resend = useResendEmailVerification({ mutation: { gcTime: 0 } });
const [email, setEmail] = useState(initialEmail);
const [fieldError, setFieldError] = useState<string | null>(null);
const [message, setMessage] = useState("");
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (resend.isPending) return;
if (!EmailAddress.safeParse(email).success) {
setFieldError("Введите корректный адрес электронной почты.");
setMessage("");
return;
}
setFieldError(null);
setMessage("");
try {
await resend.mutateAsync({ data: { email } });
setMessage(
"Запрос принят. Если для этого адреса доступна повторная отправка, письмо будет отправлено.",
);
} catch (error: unknown) {
const code = error instanceof Error && "code" in error ? String(error.code) : "";
if (code === "rate_limited") {
setMessage("Слишком много запросов. Подождите и повторите попытку.");
} else if (code === "csrf_check_failed") {
setMessage("Не удалось проверить источник запроса. Обновите страницу и повторите попытку.");
} else {
setMessage("Не удалось отправить запрос. Повторите попытку.");
}
}
}
return (
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
<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"
required
maxLength={254}
value={email}
disabled={resend.isPending}
aria-invalid={Boolean(fieldError)}
aria-describedby={fieldError ? `${id}-email-error` : undefined}
onChange={(event) => {
setEmail(event.currentTarget.value);
setFieldError(null);
setMessage("");
}}
/>
{fieldError ? (
<p className={styles.error} id={`${id}-email-error`}>
{fieldError}
</p>
) : null}
</div>
<div className={styles.actions}>
<Button type="submit" variant="secondary" isBusy={resend.isPending}>
{resend.isPending ? "Отправляем..." : "Отправить письмо повторно"}
</Button>
</div>
<p className={styles.message} role="status" aria-live="polite">
{resend.isPending ? "Отправляем запрос..." : message}
</p>
</form>
);
}
+1
View File
@@ -0,0 +1 @@
export { SignInForm } from "./ui/sign-in-form";
@@ -0,0 +1,38 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import { establishSession } from "./establish-session";
describe("establishSession", () => {
it("removes cached account data before keeping the new session in memory", () => {
const queryClient = new QueryClient();
const previousProfileKey = ["/api/v1/candidate/profile"] as const;
const nextSession = {
account: {
id: "22222222-2222-4222-8222-222222222222",
email: "new@example.test",
email_verified: true,
scenario: "employer",
onboarding_step: "employer_company",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "B".repeat(43),
} as const;
queryClient.setQueryData(previousProfileKey, {
accountId: "11111111-1111-4111-8111-111111111111",
privateNotes: ["previous account data"],
});
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
...nextSession,
account: { ...nextSession.account, id: "11111111-1111-4111-8111-111111111111" },
csrf_token: "A".repeat(43),
});
establishSession(queryClient, nextSession);
expect(queryClient.getQueryData(previousProfileKey)).toBeUndefined();
expect(queryClient.getQueryData(getGetCurrentSessionQueryKey())).toEqual(nextSession);
expect(queryClient.getQueryCache().getAll()).toHaveLength(1);
});
});
@@ -0,0 +1,9 @@
import type { QueryClient } from "@tanstack/react-query";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
/** Drop data from any previous account before caching the new in-memory session. */
export function establishSession(queryClient: QueryClient, session: Session): void {
queryClient.clear();
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
}
@@ -0,0 +1,60 @@
.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);
}
.input[aria-invalid="true"] {
border-color: var(--color-danger);
}
.error,
.hint {
font-size: var(--font-size-s);
}
.error,
.alert {
color: var(--color-danger);
}
.alert {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-danger);
background: var(--color-surface);
}
.hint {
color: var(--color-text-secondary);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
}
.status {
min-height: 1.5em;
color: var(--color-text-secondary);
}
@@ -0,0 +1,153 @@
import { useQueryClient } from "@tanstack/react-query";
import { useId, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import { useLogin } from "../../../shared/api/endpoints/identity/identity";
import { EmailAddress } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { getOnboardingDestination } from "../../../entities/session";
import { Button, TextLink } from "../../../shared/ui";
import { establishSession } from "../model/establish-session";
import styles from "./sign-in-form.module.css";
type SignInFormProps = {
onUnverified: (email: string) => void;
onSignedIn: () => void;
};
export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
const id = useId();
const queryClient = useQueryClient();
const navigate = useNavigate();
const login = useLogin({ mutation: { gcTime: 0 } });
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [fieldError, setFieldError] = useState<{ email?: string; password?: string }>({});
const [formError, setFormError] = useState<string | null>(null);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (login.isPending) return;
const errors: typeof fieldError = {};
if (!EmailAddress.safeParse(email).success) {
errors.email = "Введите корректный адрес электронной почты.";
}
const passwordLength = Array.from(password.normalize("NFKC")).length;
if (passwordLength < 1 || passwordLength > 128) {
errors.password = "Введите пароль длиной не более 128 символов.";
}
setFieldError(errors);
setFormError(null);
if (Object.keys(errors).length > 0) return;
try {
const session = await login.mutateAsync({ data: { email, password } });
establishSession(queryClient, session);
setPassword("");
onSignedIn();
await navigate(getOnboardingDestination(session.account), { replace: true });
} catch (error: unknown) {
if (error instanceof ApiRequestError && error.code === "email_not_verified") {
onUnverified(email);
setFormError("Почта не подтверждена. Запросите новое письмо и перейдите по ссылке.");
} else if (error instanceof ApiRequestError && error.code === "invalid_credentials") {
setFormError("Не удалось войти. Проверьте адрес и пароль.");
} else if (error instanceof ApiRequestError && error.code === "rate_limited") {
setFormError("Слишком много попыток. Подождите и попробуйте снова.");
} else if (error instanceof ApiRequestError && error.code === "csrf_check_failed") {
setFormError(
"Не удалось проверить источник запроса. Обновите страницу и попробуйте снова.",
);
} else {
setFormError("Не удалось выполнить вход. Проверьте соединение и повторите попытку.");
}
}
}
function changed() {
setFieldError({});
setFormError(null);
onUnverified("");
}
return (
<div className={styles.form}>
<form onSubmit={(event) => void submit(event)} noValidate>
<div className={styles.form}>
<div className={styles.field}>
<label className={styles.label} htmlFor={`${id}-email`}>
Электронная почта
</label>
<input
className={styles.input}
id={`${id}-email`}
name="email"
type="email"
autoComplete="username"
required
maxLength={254}
value={email}
disabled={login.isPending}
aria-invalid={Boolean(fieldError.email)}
aria-describedby={fieldError.email ? `${id}-email-error` : undefined}
onChange={(event) => {
changed();
setEmail(event.currentTarget.value);
}}
/>
{fieldError.email ? (
<p className={styles.error} id={`${id}-email-error`}>
{fieldError.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="current-password"
required
maxLength={512}
value={password}
disabled={login.isPending}
aria-invalid={Boolean(fieldError.password)}
aria-describedby={fieldError.password ? `${id}-password-error` : undefined}
onChange={(event) => {
changed();
setPassword(event.currentTarget.value);
}}
/>
{fieldError.password ? (
<p className={styles.error} id={`${id}-password-error`}>
{fieldError.password}
</p>
) : null}
</div>
{formError ? (
<p className={styles.alert} role="alert">
{formError}
</p>
) : null}
<div className={styles.actions}>
<Button type="submit" isBusy={login.isPending}>
{login.isPending ? "Входим..." : "Войти"}
</Button>
<TextLink to={paths.register}>Создать аккаунт</TextLink>
</div>
<p className={styles.status} role="status" aria-live="polite">
{login.isPending ? "Проверяем учетные данные..." : ""}
</p>
</div>
</form>
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
export { LoginPage } from "./ui/login-page";
export { RegisterPage } from "./ui/register-page";
export { VerifyEmailPage } from "./ui/verify-email-page";
@@ -0,0 +1,48 @@
import type { RegistrationDraft } from "../../../features/register-account";
const storageKey = "lincodex-registration-context";
export type RegistrationContext = RegistrationDraft & {
accepted: boolean;
};
const emptyContext: RegistrationContext = { email: "", scenario: "", accepted: false };
export function readRegistrationContext(): RegistrationContext {
if (typeof window === "undefined") return emptyContext;
try {
const raw = window.sessionStorage.getItem(storageKey);
if (!raw) return emptyContext;
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return emptyContext;
const value = parsed as Record<string, unknown>;
const email = typeof value.email === "string" ? value.email : "";
const scenario =
value.scenario === "candidate" || value.scenario === "employer" ? value.scenario : "";
return {
email,
scenario,
accepted: value.accepted === true && email.length > 0 && scenario !== "",
};
} catch {
return emptyContext;
}
}
export function writeRegistrationContext(context: RegistrationContext): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(storageKey, JSON.stringify(context));
} catch {
// Registration remains usable when the browser blocks session storage.
}
}
export function clearRegistrationContext(): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.removeItem(storageKey);
} catch {
// Registration remains usable when the browser blocks session storage.
}
}
+26
View File
@@ -0,0 +1,26 @@
import { useCallback, useState } from "react";
import { ResendVerificationForm } from "../../../features/resend-email-verification";
import { SignInForm } from "../../../features/sign-in";
import { Page, Section } from "../../../shared/ui";
import { clearRegistrationContext } from "../model/registration-context";
export function LoginPage() {
const [unverifiedEmail, setUnverifiedEmail] = useState("");
const clearPendingRegistration = useCallback(() => {
setUnverifiedEmail("");
clearRegistrationContext();
}, []);
return (
<Page title="Вход" lead="Войдите, чтобы продолжить настройку аккаунта с сохраненного шага.">
<Section title="Войти в аккаунт">
<SignInForm onUnverified={setUnverifiedEmail} onSignedIn={clearPendingRegistration} />
</Section>
{unverifiedEmail ? (
<Section title="Повторная отправка письма">
<ResendVerificationForm initialEmail={unverifiedEmail} />
</Section>
) : null}
</Page>
);
}
@@ -0,0 +1,68 @@
import { useState } from "react";
import { RegisterForm, type RegistrationDraft } from "../../../features/register-account";
import { ResendVerificationForm } from "../../../features/resend-email-verification";
import { Button, Page, Section, TextLink } from "../../../shared/ui";
import { paths } from "../../../shared/config";
import {
clearRegistrationContext,
readRegistrationContext,
writeRegistrationContext,
type RegistrationContext,
} from "../model/registration-context";
function scenarioLabel(scenario: RegistrationDraft["scenario"]): string {
return scenario === "employer" ? "работодатель" : "кандидат";
}
export function RegisterPage() {
const [context, setContext] = useState<RegistrationContext>(readRegistrationContext);
function saveDraft(draft: RegistrationDraft) {
const next = { ...draft, accepted: false };
setContext(next);
writeRegistrationContext(next);
}
function markAccepted(draft: RegistrationDraft) {
const next = { ...draft, accepted: true };
setContext(next);
writeRegistrationContext(next);
}
function startAgain() {
clearRegistrationContext();
setContext({ email: "", scenario: "", accepted: false });
}
return (
<Page
title="Регистрация"
lead="Создайте аккаунт и выберите, как вы будете пользоваться платформой."
>
{context.accepted ? (
<div>
<Section title="Запрос принят">
<p role="status" aria-live="polite">
Если для этого адреса требуется подтверждение, письмо будет отправлено. Выбранный
сценарий: {scenarioLabel(context.scenario)}.
</p>
<ResendVerificationForm initialEmail={context.email} />
<TextLink to={paths.login}>Перейти ко входу</TextLink>
<Button type="button" variant="quiet" onClick={startAgain}>
Начать другую регистрацию
</Button>
</Section>
</div>
) : (
<Section title="Данные аккаунта">
<RegisterForm
initialEmail={context.email}
initialScenario={context.scenario}
onDraftChange={saveDraft}
onAccepted={markAccepted}
/>
</Section>
)}
</Page>
);
}
@@ -0,0 +1,35 @@
import { useCallback, useState } from "react";
import { ConfirmEmailForm } from "../../../features/confirm-email";
import { ResendVerificationForm } from "../../../features/resend-email-verification";
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 finishConfirmation = useCallback(() => {
setNeedsResend(false);
clearRegistrationContext();
}, []);
return (
<Page
title="Подтверждение почты"
lead="Подтвердите адрес ссылкой из письма и паролем регистрации."
>
<Section title="Подтвердить адрес">
<ConfirmEmailForm
onResendNeeded={requestResend}
onTokenReady={linkReady}
onConfirmed={finishConfirmation}
/>
</Section>
{needsResend ? (
<Section title="Запросить новое письмо">
<ResendVerificationForm />
</Section>
) : null}
</Page>
);
}
@@ -0,0 +1 @@
export { CandidateOnboardingPage } from "./ui/candidate-onboarding-page";
@@ -0,0 +1,48 @@
import { Navigate } from "react-router-dom";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { getOnboardingDestination } from "../../../entities/session";
import { paths } from "../../../shared/config";
import { LoadingState, Page, Section, StatusView } from "../../../shared/ui";
export function CandidateOnboardingPage() {
const session = useGetCurrentSession();
if (!session.data) return <LoadingState label="Загружаем сохраненный шаг..." />;
const { onboarding_step: step, scenario } = session.data.account;
if (scenario !== "candidate") {
return (
<StatusView
kind="forbidden"
title="Этот шаг недоступен для вашего сценария"
description="Откройте кабинет, связанный с выбранным сценарием."
/>
);
}
if (step !== "candidate_consents" && step !== "candidate_questionnaire") {
const destination = getOnboardingDestination(session.data.account);
if (destination === paths.candidate.onboarding) {
return (
<StatusView
kind="error"
title="Не удалось определить сохраненный шаг"
description="Обновите страницу или обратитесь в поддержку."
/>
);
}
return <Navigate to={destination} replace />;
}
const stepTitle = step === "candidate_consents" ? "Согласия" : "Анкета";
const description =
step === "candidate_consents"
? "Следующий сохраненный шаг - согласия кандидата. Согласие C1 уже было показано отдельно при регистрации."
: "Следующий сохраненный шаг - анкета кандидата. После ее сохранения сервер откроет следующий этап.";
return (
<Page title="Первые шаги" eyebrow="Кабинет кандидата">
<Section title={stepTitle} description={description}>
<p>Этот шаг сохранен в аккаунте и будет открыт после следующего входа.</p>
</Section>
</Page>
);
}