Files
lincodex/frontend/e2e/auth-registration.spec.ts

332 lines
15 KiB
TypeScript

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;
}
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}`;
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 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.");
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();
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;
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);
// 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.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await captureReviewScreenshot(page, scenario, "registration-accepted");
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,
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 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.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 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).toBe("verification_token_invalid");
await expect(page.getByRole("alert")).toContainText("Не удалось подтвердить почту");
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 linkPassword(page).fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
expect((await successfulConfirmation).status()).toBe(200);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await signInAndResume(page, "candidate", email, password, "Согласия");
});
});