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

+149 -55
View File
@@ -48,6 +48,17 @@ test.describe("registration, email confirmation, and onboarding", () => {
return token;
}
function codeFromMessage(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const code = /Код подтверждения: ([0-9]{6})\b/.exec(content)?.[1];
if (!code) throw new Error("The local registration message had no verification code.");
return code;
}
function wrongCodeFor(code: string): string {
return code === "000000" ? "000001" : "000000";
}
async function openVerificationLink(page: Page, token: string): Promise<void> {
const target = new URL("/verify-email", process.env.E2E_BASE_URL);
target.hash = `token=${token}`;
@@ -90,6 +101,56 @@ test.describe("registration, email confirmation, and onboarding", () => {
await page.screenshot({ path: screenshotPath, animations: "disabled" });
}
async function registerThroughForm(
page: Page,
scenario: "candidate" | "employer",
email: string,
password: string,
): Promise<void> {
const scenarioLabel = 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 page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
await expect(
page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
).toBeVisible();
}
async function signInAndResume(
page: Page,
scenario: "candidate" | "employer",
email: string,
password: string,
nextStep: string,
): Promise<void> {
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);
}
async function completeScenario(page: Page, scenario: "candidate" | "employer") {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
@@ -113,6 +174,15 @@ test.describe("registration, email confirmation, and onboarding", () => {
await expect(
page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
).toBeVisible();
await expect(page.getByRole("heading", { name: "Введите код из письма" })).toBeVisible();
await expect(page.getByLabel("Код из письма", { exact: true })).toBeVisible();
// The password is held in memory only: no browser storage keeps it, and
// the stored context has only the address, the scenario, and the flag.
const storedText = await page.evaluate(() =>
JSON.stringify({ ...localStorage, ...sessionStorage }),
);
expect(storedText.includes(password)).toBe(false);
const registrationContextIsNonSecret = await page.evaluate(() => {
const raw = sessionStorage.getItem("lincodex-registration-context");
if (!raw) return false;
@@ -126,17 +196,79 @@ test.describe("registration, email confirmation, and onboarding", () => {
});
expect(registrationContextIsNonSecret).toBe(true);
// A reload drops the memory copy, so the step asks for the password again.
await page.reload();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
await expect(
page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)),
).toBeVisible();
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await captureReviewScreenshot(page, scenario, "registration-accepted");
const originalMessage = await waitForMessage(email);
const originalToken = tokenFromMessage(originalMessage);
await openVerificationLink(page, originalToken);
const message = await waitForMessage(email);
const code = codeFromMessage(message);
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByLabel("Код из письма", { exact: true }).fill(wrongCodeFor(code));
const rejectedConfirmation = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verifications/code" &&
response.request().method() === "POST",
);
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).toBe("verification_token_invalid");
await expect(page.getByRole("alert")).toContainText("Код не подошел");
await expect(page.getByLabel("Код из письма", { exact: true })).toHaveValue("");
// Pasted text with a space keeps only the digits, so the code still fits.
const confirmation = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/email-verifications/code" &&
response.request().method() === "POST",
);
await page
.getByLabel("Код из письма", { exact: true })
.fill(`${code.slice(0, 3)} ${code.slice(3)}`);
await page.getByRole("button", { name: "Подтвердить код" }).click();
expect((await confirmation).status()).toBe(200);
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);
await signInAndResume(page, scenario, email, password, nextStep);
}
test("candidate registration confirms with the emailed code and resumes at the saved step", async ({
page,
}) => {
await completeScenario(page, "candidate");
});
test("employer registration confirms with the emailed code and resumes at the saved step", async ({
page,
}) => {
await completeScenario(page, "employer");
});
// The link form is the labelled region "Подтвердить адрес"; the code step has
// its own password field with the same label.
function linkPassword(page: Page) {
return page
.getByRole("region", { name: "Подтвердить адрес" })
.getByLabel("Пароль, выбранный при регистрации");
}
test("the link from the same message still confirms the registration", async ({ page }) => {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
const email = `auth-link-${crypto.randomUUID()}@example.test`;
const password = "correct horse battery staple 2026";
await registerThroughForm(page, "candidate", email, password);
const originalMessage = await waitForMessage(email);
await openVerificationLink(page, tokenFromMessage(originalMessage));
await page.route("**/api/v1/identity/email-verifications", (route) =>
route.fulfill({
status: 400,
@@ -150,19 +282,21 @@ test.describe("registration, email confirmation, and onboarding", () => {
}),
}),
);
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await linkPassword(page).fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByRole("alert")).toContainText("Срок действия ссылки истек");
await page.unroute("**/api/v1/identity/email-verifications");
// An expired link leads to the code step, which asks for the address and
// its own resend. The stand allows one message per second.
await page.waitForTimeout(1100);
await page.getByLabel("Электронная почта").fill(email);
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();
await page.getByRole("button", { name: "Отправить код повторно" }).click();
expect((await resendResponse).status()).toBe(202);
await expect(page.getByText(/^Запрос принят\./)).toBeVisible();
const resentMessage = await waitForMessage(email, originalMessage.id);
@@ -173,65 +307,25 @@ test.describe("registration, email confirmation, and onboarding", () => {
new URL(response.url()).pathname === "/api/v1/identity/email-verifications" &&
response.request().method() === "POST",
);
await page.getByLabel("Пароль, выбранный при регистрации").fill("incorrect password test");
await linkPassword(page).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);
expect(rejectedProblem.code).toBe("verification_token_invalid");
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);
await expect(linkPassword(page)).toBeVisible();
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 linkPassword(page).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);
expect((await successfulConfirmation).status()).toBe(200);
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");
await signInAndResume(page, "candidate", email, password, "Согласия");
});
});