All checks were successful
Каркас на Node.js + TypeScript, тексты на трёх языках, проверки и деплой. OpenSpec change tr-1-login-window (в архиве). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
135 lines
6.4 KiB
TypeScript
135 lines
6.4 KiB
TypeScript
import { readFileSync } from "node:fs";
|
||
import { describe, expect, it } from "vitest";
|
||
import { mockAccount, verifyCredentials } from "../src/auth.ts";
|
||
import { environmentFromHost, loadConfig } from "../src/config.ts";
|
||
import { LANGS, locales, pickLang } from "../src/i18n.ts";
|
||
import { createSessionToken, readSessionToken, SESSION_TTL_MS } from "../src/session.ts";
|
||
|
||
describe("auth: проверка логина и пароля", () => {
|
||
const account = { login: "Anna", password: " s3cret " };
|
||
|
||
it("логин — без учёта регистра и пробелов, пароль — точно", () => {
|
||
expect(verifyCredentials(account, " aNNa ", " s3cret ")).toBe("Anna");
|
||
expect(verifyCredentials(account, "anna", "s3cret")).toBeNull();
|
||
expect(verifyCredentials(account, "ann", " s3cret ")).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe("session: отметка о входе", () => {
|
||
const secret = Buffer.from("k");
|
||
|
||
it("читается до истечения срока и не читается после", () => {
|
||
const token = createSessionToken("anna", secret, 1000);
|
||
expect(readSessionToken(token, secret, 1000 + SESSION_TTL_MS - 1)).toBe("anna");
|
||
expect(readSessionToken(token, secret, 1000 + SESSION_TTL_MS)).toBeNull();
|
||
});
|
||
|
||
it("не читается с другим ключом и в испорченном виде", () => {
|
||
const token = createSessionToken("anna", secret, 1000);
|
||
expect(readSessionToken(token, Buffer.from("other"), 1000)).toBeNull();
|
||
expect(readSessionToken(`${token}x`, secret, 1000)).toBeNull();
|
||
expect(readSessionToken(undefined, secret, 1000)).toBeNull();
|
||
expect(readSessionToken(".", secret, 1000)).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe("config: настройки из окружения", () => {
|
||
it("без логина и пароля работает мок", () => {
|
||
const config = loadConfig({});
|
||
expect(config.mockAuth).toBe(true);
|
||
expect(config.account).toEqual(mockAccount);
|
||
expect(config.port).toBe(3000);
|
||
expect(config.sentry).toEqual({ dsn: undefined, release: undefined, environment: "dev" });
|
||
expect(config.warnings).toHaveLength(1);
|
||
});
|
||
|
||
it.each([
|
||
[{ AUTH_LOGIN: "anna" }],
|
||
[{ AUTH_PASSWORD: "s3cret-pass" }],
|
||
[{ AUTH_LOGIN: "", AUTH_PASSWORD: "" }],
|
||
])("задана только часть — тоже мок (%j)", (env) => {
|
||
expect(loadConfig(env).mockAuth).toBe(true);
|
||
});
|
||
|
||
it("логин и пароль владельца отключают мок", () => {
|
||
const env = { AUTH_LOGIN: " anna ", AUTH_PASSWORD: "s3cret-pass", PORT: "8080" };
|
||
const config = loadConfig(env);
|
||
expect(config.mockAuth).toBe(false);
|
||
expect(config.account).toEqual({ login: "anna", password: "s3cret-pass" });
|
||
expect(config.port).toBe(8080);
|
||
expect(config.warnings).toEqual([]);
|
||
// Ключ подписи стабилен между перезапусками и меняется вместе с паролем.
|
||
expect(loadConfig(env).sessionSecret.equals(config.sessionSecret)).toBe(true);
|
||
const changed = loadConfig({ ...env, AUTH_PASSWORD: "other" });
|
||
expect(changed.sessionSecret.equals(config.sessionSecret)).toBe(false);
|
||
});
|
||
|
||
it("отметка о входе только по https в production", () => {
|
||
expect(loadConfig({ NODE_ENV: "production" }).cookieSecure).toBe(true);
|
||
expect(loadConfig({ NODE_ENV: "production", COOKIE_SECURE: "false" }).cookieSecure).toBe(false);
|
||
expect(loadConfig({}).cookieSecure).toBe(false);
|
||
});
|
||
|
||
it("окружение для отчётов об ошибках", () => {
|
||
expect(environmentFromHost("testirovanie-robot-prod.telecom.quest")).toBe("prod");
|
||
expect(environmentFromHost("testirovanie-robot-staging.telecom.quest")).toBe("staging");
|
||
expect(environmentFromHost("testirovanie-robot-pr1.telecom.quest")).toBe("dev");
|
||
expect(environmentFromHost(undefined)).toBe("dev");
|
||
const config = loadConfig({
|
||
SENTRY_DSN: "https://k@example.test/1",
|
||
SENTRY_ENVIRONMENT: "prod",
|
||
});
|
||
expect(config.sentry.environment).toBe("prod");
|
||
});
|
||
|
||
it("неверный порт — ошибка запуска", () => {
|
||
expect(() => loadConfig({ PORT: "abc" })).toThrow();
|
||
});
|
||
});
|
||
|
||
describe("i18n: тексты экранов", () => {
|
||
it("язык: выбор → cookie → браузер → русский", () => {
|
||
expect(pickLang("en", "kk", "ru")).toBe("en");
|
||
expect(pickLang("xx", "kk", "en")).toBe("kk");
|
||
expect(pickLang(undefined, undefined, "fr, en;q=0.8, kk;q=0.9")).toBe("kk");
|
||
expect(pickLang(undefined, undefined, "en;q=0, de")).toBe("ru");
|
||
expect(pickLang(undefined, undefined, undefined)).toBe("ru");
|
||
});
|
||
|
||
it("во всех языках один и тот же набор текстов и подстановок", () => {
|
||
const placeholders = (text: string) => (text.match(/\{\w+\}/g) ?? []).sort();
|
||
for (const { code } of LANGS) {
|
||
expect(Object.keys(locales[code]).sort(), code).toEqual(Object.keys(locales.ru).sort());
|
||
for (const [key, text] of Object.entries(locales[code])) {
|
||
expect(text.trim(), `${code}:${key}`).not.toBe("");
|
||
const reference = locales.ru[key as keyof typeof locales.ru];
|
||
expect(placeholders(text), `${code}:${key}`).toEqual(placeholders(reference));
|
||
}
|
||
}
|
||
});
|
||
|
||
it("в текстах нет слов из колонки «Нельзя» словаря docs/glossary.md", () => {
|
||
const glossary = readFileSync(new URL("../docs/glossary.md", import.meta.url), "utf8");
|
||
const forbidden = glossary
|
||
.split("\n")
|
||
.filter((line) => line.startsWith("|") && !line.startsWith("|---"))
|
||
.slice(1)
|
||
.flatMap((line) => (line.split("|")[3] ?? "").split(","))
|
||
.map((word) => word.trim().toLowerCase())
|
||
.filter(Boolean);
|
||
expect(forbidden.length).toBeGreaterThan(50);
|
||
const violations: string[] = [];
|
||
for (const { code } of LANGS) {
|
||
for (const [key, text] of Object.entries(locales[code])) {
|
||
for (const word of forbidden) {
|
||
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||
// Слово целиком: рядом нет других букв и цифр (кириллица, казахские буквы, латиница).
|
||
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu");
|
||
if (pattern.test(text)) violations.push(`${code}:${key} — «${word}»`);
|
||
}
|
||
}
|
||
}
|
||
expect(violations).toEqual([]);
|
||
});
|
||
});
|