customer/test/library.test.ts
peppa-bot a2c3d2e3dc
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 4с
peppa/test test: success за 61с
peppa/build build: success за 3с
ci / checks (pull_request) Successful in 1m27s
deploy / deploy (pull_request) Successful in 9s
CLT-13: пароль редактора библиотеки из секретов проекта Пеппы
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:05:24 +00:00

380 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { buildApp } from "../src/app.ts";
import { editorPasswordFromEnv } from "../src/modules/library/config.ts";
import { parseMultipart } from "../src/modules/library/forms.ts";
import { LANGS } from "../src/modules/library/i18n/index.ts";
import { createTestDb } from "./helpers/db.ts";
let app: FastifyInstance;
let db: Awaited<ReturnType<typeof createTestDb>>;
const PASS = "mock-owner-pass";
const FORM = { "content-type": "application/x-www-form-urlencoded" };
const MOCK_PDF = Buffer.from("%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n");
const MOCK_EPUB = Buffer.concat([
Buffer.from([0x50, 0x4b, 0x03, 0x04]),
Buffer.alloc(26),
Buffer.from("mimetypeapplication/epub+zip"),
Buffer.from("rest-of-zip"),
]);
beforeEach(async () => {
db = await createTestDb();
app = await buildApp({ db, library: { editorPassword: PASS } });
});
afterEach(async () => app.close());
const body = (fields: Record<string, string | string[]>) => {
const p = new URLSearchParams();
for (const [k, v] of Object.entries(fields)) for (const x of Array.isArray(v) ? v : [v]) p.append(k, x);
return p.toString();
};
async function login(password = PASS) {
return app.inject({ method: "POST", url: "/library/editor/login", headers: FORM, payload: body({ password }) });
}
async function owner() {
const res = await login();
expect(res.statusCode).toBe(303);
const cookie = String(res.headers["set-cookie"]).split(";")[0] as string;
const page = await app.inject({ method: "GET", url: "/library/editor", headers: { cookie } });
const csrf = /name="csrf" value="([^"]+)"/.exec(page.body)?.[1] as string;
const post = (url: string, fields: Record<string, string | string[]>) =>
app.inject({ method: "POST", url, headers: { ...FORM, cookie }, payload: body({ csrf, ...fields }) });
return { cookie, csrf, post };
}
const sectionId = async (title: string) =>
(await db.query<{ id: string }>("SELECT id FROM library_sections WHERE title = $1", [title])).rows[0]?.id as string;
const parentTitle = async (id: string) =>
(await db.query<{ title: string }>("SELECT p.title FROM library_sections s JOIN library_sections p ON p.id = s.parent_id WHERE s.id = $1", [id])).rows[0]?.title;
const catalog = async (q?: string) => (await app.inject({ method: "GET", url: q === undefined ? "/library" : `/library?q=${encodeURIComponent(q)}` })).body;
async function createItem(o: Awaited<ReturnType<typeof owner>>, fields: Record<string, string | string[]>) {
const res = await o.post("/library/editor/items", fields);
expect(res.statusCode).toBe(303);
return /\/library\/editor\/items\/([0-9a-f-]{36})/.exec(String(res.headers.location))?.[1] as string;
}
function multipart(csrf: string, rights: string | null, file: { name: string; data: Buffer }) {
const b = "----mockBoundary42";
const parts: Buffer[] = [Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="csrf"\r\n\r\n${csrf}\r\n`)];
if (rights) parts.push(Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="rights"\r\n\r\n${rights}\r\n`));
parts.push(Buffer.from(`--${b}\r\nContent-Disposition: form-data; name="file"; filename="${file.name}"\r\nContent-Type: application/octet-stream\r\n\r\n`), file.data, Buffer.from(`\r\n--${b}--\r\n`));
return { payload: Buffer.concat(parts), contentType: `multipart/form-data; boundary=${b}` };
}
async function upload(o: Awaited<ReturnType<typeof owner>>, id: string, rights: string | null, file: { name: string; data: Buffer }) {
const m = multipart(o.csrf, rights, file);
return app.inject({ method: "POST", url: `/library/editor/items/${id}/file`, headers: { cookie: o.cookie, "content-type": m.contentType }, payload: m.payload });
}
describe("Requirement: Вход в библиотеку с главной", () => {
it("Scenario: Ссылка на главной", async () => {
const res = await app.inject({ method: "GET", url: "/" });
expect(res.body).toContain('<a href="/library">Библиотека Клиентологии 360°</a>');
});
it("Scenario: Библиотека без БД", async () => {
const bare = await buildApp();
expect((await bare.inject({ method: "GET", url: "/library" })).statusCode).toBe(404);
await bare.close();
});
});
describe("Requirement: Начальное оглавление", () => {
it("Scenario: Оглавление в каталоге", async () => {
const html = await catalog();
expect(html).toContain("I. Понять клиента и спроектировать сервис");
expect(html).toContain("IV. Применять ИИ и внедрять улучшения");
expect(html).toContain("3. Дизайн-мышление и путь клиента");
expect(html).toContain("Service blueprint");
expect(html).toContain("14. Отраслевые кейсы");
expect(await parentTitle(await sectionId("Service blueprint"))).toBe("Дизайн-мышление и путь клиента");
const counts = (await db.query<{ depth: number; n: number }>(
`SELECT CASE WHEN parent_id IS NULL THEN 0 WHEN parent_id IN (SELECT id FROM library_sections WHERE parent_id IS NULL) THEN 1 ELSE 2 END AS depth, count(*)::int AS n
FROM library_sections GROUP BY 1 ORDER BY 1`,
)).rows;
expect(counts.slice(0, 2)).toEqual([{ depth: 0, n: 4 }, { depth: 1, n: 14 }]);
});
it("Scenario: Нумерация после перемещения", async () => {
const o = await owner();
const cases = await sectionId("Отраслевые кейсы");
expect((await o.post("/library/editor/move", { section: cases, parent: await sectionId("Понять клиента и спроектировать сервис") })).statusCode).toBe(303);
for (let i = 0; i < 3; i++) await o.post(`/library/editor/sections/${cases}`, { action: "up" });
const html = await catalog();
expect(html).toContain("1. Отраслевые кейсы");
expect(html).toContain("2. Основы клиентологии");
expect(html).toContain("14. Внедрение и развитие");
});
it("Scenario: Переводы страниц на казахский и английский", async () => {
expect(Object.keys(LANGS.kk).sort()).toEqual(Object.keys(LANGS.ru).sort());
const res = await app.inject({ method: "GET", url: "/library?lang=en" });
expect(res.body).toContain('<html lang="en">');
expect(res.body).toContain("Clientology 360° Library");
const cookie = String(res.headers["set-cookie"]).split(";")[0] as string;
expect((await app.inject({ method: "GET", url: "/library", headers: { cookie } })).body).toContain('<html lang="en">');
expect((await app.inject({ method: "GET", url: "/library?lang=kk" })).body).toContain("Клиентология 360° кітапханасы");
});
});
describe("Requirement: Вход в редактор", () => {
it("Scenario: Верный пароль", async () => {
const o = await owner();
const page = await app.inject({ method: "GET", url: "/library/editor", headers: { cookie: o.cookie } });
expect(page.body).toContain("Редактор библиотеки");
expect(page.body).toContain("Дизайн-мышление и путь клиента");
expect(String((await login()).headers["set-cookie"])).toMatch(/HttpOnly; SameSite=Strict/);
});
it("Scenario: Без входа", async () => {
const page = await app.inject({ method: "GET", url: "/library/editor" });
expect(page.body).toContain("Вход в редактор библиотеки");
const id = await sectionId("Отраслевые кейсы");
const res = await app.inject({ method: "POST", url: `/library/editor/sections/${id}`, headers: FORM, payload: body({ action: "rename", title: "Взлом" }) });
expect(res.statusCode).toBe(401);
const up = await upload({ cookie: "", csrf: "x", post: undefined as never }, "00000000-0000-4000-8000-000000000000", "own", { name: "a.pdf", data: MOCK_PDF });
expect(up.statusCode).toBe(401);
expect(await sectionId("Взлом")).toBeUndefined();
});
it("Scenario: Неверный пароль и подбор", async () => {
const bad = await login("wrong");
expect(bad.statusCode).toBe(401);
expect(bad.body).toContain("Пароль не подошёл");
for (let i = 0; i < 4; i++) await login("wrong");
const res = await login();
expect(res.statusCode).toBe(429);
expect(res.body).toContain("Слишком много попыток");
});
it("Scenario: Форма без CSRF-токена", async () => {
const o = await owner();
const id = await sectionId("Отраслевые кейсы");
const res = await app.inject({ method: "POST", url: `/library/editor/sections/${id}`, headers: { ...FORM, cookie: o.cookie }, payload: body({ action: "rename", title: "Взлом" }) });
expect(res.statusCode).toBe(403);
const cross = await app.inject({ method: "POST", url: `/library/editor/sections/${id}`, headers: { ...FORM, cookie: o.cookie, origin: "https://evil.example" }, payload: body({ csrf: o.csrf, action: "rename", title: "Взлом" }) });
expect(cross.statusCode).toBe(403);
expect(await sectionId("Взлом")).toBeUndefined();
});
it("Scenario: Редактор без пароля в настройках", async () => {
const off = await buildApp({ db });
const page = await off.inject({ method: "GET", url: "/library/editor" });
expect(page.body).toContain("Редактор пока не включён");
expect((await off.inject({ method: "POST", url: "/library/editor/login", headers: FORM, payload: body({ password: "" }) })).statusCode).toBe(404);
expect((await off.inject({ method: "GET", url: "/library" })).statusCode).toBe(200);
await off.close();
});
});
describe("Requirement: Редактирование оглавления", () => {
it("Scenario: Добавление и перемещение подпункта", async () => {
const o = await owner();
expect((await o.post("/library/editor/sections", { parent: await sectionId("Дизайн-мышление и путь клиента"), title: "Карта эмоций" })).statusCode).toBe(303);
const id = await sectionId("Карта эмоций");
expect(await parentTitle(id)).toBe("Дизайн-мышление и путь клиента");
await o.post(`/library/editor/sections/${id}`, { action: "rename", title: "Карта эмоций клиента" });
await o.post("/library/editor/move", { section: id, parent: await sectionId("Внедрение и развитие") });
expect(await parentTitle(id)).toBe("Внедрение и развитие");
const editor = await app.inject({ method: "GET", url: "/library/editor", headers: { cookie: o.cookie } });
expect(editor.body).toContain("Карта эмоций клиента");
});
it("Scenario: Скрытие и восстановление", async () => {
const o = await owner();
const id = await sectionId("Отраслевые кейсы");
await o.post(`/library/editor/sections/${id}`, { action: "hide" });
expect(await catalog()).not.toContain("Отраслевые кейсы");
expect(await catalog()).not.toContain("Телеком");
await o.post(`/library/editor/sections/${id}`, { action: "restore" });
expect(await catalog()).toContain("14. Отраслевые кейсы");
});
it("Scenario: Перенос в собственный подпункт", async () => {
const o = await owner();
const chapter = await sectionId("Дизайн-мышление и путь клиента");
const res = await o.post("/library/editor/move", { section: chapter, parent: await sectionId("Прототип") });
expect(res.statusCode).toBe(422);
expect(res.body).toContain("нельзя перенести внутрь самого себя");
expect(await parentTitle(chapter)).toBe("Понять клиента и спроектировать сервис");
});
it("Scenario: Пустое название раздела", async () => {
const o = await owner();
const res = await o.post("/library/editor/sections", { title: " " });
expect(res.statusCode).toBe(422);
expect(res.body).toContain("Не указано название");
});
});
describe("Requirement: Карточка материала", () => {
it("Scenario: Материал в двух разделах", async () => {
const o = await owner();
await o.post("/library/editor/sections", { parent: await sectionId("Дизайн-мышление и путь клиента"), title: "Карта эмоций" });
const sub = await sectionId("Карта эмоций");
const impl = await sectionId("Внедрение и развитие");
const id = await createItem(o, {
title: "Service Design Doing", author: "Marc Stickdorn", edition: "O'Reilly, 2018", language: "английский",
annotation: "Практика сервис-дизайна.", tags: "blueprint, сервис-дизайн", link: "https://www.oreilly.com/library/view/this-is-service/9781491927175/",
access: "public", status: "published", sections: [sub, impl],
});
await o.post(`/library/editor/sections/${sub}`, { action: "rename", title: "Карта эмоций клиента" });
await o.post("/library/editor/move", { section: sub, parent: await sectionId("Экономика сервиса") });
await o.post(`/library/editor/sections/${sub}`, { action: "up" });
const links = (await db.query<{ title: string }>("SELECT s.title FROM library_item_sections l JOIN library_sections s ON s.id = l.section_id WHERE l.item_id = $1 ORDER BY 1", [id])).rows;
expect(links.map((r) => r.title)).toEqual(["Внедрение и развитие", "Карта эмоций клиента"]);
const card = await app.inject({ method: "GET", url: `/library/items/${id}` });
expect(card.statusCode).toBe(200);
expect(card.body).toContain("Карта эмоций клиента");
expect(card.body).toContain("13. Внедрение и развитие");
expect(card.body).toContain("O&#39;Reilly, 2018");
expect(card.body).toContain('rel="noopener noreferrer nofollow"');
expect((await catalog()).match(/Service Design Doing/g)).toHaveLength(2);
});
it("Scenario: Публикация без источника", async () => {
const o = await owner();
const res = await o.post("/library/editor/items", { title: "Без источника", status: "published" });
expect(res.statusCode).toBe(422);
expect(res.body).toContain("Добавьте ссылку на источник или файл");
expect((await db.query("SELECT 1 FROM library_items")).rows).toHaveLength(0);
const id = await createItem(o, { title: "Без источника", status: "draft" });
expect((await o.post(`/library/editor/items/${id}`, { title: "Без источника", status: "published" })).statusCode).toBe(422);
expect((await db.query<{ status: string }>("SELECT status FROM library_items WHERE id = $1", [id])).rows[0]?.status).toBe("draft");
expect((await o.post(`/library/editor/items/${id}`, { title: "Без источника", link: "javascript:alert(1)" })).body).toContain("Ссылка не похожа");
});
it("Scenario: Файл не PDF и не EPUB", async () => {
const o = await owner();
const id = await createItem(o, { title: "Книга" });
const res = await upload(o, id, "own", { name: "book.pdf", data: Buffer.from("<html>not a pdf</html>") });
expect(res.statusCode).toBe(422);
expect(res.body).toContain("Файл не подходит");
expect((await db.query<{ file_name: string | null }>("SELECT file_name FROM library_items WHERE id = $1", [id])).rows[0]?.file_name).toBeNull();
});
it("Scenario: Файл без основания прав", async () => {
const o = await owner();
const id = await createItem(o, { title: "Книга" });
const res = await upload(o, id, null, { name: "book.pdf", data: MOCK_PDF });
expect(res.statusCode).toBe(422);
expect(res.body).toContain("почему файл можно выложить");
expect((await db.query<{ file_name: string | null }>("SELECT file_name FROM library_items WHERE id = $1", [id])).rows[0]?.file_name).toBeNull();
});
it("Scenario: Файл больше лимита", async () => {
const o = await owner();
const id = await createItem(o, { title: "Книга" });
const big = Buffer.concat([MOCK_PDF, Buffer.alloc(20 * 1024 * 1024)]);
const res = await upload(o, id, "own", { name: "big.pdf", data: big });
expect(res.statusCode).toBe(422);
expect(res.body).toContain("слишком большой");
});
});
describe("Requirement: Каталог и поиск", () => {
it("Scenario: Поиск по автору и тегу", async () => {
const o = await owner();
await createItem(o, { title: "Service Design Doing", author: "Stickdorn", tags: "blueprint", link: "https://example.com/sdd", status: "published" });
await createItem(o, { title: "Секретный черновик", author: "Stickdorn", tags: "blueprint", link: "https://example.com/d" });
await createItem(o, { title: "Путь клиента", author: "Иванова", tags: "Эмпатия", link: "https://example.com/p", status: "published" });
for (const q of ["stickdorn", "BLUEPRINT", "service design"]) {
const html = await catalog(q);
expect(html).toContain("Service Design Doing");
expect(html).not.toContain("Секретный черновик");
}
expect(await catalog("эмпатия")).toContain("Путь клиента");
expect(await catalog("ИВАНОВА")).toContain("Путь клиента");
});
it("Scenario: Ничего не найдено", async () => {
const o = await owner();
await createItem(o, { title: "Книга 100%", link: "https://example.com/x", status: "published" });
expect(await catalog("%_")).toContain("Ничего не нашлось");
expect(await catalog("<script>")).toContain("&lt;script&gt;");
});
});
describe("Requirement: Защита черновиков и закрытых файлов", () => {
it("Scenario: Прямая ссылка на черновик", async () => {
const o = await owner();
const id = await createItem(o, { title: "Секретный черновик" });
expect((await upload(o, id, "own", { name: "draft.pdf", data: MOCK_PDF })).statusCode).toBe(303);
expect((await app.inject({ method: "GET", url: `/library/items/${id}` })).statusCode).toBe(404);
expect((await app.inject({ method: "GET", url: `/library/items/${id}/file` })).statusCode).toBe(404);
expect(await catalog()).not.toContain("Секретный черновик");
const preview = await app.inject({ method: "GET", url: `/library/items/${id}`, headers: { cookie: o.cookie } });
expect(preview.statusCode).toBe(200);
expect(preview.body).toContain("Черновик: эту карточку видите только вы.");
expect((await app.inject({ method: "GET", url: "/library/items/not-a-uuid" })).statusCode).toBe(404);
});
it("Scenario: Закрытый файл", async () => {
const o = await owner();
const id = await createItem(o, { title: "Закрытая книга", access: "closed" });
await upload(o, id, "licensed", { name: "Книга «Сервис».pdf", data: MOCK_PDF });
await o.post(`/library/editor/items/${id}`, { title: "Закрытая книга", access: "closed", status: "published" });
const guest = await app.inject({ method: "GET", url: `/library/items/${id}/file` });
expect(guest.statusCode).toBe(403);
expect(guest.body).toContain("Войдите в аккаунт");
const reg = await app.inject({ method: "POST", url: "/api/auth/register", headers: { "content-type": "application/json" }, payload: { email: "anna@example.com", password: "correct-horse-9" } });
const userCookie = String(reg.headers["set-cookie"]).split(";")[0] as string;
const user = await app.inject({ method: "GET", url: `/library/items/${id}/file`, headers: { cookie: userCookie } });
expect(user.statusCode).toBe(200);
expect(user.headers["content-type"]).toBe("application/pdf");
expect(user.headers["cache-control"]).toBe("private, no-store");
expect(user.headers["content-disposition"]).toContain("filename*=UTF-8''");
expect(user.rawPayload.equals(MOCK_PDF)).toBe(true);
expect((await app.inject({ method: "GET", url: `/library/items/${id}/file`, headers: { cookie: o.cookie } })).statusCode).toBe(200);
});
it("Scenario: Открытый файл", async () => {
const o = await owner();
const id = await createItem(o, { title: "Открытая книга" });
expect((await upload(o, id, "public_domain", { name: "book.epub", data: MOCK_EPUB })).statusCode).toBe(303);
await o.post(`/library/editor/items/${id}`, { title: "Открытая книга", status: "published" });
const res = await app.inject({ method: "GET", url: `/library/items/${id}/file` });
expect(res.statusCode).toBe(200);
expect(res.headers["content-type"]).toBe("application/epub+zip");
expect(res.headers["content-disposition"]).toMatch(/^attachment;/);
expect(await o.post(`/library/editor/items/${id}/file/remove`, {})).toMatchObject({ statusCode: 422 });
});
});
describe("multipart parser", () => {
it("rejects a body without the boundary", () => {
expect(parseMultipart(Buffer.from("garbage"), "x")).toBeNull();
});
});
describe("Requirement: Пароль редактора из секретов проекта", () => {
it("Scenario: Пароль из секретов проекта", async () => {
await app.close();
app = await buildApp({ db, library: { editorPassword: editorPasswordFromEnv(`${PASS}\n`) } });
const page = await app.inject({ method: "GET", url: "/library/editor" });
expect(page.body).toContain("Вход в редактор библиотеки");
expect(page.body).toContain('type="password"');
expect(page.body).not.toContain("Редактор пока не включён");
const o = await owner();
const id = await createItem(o, { title: "Карта пути клиента", status: "draft" });
const draft = await app.inject({ method: "GET", url: `/library/editor/items/${id}`, headers: { cookie: o.cookie } });
expect(draft.statusCode).toBe(200);
expect(draft.body).toContain("Карта пути клиента");
expect(await catalog()).not.toContain("Карта пути клиента");
expect((await app.inject({ method: "GET", url: `/library/items/${id}` })).statusCode).toBe(404);
});
it("Scenario: Пароль из одних пробелов", async () => {
expect(editorPasswordFromEnv(" \n\t ")).toBeUndefined();
expect(editorPasswordFromEnv(undefined)).toBeUndefined();
const off = await buildApp({ db, library: { editorPassword: editorPasswordFromEnv(" ") } });
const page = await off.inject({ method: "GET", url: "/library/editor" });
expect(page.body).toContain("Редактор пока не включён");
expect((await off.inject({ method: "POST", url: "/library/editor/login", headers: FORM, payload: body({ password: " " }) })).statusCode).toBe(404);
await off.close();
});
});