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

238 lines
11 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;
}
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");
});
});