385 lines
18 KiB
TypeScript
385 lines
18 KiB
TypeScript
import { afterEach, describe, expect, it } from "vitest";
|
||
import { mockAccount } from "../src/auth.ts";
|
||
import { createSessionToken } from "../src/session.ts";
|
||
import { hashPassword } from "../src/users.ts";
|
||
import { cookieFrom, startApp, type TestApp } from "./helpers.ts";
|
||
|
||
const INVALID = "Неверный логин или пароль. Проверьте их и попробуйте ещё раз.";
|
||
const EMPTY = "Вы не заполнили логин или пароль. Заполните оба поля и нажмите «Войти».";
|
||
|
||
const SECOND_HINT =
|
||
"Второй пробный вход: логин demo2, пароль demo2. Войдите под каждым по очереди — главная страница покажет, под каким логином вы вошли.";
|
||
|
||
const DEMO_NOTE =
|
||
"Пробные входы работают, пока владелец продукта не задал свои логин и пароль. После этого они отключатся.";
|
||
|
||
// Пользователи А и Б из списка; хэши считаются один раз на файл тестов.
|
||
const users = [
|
||
{ login: "anna", passwordHash: hashPassword("Anna-pass-2026") },
|
||
{ login: "boris", passwordHash: hashPassword("boris") },
|
||
];
|
||
const startWithUsers = () =>
|
||
startApp({ users, account: { login: "owner", password: "owner-pass" } });
|
||
|
||
let app: TestApp;
|
||
afterEach(() => app?.close());
|
||
|
||
/** Значение поля «Логин» на странице. */
|
||
const loginFieldValue = (html: string) => /<input id="login"[^>]* value="([^"]*)"/.exec(html)?.[1];
|
||
|
||
describe("Requirement: Страница входа", () => {
|
||
it("Scenario: Страница входа открывается", async () => {
|
||
app = await startApp();
|
||
const response = await app.get("/login");
|
||
const html = await response.text();
|
||
expect(response.status).toBe(200);
|
||
expect(html).toContain("<h1>Вход</h1>");
|
||
expect(html).toContain("Введите логин и пароль. После входа откроется главная страница.");
|
||
expect(html).toContain('<label for="login">Логин</label>');
|
||
expect(html).toContain('<label for="password">Пароль</label>');
|
||
expect(html).toMatch(/<input id="password"[^>]* type="password"/);
|
||
expect(html).toContain('<button type="submit">Войти</button>');
|
||
});
|
||
|
||
it("Scenario: Вход нажатием Enter", async () => {
|
||
app = await startApp();
|
||
const html = await (await app.get("/login")).text();
|
||
// Оба поля и кнопка отправки лежат в одной форме: Enter в любом поле отправляет её.
|
||
const form =
|
||
/<form method="post" action="\/login"[^>]*>([\s\S]*?)<\/form>/.exec(html)?.[1] ?? "";
|
||
expect(form).toContain('name="login"');
|
||
expect(form).toContain('name="password"');
|
||
expect(form).toContain('<button type="submit">');
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Вход по логину и паролю", () => {
|
||
it("Scenario: Успешный вход", async () => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
|
||
expect(response.status).toBe(303);
|
||
expect(response.headers.get("location")).toBe("/");
|
||
const cookie = cookieFrom(response, "session") ?? "";
|
||
const home = await app.get("/", { cookie });
|
||
expect(await home.text()).toContain("Вы вошли как anna");
|
||
});
|
||
|
||
it("Scenario: Логин набран в другом регистре", async () => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login: " Anna ", password: "s3cret-pass" });
|
||
expect(response.status).toBe(303);
|
||
expect(response.headers.get("location")).toBe("/");
|
||
});
|
||
|
||
it.each([
|
||
["anna", "wrong"],
|
||
["boris", "s3cret-pass"],
|
||
["anna", "S3CRET-PASS"],
|
||
])("Scenario Outline: Неверный логин или пароль (%s / %s)", async (login, password) => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login, password });
|
||
const html = await response.text();
|
||
expect(response.status).toBe(401);
|
||
expect(html).toContain(INVALID);
|
||
expect(loginFieldValue(html)).toBe(login);
|
||
expect(html).not.toMatch(/<input id="password"[^>]* value=/);
|
||
expect(html).not.toContain(password);
|
||
expect(cookieFrom(response, "session")).toBeUndefined();
|
||
});
|
||
|
||
it.each([
|
||
["", "s3cret-pass"],
|
||
["anna", ""],
|
||
["", ""],
|
||
])("Scenario Outline: Поле не заполнено («%s» / «%s»)", async (login, password) => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login, password });
|
||
const html = await response.text();
|
||
expect(response.status).toBe(400);
|
||
expect(html).toContain(EMPTY);
|
||
expect(cookieFrom(response, "session")).toBeUndefined();
|
||
});
|
||
|
||
it("форму можно отправить пустой: сообщение показывает страница, а не браузер", async () => {
|
||
app = await startApp();
|
||
const html = await (await app.get("/login")).text();
|
||
expect(html).toContain("novalidate");
|
||
expect(html).not.toMatch(/<input[^>]* required/);
|
||
});
|
||
|
||
it("введённый логин показывается без исполнения разметки", async () => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login: '"><script>x</script>', password: "p" });
|
||
const html = await response.text();
|
||
expect(html).not.toContain("<script>");
|
||
expect(html).toContain("<script>");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Страница после входа", () => {
|
||
it("Scenario: Страница после входа", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const response = await app.get("/", { cookie });
|
||
const html = await response.text();
|
||
expect(response.status).toBe(200);
|
||
expect(html).toContain("Вы вошли как anna");
|
||
expect(html).toContain("Вход выполнен.");
|
||
expect(html).toContain('<button type="submit">Выйти</button>');
|
||
});
|
||
|
||
it("Scenario: Вход под А и под Б показывает разные логины", async () => {
|
||
app = await startWithUsers();
|
||
const first = await app.signIn("anna", "Anna-pass-2026");
|
||
const second = await app.signIn("boris", "boris");
|
||
const pageA = await (await app.get("/", { cookie: first })).text();
|
||
const pageB = await (await app.get("/", { cookie: second })).text();
|
||
expect(pageA).toContain("Вы вошли как anna");
|
||
expect(pageA).not.toContain("boris");
|
||
expect(pageB).toContain("Вы вошли как boris");
|
||
expect(pageB).not.toContain("anna");
|
||
});
|
||
|
||
it("Scenario: Вход под Б в том же браузере не показывает А", async () => {
|
||
app = await startWithUsers();
|
||
const first = await app.signIn("anna", "Anna-pass-2026");
|
||
await app.post("/logout", {}, { cookie: first });
|
||
const second = await app.signIn("boris", "boris");
|
||
const html = await (await app.get("/", { cookie: second })).text();
|
||
expect(html).toContain("Вы вошли как boris");
|
||
expect(html).not.toContain("anna");
|
||
});
|
||
|
||
it("вход под Б поверх входа А, без выхода, тоже показывает только Б", async () => {
|
||
app = await startWithUsers();
|
||
const first = await app.signIn("anna", "Anna-pass-2026");
|
||
const response = await app.post(
|
||
"/login",
|
||
{ login: "boris", password: "boris" },
|
||
{ cookie: first },
|
||
);
|
||
const html = await (
|
||
await app.get("/", { cookie: cookieFrom(response, "session") ?? "" })
|
||
).text();
|
||
expect(html).toContain("Вы вошли как boris");
|
||
expect(html).not.toContain("anna");
|
||
});
|
||
|
||
it("Scenario: Неудачный вход под Б не меняет вошедшего", async () => {
|
||
app = await startWithUsers();
|
||
const cookie = await app.signIn("anna", "Anna-pass-2026");
|
||
const failed = await app.post("/login", { login: "boris", password: "wrong" }, { cookie });
|
||
expect(failed.status).toBe(401);
|
||
expect(cookieFrom(failed, "session")).toBeUndefined();
|
||
expect(await (await app.get("/", { cookie })).text()).toContain("Вы вошли как anna");
|
||
});
|
||
|
||
it("логин на главной показан текстом, без исполнения разметки", async () => {
|
||
const login = '<b>&"x"</b>';
|
||
app = await startApp({ account: { login, password: "p" } });
|
||
const html = await (await app.get("/", { cookie: await app.signIn(login, "p") })).text();
|
||
expect(html).toContain("Вы вошли как <b>&"x"</b>");
|
||
expect(html).not.toContain("<b>");
|
||
});
|
||
|
||
it("Scenario: Страница после входа без входа", async () => {
|
||
app = await startApp();
|
||
const response = await app.get("/");
|
||
expect(response.status).toBe(303);
|
||
expect(response.headers.get("location")).toBe("/login");
|
||
const body = await response.text();
|
||
expect(body).not.toContain("Вы вошли как");
|
||
expect(body).not.toContain("Выйти");
|
||
});
|
||
|
||
it("Scenario: Подделанная отметка о входе", async () => {
|
||
app = await startApp();
|
||
const forged = createSessionToken("admin", Buffer.from("not-the-secret"), Date.UTC(2026, 0, 1));
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const swapped = `session=${forged.split(".")[0]}.${cookie.split(".")[1]}`;
|
||
for (const value of [`session=${forged}`, swapped, "session=garbage", "session=a.b"]) {
|
||
const response = await app.get("/", { cookie: value });
|
||
expect(response.headers.get("location"), value).toBe("/login");
|
||
}
|
||
});
|
||
|
||
it("отметка о входе недоступна скриптам и живёт, пока открыт браузер", async () => {
|
||
app = await startApp({ cookieSecure: true });
|
||
const response = await app.post("/login", { login: "anna", password: "s3cret-pass" });
|
||
const cookie = response.headers.getSetCookie().find((c) => c.startsWith("session=")) ?? "";
|
||
expect(cookie).toContain("HttpOnly");
|
||
expect(cookie).toContain("SameSite=Lax");
|
||
expect(cookie).toContain("Secure");
|
||
expect(cookie).not.toMatch(/Max-Age|Expires/i);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Пробный вход, пока логин и пароль не заданы", () => {
|
||
it("Scenario: Пробный вход работает", async () => {
|
||
app = await startApp({ account: mockAccount, mockAuth: true });
|
||
const page = await app.get("/login");
|
||
expect(await page.text()).toContain("Пробный вход: логин demo, пароль demo.");
|
||
const response = await app.post("/login", { login: "demo", password: "demo" });
|
||
expect(response.status).toBe(303);
|
||
expect(response.headers.get("location")).toBe("/");
|
||
});
|
||
|
||
it("Scenario: На странице входа показан второй пробный вход", async () => {
|
||
app = await startApp({ account: mockAccount, mockAuth: true });
|
||
expect(await (await app.get("/login")).text()).toContain(SECOND_HINT);
|
||
});
|
||
|
||
it("Scenario: На странице входа объяснено, до каких пор остаётся пробный вход", async () => {
|
||
app = await startApp({ account: mockAccount, mockAuth: true });
|
||
expect(await (await app.get("/login")).text()).toContain(DEMO_NOTE);
|
||
// Пояснение остаётся и после ошибки входа.
|
||
const failed = await app.post("/login", { login: "demo", password: "wrong" });
|
||
expect(await failed.text()).toContain(DEMO_NOTE);
|
||
});
|
||
|
||
it("Scenario: Пояснение о пробном входе скрыто, когда логин и пароль заданы", async () => {
|
||
app = await startApp();
|
||
expect(await (await app.get("/login")).text()).not.toContain("Пробные входы работают");
|
||
const failed = await app.post("/login", { login: "demo", password: "demo" });
|
||
expect(await failed.text()).not.toContain("Пробные входы работают");
|
||
});
|
||
|
||
it.each([
|
||
["demo", "demo", "demo2"],
|
||
["demo2", "demo2", "demo"],
|
||
])(
|
||
"Scenario Outline: Два пробных входа показывают разные логины — %s",
|
||
async (login, password, other) => {
|
||
app = await startApp({ account: mockAccount, mockAuth: true });
|
||
const html = await (await app.get("/", { cookie: await app.signIn(login, password) })).text();
|
||
// Заголовок сверяется целиком: «Вы вошли как demo2» содержит «Вы вошли как demo».
|
||
expect(/<h1>([^<]*)<\/h1>/.exec(html)?.[1]).toBe(`Вы вошли как ${login}`);
|
||
expect(html).not.toContain(`Вы вошли как ${other}<`);
|
||
},
|
||
);
|
||
|
||
it("Scenario: Пароль одного пробного входа не подходит к другому", async () => {
|
||
app = await startApp({ account: mockAccount, mockAuth: true });
|
||
const response = await app.post("/login", { login: "demo2", password: "demo" });
|
||
expect(response.status).toBe(401);
|
||
expect(await response.text()).toContain(INVALID);
|
||
});
|
||
|
||
it("Scenario: Второй пробный вход отключён", async () => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login: "demo2", password: "demo2" });
|
||
const html = await response.text();
|
||
expect(response.status).toBe(401);
|
||
expect(html).toContain(INVALID);
|
||
expect(loginFieldValue(html)).toBe("demo2");
|
||
expect(html.replace(/<input id="login"[^>]*>/, "")).not.toContain("demo2");
|
||
expect(await (await app.get("/login")).text()).not.toContain("demo2");
|
||
});
|
||
|
||
it("Scenario: Пробный вход отключён", async () => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login: "demo", password: "demo" });
|
||
const html = await response.text();
|
||
expect(response.status).toBe(401);
|
||
expect(html).toContain(INVALID);
|
||
expect(html).not.toContain("Пробный вход");
|
||
const page = await (await app.get("/login")).text();
|
||
expect(page).not.toContain("Пробный вход");
|
||
// Логин и пароль владельца в тексте страницы не появляются.
|
||
expect(page).not.toContain("anna");
|
||
expect(page).not.toContain("s3cret-pass");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Язык экранов", () => {
|
||
it.each([
|
||
["ru", "Русский", "Войти"],
|
||
["kk", "Қазақша", "Кіру"],
|
||
["en", "English", "Sign in"],
|
||
])("Scenario Outline: Язык выбран в переключателе (%s)", async (code, name, button) => {
|
||
app = await startApp();
|
||
const start = await app.get("/login", { "accept-language": "de" });
|
||
expect(await start.text()).toContain(`<a href="/login?lang=${code}" lang="${code}"`);
|
||
const chosen = await app.get(`/login?lang=${code}`);
|
||
const html = await chosen.text();
|
||
expect(html).toContain(`<button type="submit">${button}</button>`);
|
||
expect(html).toContain(`aria-current="true">${name}</a>`);
|
||
const cookie = cookieFrom(chosen, "lang");
|
||
expect(cookie).toBe(`lang=${code}`);
|
||
const again = await app.get("/login", { cookie: cookie ?? "", "accept-language": "de" });
|
||
expect(await again.text()).toContain(`<button type="submit">${button}</button>`);
|
||
});
|
||
|
||
it("Scenario: Язык браузера не поддерживается", async () => {
|
||
app = await startApp();
|
||
const response = await app.get("/login", { "accept-language": "de-DE,de;q=0.9" });
|
||
expect(await response.text()).toContain('<button type="submit">Войти</button>');
|
||
expect(response.headers.get("content-language")).toBe("ru");
|
||
});
|
||
|
||
it("без выбора в переключателе берётся язык браузера", async () => {
|
||
app = await startApp();
|
||
const response = await app.get("/login", {
|
||
"accept-language": "de;q=0.9,kk-KZ;q=0.8,en;q=0.5",
|
||
});
|
||
expect(await response.text()).toContain('<button type="submit">Кіру</button>');
|
||
});
|
||
|
||
it("ошибка входа показана на выбранном языке", async () => {
|
||
app = await startApp();
|
||
const response = await app.post(
|
||
"/login",
|
||
{ login: "anna", password: "wrong" },
|
||
{ cookie: "lang=en" },
|
||
);
|
||
expect(await response.text()).toContain("Wrong login or password.");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Проверка работоспособности", () => {
|
||
it("Scenario: Сервис работает", async () => {
|
||
app = await startApp();
|
||
const response = await app.get("/healthz");
|
||
expect(response.status).toBe(200);
|
||
});
|
||
|
||
it("Scenario: Неизвестный адрес", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const response = await app.get("/no-such-page", { cookie });
|
||
expect(response.status).toBe(404);
|
||
expect(await response.text()).toContain("Такой страницы нет. Вернитесь на главную.");
|
||
});
|
||
|
||
it("сбой показывает две фразы без подробностей и сообщает об ошибке", async () => {
|
||
const errors: unknown[] = [];
|
||
app = await startApp({
|
||
onError: (error) => errors.push(error),
|
||
now: () => {
|
||
throw new Error("boom-secret-detail");
|
||
},
|
||
});
|
||
const response = await app.get("/");
|
||
const html = await response.text();
|
||
expect(response.status).toBe(500);
|
||
expect(html).toContain("Что-то пошло не так. Обновите страницу и попробуйте ещё раз.");
|
||
expect(html).not.toContain("boom-secret-detail");
|
||
expect(errors).toHaveLength(1);
|
||
});
|
||
|
||
it("слишком большая форма отклоняется", async () => {
|
||
app = await startApp();
|
||
const response = await app.post("/login", { login: "anna", password: "x".repeat(20_000) });
|
||
expect(response.status).toBe(413);
|
||
});
|
||
|
||
it("страницы запрещают встраивание и посторонние скрипты", async () => {
|
||
app = await startApp();
|
||
const response = await app.get("/login");
|
||
expect(response.headers.get("content-security-policy")).toContain("default-src 'none'");
|
||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||
const css = await app.get("/static/style.css");
|
||
expect(css.headers.get("content-type")).toContain("text/css");
|
||
});
|
||
});
|