All checks were successful
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
326 lines
16 KiB
TypeScript
326 lines
16 KiB
TypeScript
import { afterEach, describe, expect, it } from "vitest";
|
||
import { createRevocationList, SESSION_TTL_MS } from "../src/session.ts";
|
||
import { hashPassword } from "../src/users.ts";
|
||
import { cookieFrom, startApp, type TestApp } from "./helpers.ts";
|
||
|
||
let app: TestApp;
|
||
afterEach(() => app?.close());
|
||
|
||
const expectRedirectToLogin = (response: Response) => {
|
||
expect(response.status).toBe(303);
|
||
expect(response.headers.get("location")).toBe("/login");
|
||
};
|
||
|
||
describe("Requirement: Страница входа", () => {
|
||
it("Scenario: Вошедший пользователь открывает страницу входа", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const response = await app.get("/login", { cookie });
|
||
expect(response.status).toBe(303);
|
||
expect(response.headers.get("location")).toBe("/");
|
||
expect(await response.text()).not.toContain("<form");
|
||
});
|
||
});
|
||
|
||
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 home = await app.get("/", { cookie: cookieFrom(response, "session") ?? "" });
|
||
const html = await home.text();
|
||
expect(home.status).toBe(200);
|
||
expect(html).toContain("Вы вошли как anna");
|
||
expect(html).toContain('<button type="submit">Выйти</button>');
|
||
});
|
||
|
||
it.each([["/"], ["/reports"], ["/no/such/page"], ["/logout"]])(
|
||
"Scenario Outline: Закрытый адрес без входа ведёт на страницу входа — %s",
|
||
async (path) => {
|
||
app = await startApp();
|
||
const response = await app.get(path);
|
||
expectRedirectToLogin(response);
|
||
expect(await response.text()).toBe("");
|
||
},
|
||
);
|
||
|
||
it("Scenario: Обновление страницы не сбрасывает вход", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
for (let i = 0; i < 3; i++) {
|
||
const response = await app.get("/", { cookie });
|
||
expect(response.status).toBe(200);
|
||
// Повторные ответы не трогают отметку о входе.
|
||
expect(cookieFrom(response, "session")).toBeUndefined();
|
||
expect(await response.text()).toContain("Вы вошли как anna");
|
||
}
|
||
});
|
||
|
||
it("Scenario: Вход пропадает при закрытии браузера", async () => {
|
||
app = await startApp();
|
||
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).not.toMatch(/Max-Age|Expires/i);
|
||
});
|
||
|
||
it("страница входа и её оформление открыты без входа", async () => {
|
||
app = await startApp();
|
||
expect((await app.get("/login")).status).toBe(200);
|
||
expect((await app.get("/static/style.css")).status).toBe(200);
|
||
});
|
||
|
||
it("закрытый адрес без входа закрыт для любого способа запроса", async () => {
|
||
app = await startApp();
|
||
expectRedirectToLogin(await app.post("/reports", {}));
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Выход", () => {
|
||
it("Scenario: Выход ведёт на страницу входа", async () => {
|
||
app = await startApp({ cookieSecure: true });
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const response = await app.post("/logout", {}, { cookie });
|
||
expectRedirectToLogin(response);
|
||
const cleared = response.headers.getSetCookie().find((c) => c.startsWith("session=")) ?? "";
|
||
expect(cleared).toMatch(/^session=;/);
|
||
expect(cleared).toContain("Max-Age=0");
|
||
// Те же признаки, что при выдаче, иначе браузер не сотрёт отметку.
|
||
expect(cleared).toContain("Path=/");
|
||
expect(cleared).toContain("Secure");
|
||
});
|
||
|
||
it("Scenario: После выхода прямая ссылка ведёт на страницу входа", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const logout = await app.post("/logout", {}, { cookie });
|
||
// Браузер после выхода отправляет то, что осталось от отметки, — пустое значение.
|
||
const left = cookieFrom(logout, "session") ?? "";
|
||
expect(left).toBe("session=");
|
||
expectRedirectToLogin(await app.get("/", { cookie: left }));
|
||
expectRedirectToLogin(await app.get("/"));
|
||
// Страница входа снова показывает форму, а не перенаправляет на главную.
|
||
const login = await app.get("/login", { cookie: left });
|
||
expect(login.status).toBe(200);
|
||
expect(await login.text()).toContain('<button type="submit">Войти</button>');
|
||
});
|
||
|
||
it("Scenario: Прежняя отметка о входе после выхода не работает", async () => {
|
||
app = await startApp();
|
||
const copied = await app.signIn("anna", "s3cret-pass");
|
||
expect((await app.get("/", { cookie: copied })).status).toBe(200);
|
||
await app.post("/logout", {}, { cookie: copied });
|
||
expectRedirectToLogin(await app.get("/", { cookie: copied }));
|
||
expect((await app.get("/login", { cookie: copied })).status).toBe(200);
|
||
});
|
||
|
||
it("Scenario: Кнопка «Назад» после выхода", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const home = await app.get("/", { cookie });
|
||
expect(await home.text()).toContain("<h1>Вы вошли как anna</h1>");
|
||
// Браузеру запрещено хранить страницу: по «Назад» он запросит её заново.
|
||
expect(home.headers.get("cache-control")).toBe("no-store");
|
||
const logout = await app.post("/logout", {}, { cookie });
|
||
expect(logout.headers.get("cache-control")).toBe("no-store");
|
||
// «Назад»: повторный запрос главной — отметка в браузере стёрта либо осталась прежняя.
|
||
const attempts: Record<string, string>[] = [{}, { cookie }];
|
||
for (const headers of attempts) {
|
||
const back = await app.get("/", headers);
|
||
expectRedirectToLogin(back);
|
||
expect(back.headers.get("cache-control")).toBe("no-store");
|
||
const text = await back.text();
|
||
expect(text).not.toContain("Вы вошли как anna");
|
||
expect(text).not.toContain("Выйти");
|
||
}
|
||
});
|
||
|
||
it.each([
|
||
["kk", "Сіз anna ретінде кірдіңіз", "Шығу"],
|
||
["en", "You are signed in as anna", "Sign out"],
|
||
])("Scenario: Вход, выход и «Назад» на языке %s", async (lang, title, button) => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const home = await (await app.get(`/?lang=${lang}`, { cookie })).text();
|
||
expect(home).toContain(`<h1>${title}</h1>`);
|
||
expect(home).toContain(`<button type="submit">${button}</button>`);
|
||
await app.post("/logout", {}, { cookie });
|
||
const attempts: Record<string, string>[] = [{}, { cookie }];
|
||
for (const headers of attempts) {
|
||
const back = await app.get(`/?lang=${lang}`, headers);
|
||
expectRedirectToLogin(back);
|
||
expect(await back.text()).not.toContain(title);
|
||
}
|
||
});
|
||
|
||
it("Scenario: Выход без входа", async () => {
|
||
app = await startApp();
|
||
expectRedirectToLogin(await app.post("/logout", {}));
|
||
expectRedirectToLogin(await app.post("/logout", {}, { cookie: "session=garbage" }));
|
||
});
|
||
|
||
it("Scenario: Выход одного пользователя не затрагивает другой браузер", async () => {
|
||
app = await startApp();
|
||
const first = await app.signIn("anna", "s3cret-pass");
|
||
const second = await app.signIn("anna", "s3cret-pass");
|
||
expect(second).not.toBe(first);
|
||
await app.post("/logout", {}, { cookie: first });
|
||
expectRedirectToLogin(await app.get("/", { cookie: first }));
|
||
const response = await app.get("/", { cookie: second });
|
||
expect(response.status).toBe(200);
|
||
expect(await response.text()).toContain("Вы вошли как anna");
|
||
});
|
||
|
||
it("выход работает только кнопкой: открытие адреса выхода ссылкой вход не сбрасывает", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const response = await app.get("/logout", { cookie });
|
||
expect(response.status).toBe(404);
|
||
expect((await app.get("/", { cookie })).status).toBe(200);
|
||
});
|
||
|
||
it("кнопка «Выйти» отправляет форму на адрес выхода", async () => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const html = await (await app.get("/", { cookie })).text();
|
||
expect(html).toMatch(
|
||
/<form method="post" action="\/logout">\s*<button type="submit">Выйти<\/button>\s*<\/form>/,
|
||
);
|
||
});
|
||
|
||
it.each([
|
||
["kk", "Шығу"],
|
||
["en", "Sign out"],
|
||
])("кнопка выхода переведена — %s", async (lang, label) => {
|
||
app = await startApp();
|
||
const cookie = await app.signIn("anna", "s3cret-pass");
|
||
const html = await (await app.get(`/?lang=${lang}`, { cookie })).text();
|
||
expect(html).toContain(`<button type="submit">${label}</button>`);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Путь от входа до выхода на главной странице", () => {
|
||
// Обычные пользователи из списка теста, не пробный вход: его нет ни в одном окружении.
|
||
const users = [
|
||
{ login: "demo", passwordHash: hashPassword("Demo-pass-2026") },
|
||
{ login: "demo2", passwordHash: hashPassword("Demo2-pass-2026") },
|
||
];
|
||
const headings = (html: string) => html.match(/<h1>.*?<\/h1>/g);
|
||
|
||
it.each([
|
||
["demo", "Demo-pass-2026", "demo2"],
|
||
["demo2", "Demo2-pass-2026", "demo"],
|
||
])("Scenario Outline: От входа до выхода — %s", async (login, password, other) => {
|
||
app = await startApp({ account: undefined, users });
|
||
const cookie = await app.signIn(login, password);
|
||
|
||
const home = await (await app.get("/", { cookie })).text();
|
||
// Заголовок сверяется целиком: «Вы вошли как demo2» содержит «Вы вошли как demo».
|
||
expect(headings(home)).toEqual([`<h1>Вы вошли как ${login}</h1>`]);
|
||
expect(home).toContain('<button type="submit">Выйти</button>');
|
||
// Чужого логина нет нигде на странице, а не только в заголовке.
|
||
expect(home.replaceAll(login, "")).not.toContain(other);
|
||
expect(home.replaceAll("demo2", "").includes("demo")).toBe(login === "demo");
|
||
|
||
const out = await app.post("/logout", {}, { cookie });
|
||
expectRedirectToLogin(out);
|
||
const loginPage = await (await app.get("/login")).text();
|
||
expect(headings(loginPage)).toEqual(["<h1>Вход</h1>"]);
|
||
|
||
expectRedirectToLogin(await app.get("/", { cookie }));
|
||
});
|
||
|
||
it("Scenario: Главная страница без входа", async () => {
|
||
app = await startApp({ account: undefined, users });
|
||
const response = await app.get("/");
|
||
expectRedirectToLogin(response);
|
||
const loginPage = await (await app.get(response.headers.get("location") ?? "")).text();
|
||
expect(headings(loginPage)).toEqual(["<h1>Вход</h1>"]);
|
||
expect(loginPage).toContain('<label for="login">Логин</label>');
|
||
expect(loginPage).toContain('<label for="password">Пароль</label>');
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Путь от входа до выхода на трёх языках", () => {
|
||
// Обычные пользователи из списка теста, не пробный вход: его нет ни в одном окружении.
|
||
const users = [
|
||
{ login: "demo", passwordHash: hashPassword("Demo-pass-2026") },
|
||
{ login: "demo2", passwordHash: hashPassword("Demo2-pass-2026") },
|
||
];
|
||
const headings = (html: string) => html.match(/<h1>.*?<\/h1>/g);
|
||
const languages = [
|
||
["ru", "Вы вошли как {login}", "Выйти", "Вход"],
|
||
["kk", "Сіз {login} ретінде кірдіңіз", "Шығу", "Кіру"],
|
||
["en", "You are signed in as {login}", "Sign out", "Sign in"],
|
||
] as const;
|
||
const people = [
|
||
["demo", "Demo-pass-2026"],
|
||
["demo2", "Demo2-pass-2026"],
|
||
] as const;
|
||
const rows = people.flatMap(([login, password]) =>
|
||
languages.map((row) => [login, password, ...row] as const),
|
||
);
|
||
|
||
it.each(rows)(
|
||
"Scenario Outline: От входа до кнопки «Назад» на выбранном языке — %s, %s, %s",
|
||
async (login, password, lang, pattern, button, loginTitle) => {
|
||
app = await startApp({ account: undefined, users });
|
||
const cookie = await app.signIn(login, password);
|
||
const title = pattern.replace("{login}", login);
|
||
|
||
const response = await app.get(`/?lang=${lang}`, { cookie });
|
||
// Браузеру запрещено хранить страницу: по «Назад» он запросит её заново.
|
||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||
const home = await response.text();
|
||
// Заголовок сверяется целиком: «…demo2…» содержит «…demo…».
|
||
expect(headings(home)).toEqual([`<h1>${title}</h1>`]);
|
||
expect(home).toContain(`<button type="submit">${button}</button>`);
|
||
// Логина другого пользователя нет нигде на странице.
|
||
expect(home.includes("demo2")).toBe(login === "demo2");
|
||
expect(home.replaceAll("demo2", "").includes("demo")).toBe(login === "demo");
|
||
|
||
const out = await app.post("/logout", {}, { cookie });
|
||
expectRedirectToLogin(out);
|
||
expect(out.headers.get("cache-control")).toBe("no-store");
|
||
const loginPage = await (await app.get(`/login?lang=${lang}`)).text();
|
||
expect(headings(loginPage)).toEqual([`<h1>${loginTitle}</h1>`]);
|
||
|
||
// «Назад»: браузер заново запрашивает главную с прежней отметкой о входе.
|
||
const back = await app.get(`/?lang=${lang}`, { cookie });
|
||
expectRedirectToLogin(back);
|
||
expect(back.headers.get("cache-control")).toBe("no-store");
|
||
expect(await back.text()).not.toContain(title);
|
||
},
|
||
);
|
||
|
||
it("Scenario: «Назад» после выхода без отметки о входе", async () => {
|
||
app = await startApp({ account: undefined, users });
|
||
const cookie = await app.signIn("demo", "Demo-pass-2026");
|
||
await app.post("/logout", {}, { cookie });
|
||
const back = await app.get("/?lang=en");
|
||
expectRedirectToLogin(back);
|
||
expect(await back.text()).not.toContain("You are signed in as demo");
|
||
});
|
||
});
|
||
|
||
describe("session: отменённые отметки о входе", () => {
|
||
it("отменённая отметка считается отменённой, остальные — нет", () => {
|
||
const list = createRevocationList();
|
||
list.revoke("token-a", 1000);
|
||
expect(list.isRevoked("token-a", 1001)).toBe(true);
|
||
expect(list.isRevoked("token-b", 1001)).toBe(false);
|
||
});
|
||
|
||
it("запись хранится не дольше срока действия отметки", () => {
|
||
const list = createRevocationList();
|
||
list.revoke("token-a", 1000);
|
||
expect(list.isRevoked("token-a", 1000 + SESSION_TTL_MS - 1)).toBe(true);
|
||
expect(list.isRevoked("token-a", 1000 + SESSION_TTL_MS)).toBe(false);
|
||
// Следующая отмена вычищает просроченные записи и не ломает новые.
|
||
list.revoke("token-b", 1000 + SESSION_TTL_MS);
|
||
expect(list.isRevoked("token-a", 1000 + SESSION_TTL_MS)).toBe(false);
|
||
expect(list.isRevoked("token-b", 1000 + SESSION_TTL_MS + 1)).toBe(true);
|
||
});
|
||
});
|