CLT-12: библиотека 360° — оглавление, каталог, редактор, переводы

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-23 04:51:59 +00:00
parent 3c031c44f4
commit 8060477e41
17 changed files with 1439 additions and 1 deletions

View File

@ -25,6 +25,8 @@ services:
TELEGRAM_BOT_TOKEN: "${TELEGRAM_BOT_TOKEN:-}" TELEGRAM_BOT_TOKEN: "${TELEGRAM_BOT_TOKEN:-}"
TELEGRAM_WEBHOOK_SECRET: "${TELEGRAM_WEBHOOK_SECRET:-}" TELEGRAM_WEBHOOK_SECRET: "${TELEGRAM_WEBHOOK_SECRET:-}"
TELEGRAM_BOT_USERNAME: "${TELEGRAM_BOT_USERNAME:-}" TELEGRAM_BOT_USERNAME: "${TELEGRAM_BOT_USERNAME:-}"
# Пароль редактора библиотеки (CLT-12) — из secrets Actions; без него редактор выключен, каталог работает.
LIBRARY_EDITOR_PASSWORD: "${LIBRARY_EDITOR_PASSWORD:-}"
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy

129
migrations/0009_library.sql Normal file
View File

@ -0,0 +1,129 @@
-- CLT-12: библиотека «Клиентология 360°» — оглавление, материалы, связи, сессии редактора.
CREATE TABLE library_sections (
id uuid PRIMARY KEY,
parent_id uuid REFERENCES library_sections (id),
title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
position integer NOT NULL DEFAULT 0,
hidden boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX library_sections_parent ON library_sections (parent_id, position);
CREATE TABLE library_items (
id uuid PRIMARY KEY,
title text NOT NULL,
author text NOT NULL DEFAULT '',
edition text NOT NULL DEFAULT '',
language text NOT NULL DEFAULT '',
annotation text NOT NULL DEFAULT '',
tags text[] NOT NULL DEFAULT '{}',
link_url text,
file_name text,
file_type text CHECK (file_type IN ('application/pdf', 'application/epub+zip')),
file_size integer,
file_data bytea,
file_access text NOT NULL DEFAULT 'public' CHECK (file_access IN ('public', 'closed')),
rights_basis text CHECK (rights_basis IN ('own', 'licensed', 'public_domain')),
status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE library_item_sections (
item_id uuid NOT NULL REFERENCES library_items (id) ON DELETE CASCADE,
section_id uuid NOT NULL REFERENCES library_sections (id),
PRIMARY KEY (item_id, section_id)
);
CREATE INDEX library_item_sections_section ON library_item_sections (section_id);
CREATE TABLE library_editor_sessions (
token_hash bytea PRIMARY KEY,
csrf_token text NOT NULL,
expires_at timestamptz NOT NULL
);
-- Начальное оглавление: 4 части, 14 глав и пункты. Номера не храним — считаются при выводе.
INSERT INTO library_sections (id, parent_id, title, position) VALUES
('ce872560-1585-4ba1-80e5-6fb8162557d3', NULL, 'Понять клиента и спроектировать сервис', 0),
('592ce21c-9ae6-4cf5-8e06-42244c139d42', 'ce872560-1585-4ba1-80e5-6fb8162557d3', 'Основы клиентологии', 0),
('2e3bbc97-5cc9-4aff-81f9-eda5bf5dee8b', '592ce21c-9ae6-4cf5-8e06-42244c139d42', 'Обещание', 0),
('e3c9ec20-43bf-4ccc-8f43-d18d655b569c', '592ce21c-9ae6-4cf5-8e06-42244c139d42', 'Ожидания', 1),
('a8051d6a-3859-44d2-88ea-278be90db578', '592ce21c-9ae6-4cf5-8e06-42244c139d42', 'Ценность', 2),
('9599a330-d7bd-47c8-89e8-40988392f000', '592ce21c-9ae6-4cf5-8e06-42244c139d42', 'Зрелость', 3),
('0067057c-e06a-4d4d-85f4-062ebb6beeef', 'ce872560-1585-4ba1-80e5-6fb8162557d3', 'Исследование клиентов', 1),
('438aed57-732f-4c1d-8f4a-4f405e2c500f', '0067057c-e06a-4d4d-85f4-062ebb6beeef', 'Задачи', 0),
('782f9cf3-da81-4184-8545-d921d9d721fb', '0067057c-e06a-4d4d-85f4-062ebb6beeef', 'Сегменты', 1),
('503d3f93-9178-488c-8bd6-0a2aa2fd246d', '0067057c-e06a-4d4d-85f4-062ebb6beeef', 'Интервью', 2),
('b3db4d2c-c216-4439-8df7-163c310d7ac3', '0067057c-e06a-4d4d-85f4-062ebb6beeef', 'Наблюдение', 3),
('c5100774-1f2b-48ca-8a70-6171d74289bf', '0067057c-e06a-4d4d-85f4-062ebb6beeef', 'Обратная связь', 4),
('d1b6ad13-90fa-4b31-864a-55ee65d13911', '0067057c-e06a-4d4d-85f4-062ebb6beeef', 'Отток', 5),
('7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'ce872560-1585-4ba1-80e5-6fb8162557d3', 'Дизайн-мышление и путь клиента', 2),
('8f4b56f5-e742-45d7-88d4-99096e4655a3', '7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'Карта пути', 0),
('77fa1311-177d-4fa8-8743-fe550bfb96d0', '7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'Проблема', 1),
('f5c976dc-88b7-4a54-8061-8abb01f881d3', '7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'Идеи', 2),
('7751db3e-e3e3-4aec-83b7-6a715fd15705', '7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'Прототип', 3),
('b29db4f6-bec5-40a1-813f-732c26d408a9', '7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'Service blueprint', 4),
('c184783e-adc7-453e-8a45-ec3fd3059128', '7ad0c3a7-e343-46e4-8866-86ec9ce71c44', 'Тест с клиентами', 5),
('ea6060eb-44d4-4996-859f-41d0df486c2a', NULL, 'Организовать работу на всём пути клиента', 1),
('1c070b54-b8e3-40a3-83a0-2371b9ea3468', 'ea6060eb-44d4-4996-859f-41d0df486c2a', 'Продаванам', 0),
('5f961240-e058-4dbf-8590-dfee0acbefda', '1c070b54-b8e3-40a3-83a0-2371b9ea3468', 'Потребности', 0),
('5695e8f4-a8e5-448c-89b6-cfd4e429f16d', '1c070b54-b8e3-40a3-83a0-2371b9ea3468', 'Предложение', 1),
('a02e10c8-147d-475d-8ee4-8367310a3456', '1c070b54-b8e3-40a3-83a0-2371b9ea3468', 'Договорённости', 2),
('4ae02efa-8080-44c9-86d3-0226d4334d54', '1c070b54-b8e3-40a3-83a0-2371b9ea3468', 'Передача клиента', 3),
('dce77359-21a7-4c1c-8fef-b0974227dcd0', '1c070b54-b8e3-40a3-83a0-2371b9ea3468', 'Продление', 4),
('418bd309-f079-46ab-817d-2aae20866cd4', 'ea6060eb-44d4-4996-859f-41d0df486c2a', 'Операционные модели', 1),
('2cc3105a-accb-468b-89f9-cad507f9c49c', '418bd309-f079-46ab-817d-2aae20866cd4', 'Роли', 0),
('74af9cbb-0ef7-4dbb-8bf5-16fcc8e7d947', '418bd309-f079-46ab-817d-2aae20866cd4', 'Подрядчики', 1),
('08bf56de-a716-449a-8b28-1c7c7fab04fb', '418bd309-f079-46ab-817d-2aae20866cd4', 'Эскалации', 2),
('d8ad3a41-64e4-4b5e-8b37-f591907d992b', '418bd309-f079-46ab-817d-2aae20866cd4', 'Нагрузка', 3),
('62e6f9bf-9f9d-4339-8544-142628d64408', 'ea6060eb-44d4-4996-859f-41d0df486c2a', 'Каналы, контакт-центр и самообслуживание', 2),
('d307b171-0b87-4014-875c-9c0f93adacf1', '62e6f9bf-9f9d-4339-8544-142628d64408', 'Маршрутизация', 0),
('4545e0d3-e788-4731-8f03-310e271b0e73', '62e6f9bf-9f9d-4339-8544-142628d64408', 'Контекст', 1),
('f656435e-2970-4610-8bf5-ac1f94811c34', '62e6f9bf-9f9d-4339-8544-142628d64408', 'Доступность', 2),
('0f2e2995-0104-464c-855e-14b932ccf359', '62e6f9bf-9f9d-4339-8544-142628d64408', 'Языки', 3),
('110994f9-93b7-4e43-884d-41f418d8fedb', 'ea6060eb-44d4-4996-859f-41d0df486c2a', 'Люди и культура сервиса', 3),
('5180b42d-b323-4b58-82d0-50fa0e1d423b', '110994f9-93b7-4e43-884d-41f418d8fedb', 'Навыки', 0),
('5b9e3cca-7fc7-461d-8f7b-1f3482c30f3d', '110994f9-93b7-4e43-884d-41f418d8fedb', 'Адаптация', 1),
('aa70f483-90c1-48be-84af-29a2d9a4c4f2', '110994f9-93b7-4e43-884d-41f418d8fedb', 'Коммуникация', 2),
('ef05707f-389b-4c10-87e4-83e8aa0e5f89', '110994f9-93b7-4e43-884d-41f418d8fedb', 'Обучение', 3),
('0c4399d5-f5ba-4438-836f-29af07d22fa3', '110994f9-93b7-4e43-884d-41f418d8fedb', 'Мотивация', 4),
('86532cf0-2cf2-4c51-87df-b420da452f22', NULL, 'Управлять качеством, сбоями и экономикой', 2),
('0eeb6f2e-406a-489b-850b-bec3099c4e5c', '86532cf0-2cf2-4c51-87df-b420da452f22', 'Стандарты и качество', 0),
('83f3b421-fb48-42db-8cac-eb84d560fd45', '0eeb6f2e-406a-489b-850b-bec3099c4e5c', 'Стандарты', 0),
('12dd1324-a5d3-4624-882c-4aa56796b943', '0eeb6f2e-406a-489b-850b-bec3099c4e5c', 'Уровни сервиса', 1),
('2aa15750-b787-4930-8089-93ae97c4484e', '0eeb6f2e-406a-489b-850b-bec3099c4e5c', 'Аудит и калибровка', 2),
('baa1f2e2-b45f-419f-823c-149c767a690d', '86532cf0-2cf2-4c51-87df-b420da452f22', 'Жалобы и восстановление', 1),
('e7277dba-a53e-43ff-8044-112b80ee89cd', 'baa1f2e2-b45f-419f-823c-149c767a690d', 'Решение', 0),
('eb855b12-851a-4385-8c6d-650c9be9c09e', 'baa1f2e2-b45f-419f-823c-149c767a690d', 'Сбои', 1),
('bd7017fc-0a4a-4739-8ecc-0f6e2eb2a4cf', 'baa1f2e2-b45f-419f-823c-149c767a690d', 'Компенсации', 2),
('0b719584-c7f7-4b89-8ad3-3f0faff800b5', 'baa1f2e2-b45f-419f-823c-149c767a690d', 'Первопричины', 3),
('044d9a8b-ded4-4088-8e2c-6772aab39325', '86532cf0-2cf2-4c51-87df-b420da452f22', 'Метрики и аналитика', 2),
('c7e6ac28-7f6e-43e5-8385-9eabc3f3650a', '044d9a8b-ded4-4088-8e2c-6772aab39325', 'Клиентский результат', 0),
('d43fbb9f-03b4-448b-8159-b3018a739be7', '044d9a8b-ded4-4088-8e2c-6772aab39325', 'CSAT', 1),
('4259d1b0-2076-4b57-853b-92ab5238f305', '044d9a8b-ded4-4088-8e2c-6772aab39325', 'CES', 2),
('00de94c8-0075-4e48-816a-e35eaeff285f', '044d9a8b-ded4-4088-8e2c-6772aab39325', 'NPS', 3),
('a95b4f61-7311-4d5a-8879-862be476dc3a', '044d9a8b-ded4-4088-8e2c-6772aab39325', 'FCR', 4),
('c1add449-a848-43ce-821e-c012729df439', '044d9a8b-ded4-4088-8e2c-6772aab39325', 'Паспорта и анализ', 5),
('d65dc01b-21b0-4a6c-8874-8c8f400b7991', '86532cf0-2cf2-4c51-87df-b420da452f22', 'Экономика сервиса', 3),
('c54c38df-00d6-4dd4-8350-f57fbf9604cb', 'd65dc01b-21b0-4a6c-8874-8c8f400b7991', 'Стоимость решения', 0),
('7f2c2d80-c282-4fe4-8dab-80ec57caf193', 'd65dc01b-21b0-4a6c-8874-8c8f400b7991', 'Потери', 1),
('063c61e9-1537-4062-8f5a-fbd8802e996b', 'd65dc01b-21b0-4a6c-8874-8c8f400b7991', 'Удержание', 2),
('62e89cb6-3ac9-4240-8752-57d803b51cfc', 'd65dc01b-21b0-4a6c-8874-8c8f400b7991', 'Бизнес-кейс', 3),
('3e9c8367-d72a-4291-8931-4e39c9668b6e', NULL, 'Применять ИИ и внедрять улучшения', 3),
('56ee217c-0043-4941-854f-7a1a32bb9b37', '3e9c8367-d72a-4291-8931-4e39c9668b6e', 'Данные, технологии и ИИ', 0),
('6f8b2b76-d780-4a37-83b3-770c0345dfa0', '56ee217c-0043-4941-854f-7a1a32bb9b37', 'CRM', 0),
('cb5d6a0c-1b3d-4cab-8b71-3964b211fb4e', '56ee217c-0043-4941-854f-7a1a32bb9b37', 'Знания', 1),
('881fcea7-d92b-4619-82d9-2a111cc55e5c', '56ee217c-0043-4941-854f-7a1a32bb9b37', 'Сценарии', 2),
('9d925cfa-c336-4d89-884f-c661aa99815f', '56ee217c-0043-4941-854f-7a1a32bb9b37', 'Контроль качества', 3),
('0d7016b9-ceb3-40cc-8825-67ad25b4346c', '56ee217c-0043-4941-854f-7a1a32bb9b37', 'Переход к человеку', 4),
('72e163e9-1476-429c-86c7-f282dfa8bfe5', '3e9c8367-d72a-4291-8931-4e39c9668b6e', 'Внедрение и развитие', 1),
('5bba9d2d-a295-4753-8c38-93a8bf688bdf', '72e163e9-1476-429c-86c7-f282dfa8bfe5', 'Диагностика', 0),
('25f710fc-aa78-4956-835c-291f04701bbd', '72e163e9-1476-429c-86c7-f282dfa8bfe5', 'Приоритеты', 1),
('88b622cd-607f-4e0c-80a4-2fc84dff2189', '72e163e9-1476-429c-86c7-f282dfa8bfe5', 'Пилот', 2),
('2ea90ccb-cfb7-452e-8624-8b002dcf476e', '72e163e9-1476-429c-86c7-f282dfa8bfe5', 'Оценка и масштабирование', 3),
('39573d7c-6679-4985-87e1-cd3b5747fae2', '3e9c8367-d72a-4291-8931-4e39c9668b6e', 'Отраслевые кейсы', 2),
('ed556158-a02f-4626-8958-0550cbb0646e', '39573d7c-6679-4985-87e1-cd3b5747fae2', 'Телеком', 0),
('e53d4f33-8369-4290-8d43-53c52697d7ed', '39573d7c-6679-4985-87e1-cd3b5747fae2', 'Подписки', 1),
('8f4f2faf-897b-4d40-85dd-94c7187b1347', '39573d7c-6679-4985-87e1-cd3b5747fae2', 'Розница', 2),
('0579be92-017d-4f91-8560-04fb9cb70271', '39573d7c-6679-4985-87e1-cd3b5747fae2', 'Логистика', 3),
('67d9e689-da9d-498a-8731-0fde94caee58', '39573d7c-6679-4985-87e1-cd3b5747fae2', 'B2B и госуслуги', 4);

View File

@ -0,0 +1,41 @@
# Дизайн
## Данные (migrations/0009_library.sql)
- `library_sections(id uuid, parent_id → library_sections, title, position, hidden, created_at)` —
дерево любой глубины (редактор ограничивает 5 уровнями). Нумерация не хранится: части — римские,
главы — сквозные арабские, считаются при выводе по порядку видимых разделов. Поэтому
переименование и перемещение не ломают нумерацию.
- `library_items` — карточка: title, author, edition (издание/год, текст), language, annotation,
tags text[], link_url, файл (file_name, file_type, file_size, file_data bytea), file_access
(`public|closed`), rights_basis (`own|licensed|public_domain`), status (`draft|published`).
- `library_item_sections(item_id, section_id)` — связи по id раздела: переименование, перемещение
и скрытие раздела их не меняют. Разделы не удаляются (только скрываются) — связи не теряются.
- `library_editor_sessions(token_hash, csrf, expires_at)` — сессии редактора (SHA-256 токена, 12 ч).
- Начальное оглавление — INSERT в миграции с фиксированными UUID (идемпотентно для одного прогона
миграций; повторно миграция не выполняется).
## Доступ
- Редактор: пароль из env `LIBRARY_EDITOR_PASSWORD` (сравнение SHA-256 + timingSafeEqual,
rate-limit 5 попыток / 15 мин на IP), cookie `lib_sid` (HttpOnly, SameSite=Strict, Path=/library,
Secure в production). Каждая форма несёт CSRF-токен сессии, плюс проверка Origin. Без пароля в env
редактор отвечает «редактор не настроен», каталог работает.
- Гость: видит только опубликованные материалы и видимые разделы (раздел скрыт, если скрыт он или
предок). Карточка черновика и файл черновика → 404 (как несуществующие). Закрытый файл без входа →
403 со страницей «войдите». Вошедший пользователь — по cookie `sid` модуля accounts.
Владелица в редакторе видит и черновики, и скачивает любые файлы.
- Файлы: только PDF (`%PDF-`) и EPUB (zip с `mimetype` = `application/epub+zip`), до 20 МБ, с
обязательным основанием прав. Отдача — `attachment`, `no-store` для закрытых. Опубликовать карточку
можно только с ссылкой (http/https) или файлом.
## HTTP
- Формы редактора — обычные HTML-формы (CSP `script-src 'self'`, без JS). Парсеры
`application/x-www-form-urlencoded` и `multipart/form-data` (свой, без зависимостей) регистрируются
внутри плагина library (без skip-override), чтобы не менять поведение других модулей.
- Лимит тела: глобальный хук 413 учитывает `routeOptions.bodyLimit`; у маршрута загрузки файла — 21 МБ.
- Язык страниц: `?lang=ru|kk|en` запоминается в cookie `lib_lang`; по умолчанию ru. Тексты —
`src/modules/library/i18n/{ru,kk,en}.ts` (kk и en типизированы по ru).
- Поиск: `ILIKE` по title, author и тегам с экранированием `%`/`_`, только опубликованные.
## Модуль и окружение
- `src/modules/library`, регистрируется при наличии БД; `editorPassword` — опция (env).
- `deploy/compose.yml`: передаём `LIBRARY_EDITOR_PASSWORD` из secrets Actions (нужно для приёмки).

View File

@ -0,0 +1,27 @@
# CLT-12: Библиотека «Клиентология 360°» с обновляемым оглавлением
Цель: раздел сайта «Библиотека Клиентологии 360°» (вход с главной) — каталог книг и материалов,
разложенных по редактируемому оглавлению (части → главы → пункты). Владелица ведёт оглавление и
карточки материалов в защищённом веб-редакторе; всё хранится в БД, без правок кода.
## Что делаем
- Модуль `library`: таблицы оглавления, материалов и связей «материал ↔ раздел» (миграция 0009) с
начальным оглавлением из 4 частей, 14 глав и их пунктов.
- Публичный каталог `/library`: раскрываемое оглавление, поиск по названию, автору и тегам,
карточка материала, скачивание разрешённого файла. Ссылка на раздел с главной.
- Редактор `/library/editor` за паролем владелицы (`LIBRARY_EDITOR_PASSWORD`): добавить,
переименовать, переместить (вверх/вниз, в другой раздел), скрыть и восстановить раздел любого
уровня; создать и править карточку материала (название, автор, издание/год, язык, аннотация,
теги, ссылка на легальный источник или загруженный файл PDF/EPUB с основанием прав, несколько
разделов, статус черновик/опубликовано).
- Защита: черновики, скрытые разделы и закрытые файлы недоступны гостю, в том числе по прямой ссылке.
- Тексты страниц — в файлах переводов (ru, kk, en), словарь `docs/glossary.md`.
## Вне scope
- Оплата доступа, написание книг, отзывы и рейтинги, полнотекстовый поиск по содержимому файлов.
- Несколько редакторов с разными правами (один пароль владелицы).
## Решения без PM
- «Пользователь сам добавляет книги» — книги в каталог добавляет владелица через редактор;
начальных книг нет, только оглавление.
- «Закрытый файл» — файл, доступный только вошедшим пользователям сайта и владелице; гостю — отказ.

View File

@ -0,0 +1,121 @@
## ADDED Requirements
### Requirement: Вход в библиотеку с главной
Главная страница SHALL содержать ссылку «Библиотека Клиентологии 360°» на `/library`.
#### Scenario: Ссылка на главной
- **GIVEN** сервис запущен с БД
- **WHEN** посетитель открывает `/`
- **THEN** на странице есть ссылка «Библиотека Клиентологии 360°» на `/library`
#### Scenario: Библиотека без БД
- **GIVEN** сервис запущен без БД
- **WHEN** посетитель открывает `/library`
- **THEN** ответ — статус 404
### Requirement: Начальное оглавление
После миграций библиотека SHALL содержать 4 части, 14 глав и пункты из текста после тире. Части SHALL нумероваться римскими цифрами, главы — сквозными арабскими, по текущему порядку.
#### Scenario: Оглавление в каталоге
- **GIVEN** применены миграции
- **WHEN** гость открывает `/library`
- **THEN** видны «I. Понять клиента и спроектировать сервис» и «3. Дизайн-мышление и путь клиента»
- **AND** у главы 3 есть пункт «Service blueprint»
- **AND** видна «14. Отраслевые кейсы»
#### Scenario: Нумерация после перемещения
- **GIVEN** глава «Отраслевые кейсы» перемещена в начало части I
- **WHEN** гость открывает `/library`
- **THEN** она показана как «1. Отраслевые кейсы», а «Основы клиентологии» — как «2.»
### Requirement: Вход в редактор
Редактор `/library/editor` SHALL быть доступен только после ввода пароля владелицы (`LIBRARY_EDITOR_PASSWORD`). Изменения SHALL требовать CSRF-токен сессии. После 5 неверных попыток за 15 минут вход SHALL блокироваться.
#### Scenario: Верный пароль
- **GIVEN** задан пароль редактора «mock-owner-pass»
- **WHEN** владелица вводит «mock-owner-pass» на странице входа
- **THEN** открывается редактор с оглавлением
#### Scenario: Без входа
- **WHEN** гость открывает `/library/editor` или отправляет форму изменения
- **THEN** показывается страница входа (форма — статус 401), данные не меняются
#### Scenario: Неверный пароль и подбор
- **GIVEN** 5 неверных попыток подряд
- **WHEN** вводится верный пароль
- **THEN** ответ — статус 429 и страница «Слишком много попыток»
#### Scenario: Форма без CSRF-токена
- **GIVEN** владелица вошла
- **WHEN** форма переименования приходит без CSRF-токена
- **THEN** ответ — статус 403, название не меняется
### Requirement: Редактирование оглавления
Владелица SHALL добавлять, переименовывать, перемещать (вверх, вниз, в другой раздел), скрывать и восстанавливать части, главы и пункты любого уровня (до 5). Раздел SHALL NOT перемещаться в себя или в свой вложенный раздел. Изменения сохраняются в БД; связи материалов с разделами SHALL сохраняться.
#### Scenario: Добавление и перемещение подпункта
- **GIVEN** владелица вошла
- **WHEN** она добавляет пункт «Карта эмоций» к главе «Дизайн-мышление и путь клиента», переименовывает его в «Карта эмоций клиента» и переносит в главу «Внедрение и развитие»
- **THEN** после перезагрузки «Карта эмоций клиента» видна в главе «Внедрение и развитие»
#### Scenario: Скрытие и восстановление
- **GIVEN** глава «Отраслевые кейсы» скрыта
- **WHEN** гость открывает `/library`
- **THEN** главы нет в каталоге
- **AND** после восстановления она снова видна
#### Scenario: Перенос в собственный подпункт
- **WHEN** владелица переносит главу «Дизайн-мышление и путь клиента» в её же пункт «Прототип»
- **THEN** ответ — статус 422, структура не меняется
### Requirement: Карточка материала
Владелица SHALL создавать и править карточку: название (обязательно), автор, издание/год, язык, аннотация, теги, ссылка на легальный источник (http/https) или файл PDF/EPUB до 20 МБ с основанием прав (собственный, лицензия правообладателя, общественное достояние), доступ к файлу (всем / только вошедшим), несколько разделов, статус «черновик» или «опубликовано». Опубликовать карточку без ссылки и без файла SHALL NOT быть возможно.
#### Scenario: Материал в двух разделах
- **GIVEN** владелица вошла
- **WHEN** она создаёт карточку «Service Design Doing» с ссылкой на сайт издателя, разделами «Карта эмоций» и «Внедрение и развитие» и публикует её
- **THEN** карточка видна в каталоге в обоих разделах
- **AND** после переименования и перемещения раздела «Карта эмоций» связи сохраняются
#### Scenario: Публикация без источника
- **WHEN** владелица публикует карточку без ссылки и без файла
- **THEN** ответ — статус 422 и текст «Добавьте ссылку на источник или файл», статус остаётся «черновик»
#### Scenario: Файл не PDF и не EPUB
- **WHEN** владелица загружает файл «book.pdf», содержимое которого не PDF
- **THEN** ответ — статус 422, файл не сохраняется
#### Scenario: Файл без основания прав
- **WHEN** владелица загружает PDF, не выбрав основание прав
- **THEN** ответ — статус 422, файл не сохраняется
### Requirement: Каталог и поиск
`/library` SHALL показывать раскрываемое оглавление видимых разделов с опубликованными материалами; `/library?q=` SHALL искать опубликованные материалы по названию, автору и тегам без учёта регистра.
#### Scenario: Поиск по автору и тегу
- **GIVEN** опубликована карточка «Service Design Doing», автор «Stickdorn», тег «blueprint», и черновик «Секретный черновик» с тем же тегом
- **WHEN** гость ищет «stickdorn» или «BLUEPRINT»
- **THEN** найдена только «Service Design Doing»
#### Scenario: Ничего не найдено
- **WHEN** гость ищет «%»
- **THEN** показано «Ничего не нашлось»
### Requirement: Защита черновиков и закрытых файлов
Черновик и его файл SHALL отдавать гостю 404 даже по прямой ссылке. Закрытый файл опубликованной карточки SHALL отдаваться только вошедшему пользователю или владелице; гостю — 403 со страницей «войдите».
#### Scenario: Прямая ссылка на черновик
- **GIVEN** черновик с файлом
- **WHEN** гость открывает `/library/items/<id>` или `/library/items/<id>/file`
- **THEN** ответ — статус 404
#### Scenario: Закрытый файл
- **GIVEN** опубликованная карточка с закрытым PDF
- **WHEN** гость открывает `/library/items/<id>/file`
- **THEN** ответ — статус 403
- **AND** вошедший пользователь и владелица получают файл (200, `application/pdf`)
#### Scenario: Открытый файл
- **GIVEN** опубликованная карточка с открытым EPUB
- **WHEN** гость открывает `/library/items/<id>/file`
- **THEN** ответ — статус 200, `application/epub+zip`, `content-disposition: attachment`

View File

@ -0,0 +1,11 @@
## 1. Данные
- [ ] 1.1 Миграция 0009_library.sql с начальным оглавлением
## 2. Модуль library
- [ ] 2.1 Переводы ru/kk/en, словарь docs/glossary.md
- [ ] 2.2 Каталог: оглавление, поиск, карточка, файлы с проверкой доступа; ссылка с главной
- [ ] 2.3 Редактор: вход, разделы (добавить/переименовать/переместить/скрыть/восстановить)
- [ ] 2.4 Редактор: карточки материалов, разделы, файл, статусы
- [ ] 2.5 Регистрация в buildApp/index, compose, лимит тела по маршруту
## 3. Тесты и завершение
- [ ] 3.1 Тесты по сценариям
- [ ] 3.2 Проверки, память, archive, PR

View File

@ -11,6 +11,7 @@ import { hrModule, type HrOptions } from "./modules/hr/index.ts";
import { contentModule, type ContentOptions } from "./modules/content/index.ts"; import { contentModule, type ContentOptions } from "./modules/content/index.ts";
import { kitsModule, type KitsOptions } from "./modules/kits/index.ts"; import { kitsModule, type KitsOptions } from "./modules/kits/index.ts";
import { trainerModule, type TrainerOptions } from "./modules/trainer/index.ts"; import { trainerModule, type TrainerOptions } from "./modules/trainer/index.ts";
import { libraryModule, type LibraryOptions } from "./modules/library/index.ts";
export const BODY_LIMIT = 1024 * 1024; export const BODY_LIMIT = 1024 * 1024;
@ -34,6 +35,8 @@ export interface AppOptions {
hr?: Omit<HrOptions, "db">; hr?: Omit<HrOptions, "db">;
/** Контент-агент (блог, Telegram); нужны БД, baseUrl и adminToken. */ /** Контент-агент (блог, Telegram); нужны БД, baseUrl и adminToken. */
content?: Omit<ContentOptions, "db">; content?: Omit<ContentOptions, "db">;
/** Библиотека 360°; нужна БД, редактор — при заданном пароле. */
library?: Omit<LibraryOptions, "db">;
} }
const CLIENT_ERROR_CODES: Record<number, string> = { const CLIENT_ERROR_CODES: Record<number, string> = {
@ -73,7 +76,9 @@ export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance>
// Тело больше лимита отклоняем до маршрутизации — и для несуществующих маршрутов тоже. // Тело больше лимита отклоняем до маршрутизации — и для несуществующих маршрутов тоже.
app.addHook("onRequest", async (req, reply) => { app.addHook("onRequest", async (req, reply) => {
const len = Number(req.headers["content-length"] ?? 0); const len = Number(req.headers["content-length"] ?? 0);
if (Number.isFinite(len) && len > BODY_LIMIT) { // Маршрут может поднять лимит (загрузка файлов библиотеки); для неизвестных — общий.
const limit = req.routeOptions.bodyLimit ?? BODY_LIMIT;
if (Number.isFinite(len) && len > limit) {
return reply.code(413).send({ error: "payload_too_large" }); return reply.code(413).send({ error: "payload_too_large" });
} }
}); });
@ -104,6 +109,7 @@ export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance>
if (opts.trainer && app.uploads) await app.register(trainerModule, { now: opts.accounts?.now, ...opts.trainer, db: opts.db }); if (opts.trainer && app.uploads) await app.register(trainerModule, { now: opts.accounts?.now, ...opts.trainer, db: opts.db });
if (opts.content) await app.register(contentModule, { now: opts.accounts?.now, ...opts.content, db: opts.db }); if (opts.content) await app.register(contentModule, { now: opts.accounts?.now, ...opts.content, db: opts.db });
if (opts.hr) await app.register(hrModule, { now: opts.accounts?.now, ...opts.hr, db: opts.db }); if (opts.hr) await app.register(hrModule, { now: opts.accounts?.now, ...opts.hr, db: opts.db });
await app.register(libraryModule, { now: opts.accounts?.now, secureCookie: opts.accounts?.secureCookie, ...opts.library, db: opts.db });
} }
return app; return app;

View File

@ -60,6 +60,7 @@ async function main(): Promise<void> {
} }
: undefined, : undefined,
hr: fontPath ? { fontData: readFileSync(fontPath) } : undefined, hr: fontPath ? { fontData: readFileSync(fontPath) } : undefined,
library: { editorPassword: process.env.LIBRARY_EDITOR_PASSWORD || undefined },
logger: { logger: {
level: process.env.LOG_LEVEL ?? "info", level: process.env.LOG_LEVEL ?? "info",
// В логах — только метод и путь: без IP клиента, query и заголовков (ПДн). // В логах — только метод и путь: без IP клиента, query и заголовков (ПДн).

View File

@ -1,6 +1,7 @@
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
import { escapeHtml } from "../../html.ts"; import { escapeHtml } from "../../html.ts";
import { PRODUCTS, type Product } from "./products.ts"; import { PRODUCTS, type Product } from "./products.ts";
import { ru as libraryText } from "../library/i18n/ru.ts";
export interface CatalogOptions { export interface CatalogOptions {
products?: readonly Product[]; products?: readonly Product[];
@ -47,6 +48,7 @@ export function renderLanding(products: readonly Product[]): string {
<main> <main>
<h1>Клиентология</h1> <h1>Клиентология</h1>
<p class="lead">Инструменты для контакт-центров и отделов продаж по методологии «Клиентологии»: цифровые комплекты, автоматические аудиты, тренажёры и тестирование кандидатов.</p> <p class="lead">Инструменты для контакт-центров и отделов продаж по методологии «Клиентологии»: цифровые комплекты, автоматические аудиты, тренажёры и тестирование кандидатов.</p>
<p class="lead"><a href="/library">${escapeHtml(libraryText.title)}</a> — ${escapeHtml(libraryText.landingTeaser)}</p>
<ul class="grid"> <ul class="grid">
${products.map(renderCard).join("\n")} ${products.map(renderCard).join("\n")}
</ul> </ul>

View File

@ -0,0 +1,70 @@
/** Поля HTML-формы: повторяющиеся имена собираются в массив. */
export type FormFields = Record<string, string | string[]>;
export function parseUrlEncoded(body: string): FormFields {
const out: FormFields = {};
for (const [k, v] of new URLSearchParams(body)) add(out, k, v);
return out;
}
function add(out: FormFields, k: string, v: string): void {
const cur = out[k];
if (cur === undefined) out[k] = v;
else out[k] = Array.isArray(cur) ? [...cur, v] : [cur, v];
}
export const one = (f: FormFields, k: string): string => {
const v = f[k];
return (Array.isArray(v) ? v[0] : v) ?? "";
};
export const many = (f: FormFields, k: string): string[] => {
const v = f[k];
return v === undefined ? [] : Array.isArray(v) ? v : [v];
};
export interface UploadedFile {
filename: string;
contentType: string;
data: Buffer;
}
export interface Multipart {
fields: FormFields;
files: Record<string, UploadedFile>;
}
/** Граница из заголовка Content-Type; null — не multipart. */
export function multipartBoundary(contentType: string | undefined): string | null {
const m = /^multipart\/form-data\s*;.*?boundary=(?:"([^"]{1,70})"|([^\s;]{1,70}))/i.exec(contentType ?? "");
return m ? (m[1] ?? m[2] ?? null) : null;
}
/** Разбор multipart/form-data (RFC 7578) без зависимостей; при битом теле — null. */
export function parseMultipart(body: Buffer, boundary: string): Multipart | null {
const delim = Buffer.from(`--${boundary}`);
const out: Multipart = { fields: {}, files: {} };
let pos = body.indexOf(delim);
if (pos !== 0) return null;
for (;;) {
pos += delim.length;
if (body.subarray(pos, pos + 2).toString() === "--") return out;
if (body.subarray(pos, pos + 2).toString() !== "\r\n") return null;
pos += 2;
const headEnd = body.indexOf("\r\n\r\n", pos);
if (headEnd < 0) return null;
const headers = body.subarray(pos, headEnd).toString("utf8");
const next = body.indexOf(Buffer.concat([Buffer.from("\r\n"), delim]), headEnd + 4);
if (next < 0) return null;
const data = body.subarray(headEnd + 4, next);
const disp = /content-disposition:\s*form-data\s*;([^\r\n]*)/i.exec(headers)?.[1] ?? "";
const name = /\bname="([^"]*)"/i.exec(disp)?.[1];
const filename = /\bfilename="([^"]*)"/i.exec(disp)?.[1];
if (name === undefined) return null;
if (filename !== undefined) {
const contentType = /content-type:\s*([^\r\n;]+)/i.exec(headers)?.[1]?.trim() ?? "application/octet-stream";
if (filename !== "" || data.length > 0) out.files[name] = { filename, contentType, data: Buffer.from(data) };
} else {
add(out.fields, name, data.toString("utf8"));
}
pos = next + 2;
}
}

View File

@ -0,0 +1,95 @@
import type { Dict } from "./ru.ts";
export const en: Dict = {
htmlLang: "en",
siteName: "Clientology",
title: "Clientology 360° Library",
lead: "Books and materials on customer service, arranged by the chapters of the methodology. Open a section or find a material by title, author or topic.",
landingTeaser: "books and materials by the chapters of the methodology.",
home: "Home",
languages: "Page language",
searchLabel: "Search by title, author and topics",
searchButton: "Search",
searchResults: "Found for “{q}”",
nothingFound: "Nothing found. Try another word or open the table of contents.",
tocHeading: "Table of contents",
allLibrary: "Whole library",
author: "Author",
edition: "Edition, year",
language: "Language",
tags: "Topics",
sections: "Sections",
annotation: "Summary",
openLink: "Open at the source",
download: "Download file",
closedFileNote: "The file is available after you sign in.",
draftNote: "Draft: only you can see this card.",
notFoundTitle: "Material not found",
notFoundText: "This material does not exist or is not published yet. Go back to the library and choose another one.",
forbiddenTitle: "Sign-in required",
forbiddenText: "This file is available to Clientology members only. Sign in to your account and open the link again.",
editorTitle: "Library editor",
editorLead: "Here you change the table of contents and material cards. Changes appear in the library right away; only you see drafts.",
loginTitle: "Sign in to the library editor",
loginLead: "Enter the editor password to change the table of contents and materials. The editor opens after you sign in.",
password: "Password",
loginButton: "Sign in",
logout: "Sign out",
openCatalog: "Open the library",
wrongPassword: "The password did not match. Check the keyboard layout and enter it again.",
tooManyAttempts: "Too many sign-in attempts. Wait 15 minutes and try again.",
editorOff: "The editor is not enabled yet. Ask the person who sets up the site to set the editor password.",
staleForm: "The page is out of date. Refresh it and repeat the action.",
saved: "Saved.",
addPart: "Add a part",
addChild: "Add an item",
newTitle: "Title",
rename: "Rename",
up: "Up",
down: "Down",
hide: "Hide",
restore: "Restore",
hiddenMark: "hidden",
actions: "Actions",
moveHeading: "Move a section",
moveWhat: "Which section",
moveWhere: "Where to",
moveButton: "Move",
topLevel: "To the top (as a part)",
materialsHeading: "Materials",
newMaterial: "Add a material",
noMaterials: "No materials yet. Add the first one — it will appear in the chosen sections.",
edit: "Edit",
backToEditor: "Back to the editor",
preview: "Open the card",
status: "Status",
statusDraft: "Draft",
statusPublished: "Published",
fieldTitle: "Title",
fieldTags: "Topics, comma-separated",
fieldLink: "Link to a legal source",
fieldAccess: "Who can download the file",
accessPublic: "All visitors",
accessClosed: "Signed-in users only",
fieldRights: "Why you may publish this file",
rightsOwn: "This is my own material",
rightsLicensed: "I have the rights holder's permission",
rightsPublicDomain: "Public domain",
fieldFile: "File: PDF or EPUB, up to 20 MB",
upload: "Upload file",
removeFile: "Remove file",
currentFile: "Uploaded now: {name}, {size} KB",
save: "Save",
fileHeading: "File",
errTitle: "The title is missing. Enter a title and save again.",
errTooLong: "The text is too long. Shorten it and save again.",
errLink: "The link does not look like a web address. Paste the full address starting with https://.",
errNeedSource: "A material cannot be published without a source. Add a link to the source or a file.",
errFileType: "This file is not suitable. Upload a PDF or EPUB.",
errFileSize: "The file is too large or empty. Upload a file up to 20 MB.",
errRights: "You did not say why the file may be published. Choose a reason and upload the file again.",
errCycle: "A section cannot be moved inside itself. Choose another place.",
errDepth: "The nesting would be too deep. Choose a section one level higher.",
errNotFound: "The section or material was not found. Refresh the page and try again.",
};

View File

@ -0,0 +1,13 @@
import { en } from "./en.ts";
import { kk } from "./kk.ts";
import { ru, type Dict } from "./ru.ts";
export type { Dict };
export const LANGS = { ru, kk, en } as const;
export type Lang = keyof typeof LANGS;
export const LANG_NAMES: Record<Lang, string> = { ru: "Русский", kk: "Қазақша", en: "English" };
export const isLang = (v: unknown): v is Lang => typeof v === "string" && Object.hasOwn(LANGS, v);
/** Подставляет {ключ} в строку перевода. */
export const fmt = (s: string, vars: Record<string, string | number>): string =>
s.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));

View File

@ -0,0 +1,95 @@
import type { Dict } from "./ru.ts";
export const kk: Dict = {
htmlLang: "kk",
siteName: "Клиентология",
title: "Клиентология 360° кітапханасы",
lead: "Клиенттерге қызмет көрсету туралы кітаптар мен материалдар әдістеменің тараулары бойынша жинақталған. Бөлімді ашыңыз немесе материалды атауы, авторы не тақырыбы бойынша табыңыз.",
landingTeaser: "әдістеме тараулары бойынша кітаптар мен материалдар.",
home: "Басты бетке",
languages: "Бет тілі",
searchLabel: "Атауы, авторы және тақырыбы бойынша іздеу",
searchButton: "Табу",
searchResults: "«{q}» сұрауы бойынша табылды",
nothingFound: "Ештеңе табылмады. Басқа сөзбен іздеп көріңіз немесе мазмұнды ашыңыз.",
tocHeading: "Мазмұны",
allLibrary: "Бүкіл кітапхана",
author: "Авторы",
edition: "Басылымы, жылы",
language: "Тілі",
tags: "Тақырыптар",
sections: "Бөлімдер",
annotation: "Аннотация",
openLink: "Дереккөзде ашу",
download: "Файлды жүктеп алу",
closedFileNote: "Файл аккаунтқа кіргеннен кейін қолжетімді.",
draftNote: "Жоба: бұл карточканы тек сіз көресіз.",
notFoundTitle: "Материал табылмады",
notFoundText: "Мұндай материал жоқ немесе әлі жарияланбаған. Кітапханаға оралып, басқасын таңдаңыз.",
forbiddenTitle: "Кіру қажет",
forbiddenText: "Бұл файл тек «Клиентология» қатысушыларына қолжетімді. Аккаунтыңызға кіріп, сілтемені қайта ашыңыз.",
editorTitle: "Кітапхана редакторы",
editorLead: "Мұнда сіз мазмұн мен материал карточкаларын өзгертесіз. Өзгерістер кітапханада бірден көрінеді, ал жобаларды тек сіз көресіз.",
loginTitle: "Кітапхана редакторына кіру",
loginLead: "Мазмұн мен материалдарды өзгерту үшін редактор құпиясөзін енгізіңіз. Кіргеннен кейін редактор ашылады.",
password: "Құпиясөз",
loginButton: "Кіру",
logout: "Шығу",
openCatalog: "Кітапхананы ашу",
wrongPassword: "Құпиясөз сәйкес келмеді. Пернетақта тілін тексеріп, қайта енгізіңіз.",
tooManyAttempts: "Кіру әрекеттері тым көп. 15 минут күтіп, қайта көріңіз.",
editorOff: "Редактор әлі қосылмаған. Сайтты баптайтын адамнан редактор құпиясөзін орнатуды сұраңыз.",
staleForm: "Бет ескірді. Оны жаңартып, әрекетті қайталаңыз.",
saved: "Сақталды.",
addPart: "Бөлік қосу",
addChild: "Тармақ қосу",
newTitle: "Атауы",
rename: "Атын өзгерту",
up: "Жоғары",
down: "Төмен",
hide: "Жасыру",
restore: "Қайтару",
hiddenMark: "жасырылған",
actions: "Әрекеттер",
moveHeading: "Бөлімді көшіру",
moveWhat: "Қай бөлім",
moveWhere: "Қайда",
moveButton: "Көшіру",
topLevel: "Ең жоғарыға (бөлік ретінде)",
materialsHeading: "Материалдар",
newMaterial: "Материал қосу",
noMaterials: "Әзірге материал жоқ. Біріншісін қосыңыз — ол таңдалған бөлімдерде пайда болады.",
edit: "Өзгерту",
backToEditor: "Редакторға оралу",
preview: "Карточканы ашу",
status: "Күйі",
statusDraft: "Жоба",
statusPublished: "Жарияланды",
fieldTitle: "Атауы",
fieldTags: "Тақырыптар үтір арқылы",
fieldLink: "Заңды дереккөзге сілтеме",
fieldAccess: "Файлды кім жүктей алады",
accessPublic: "Барлық келушілер",
accessClosed: "Тек аккаунтқа кіргендер",
fieldRights: "Бұл файлды неліктен жариялай аласыз",
rightsOwn: "Бұл менің материалым",
rightsLicensed: "Құқық иесінің рұқсаты бар",
rightsPublicDomain: "Қоғамдық игілік",
fieldFile: "Файл: PDF немесе EPUB, 20 МБ дейін",
upload: "Файлды жүктеу",
removeFile: "Файлды алып тастау",
currentFile: "Қазір жүктелген: {name}, {size} КБ",
save: "Сақтау",
fileHeading: "Файл",
errTitle: "Атауы көрсетілмеген. Атауын жазып, қайта сақтаңыз.",
errTooLong: "Мәтін тым ұзын. Оны қысқартып, қайта сақтаңыз.",
errLink: "Сілтеме сайт мекенжайына ұқсамайды. https:// деп басталатын толық мекенжайды қойыңыз.",
errNeedSource: "Дереккөзсіз жариялауға болмайды. Дереккөзге сілтеме немесе файл қосыңыз.",
errFileType: "Файл сәйкес емес. PDF немесе EPUB жүктеңіз.",
errFileSize: "Файл тым үлкен немесе бос. 20 МБ дейінгі файлды жүктеңіз.",
errRights: "Файлды неліктен жариялауға болатыны көрсетілмеген. Негізін таңдап, файлды қайта жүктеңіз.",
errCycle: "Бөлімді өзінің ішіне көшіруге болмайды. Басқа орынды таңдаңыз.",
errDepth: "Ендіру тым терең болады. Бір деңгей жоғары бөлімді таңдаңыз.",
errNotFound: "Бөлім немесе материал табылмады. Бетті жаңартып, қайта көріңіз.",
};

View File

@ -0,0 +1,96 @@
/** Тексты библиотеки (CLT-12). kk.ts и en.ts повторяют ключи; новые слова — сначала в docs/glossary.md. */
export const ru = {
htmlLang: "ru",
siteName: "Клиентология",
title: "Библиотека Клиентологии 360°",
lead: "Книги и материалы по клиентскому сервису, разложенные по главам методологии. Раскройте раздел или найдите материал по названию, автору или теме.",
landingTeaser: "книги и материалы по главам методологии.",
home: "На главную",
languages: "Язык страницы",
searchLabel: "Поиск по названию, автору и темам",
searchButton: "Найти",
searchResults: "Найдено по запросу «{q}»",
nothingFound: "Ничего не нашлось. Попробуйте другое слово или откройте оглавление.",
tocHeading: "Оглавление",
allLibrary: "Вся библиотека",
author: "Автор",
edition: "Издание, год",
language: "Язык",
tags: "Темы",
sections: "Разделы",
annotation: "Аннотация",
openLink: "Открыть у источника",
download: "Скачать файл",
closedFileNote: "Файл доступен после входа в аккаунт.",
draftNote: "Черновик: эту карточку видите только вы.",
notFoundTitle: "Материал не найден",
notFoundText: "Такого материала нет или он ещё не опубликован. Вернитесь в библиотеку и выберите другой.",
forbiddenTitle: "Нужен вход",
forbiddenText: "Этот файл доступен только участникам «Клиентологии». Войдите в аккаунт и откройте ссылку ещё раз.",
editorTitle: "Редактор библиотеки",
editorLead: "Здесь вы меняете оглавление и карточки материалов. Изменения сразу видны в библиотеке, а черновики видите только вы.",
loginTitle: "Вход в редактор библиотеки",
loginLead: "Введите пароль редактора, чтобы менять оглавление и материалы. После входа откроется редактор.",
password: "Пароль",
loginButton: "Войти",
logout: "Выйти",
openCatalog: "Открыть библиотеку",
wrongPassword: "Пароль не подошёл. Проверьте раскладку и введите его ещё раз.",
tooManyAttempts: "Слишком много попыток входа. Подождите 15 минут и попробуйте снова.",
editorOff: "Редактор пока не включён. Попросите того, кто настраивает сайт, задать пароль редактора.",
staleForm: "Страница устарела. Обновите её и повторите действие.",
saved: "Сохранено.",
addPart: "Добавить часть",
addChild: "Добавить пункт",
newTitle: "Название",
rename: "Переименовать",
up: "Выше",
down: "Ниже",
hide: "Скрыть",
restore: "Вернуть",
hiddenMark: "скрыто",
actions: "Действия",
moveHeading: "Перенести раздел",
moveWhat: "Какой раздел",
moveWhere: "Куда",
moveButton: "Перенести",
topLevel: "В самый верх (как часть)",
materialsHeading: "Материалы",
newMaterial: "Добавить материал",
noMaterials: "Материалов пока нет. Добавьте первый — он появится в выбранных разделах.",
edit: "Изменить",
backToEditor: "Назад в редактор",
preview: "Открыть карточку",
status: "Статус",
statusDraft: "Черновик",
statusPublished: "Опубликовано",
fieldTitle: "Название",
fieldTags: "Темы через запятую",
fieldLink: "Ссылка на легальный источник",
fieldAccess: "Кто может скачать файл",
accessPublic: "Все посетители",
accessClosed: "Только вошедшие в аккаунт",
fieldRights: "Почему вы можете выложить этот файл",
rightsOwn: "Это мой материал",
rightsLicensed: "Есть разрешение правообладателя",
rightsPublicDomain: "Общественное достояние",
fieldFile: "Файл: PDF или EPUB, до 20 МБ",
upload: "Загрузить файл",
removeFile: "Убрать файл",
currentFile: "Сейчас загружен: {name}, {size} КБ",
save: "Сохранить",
fileHeading: "Файл",
errTitle: "Не указано название. Впишите название и сохраните ещё раз.",
errTooLong: "Текст слишком длинный. Сократите его и сохраните ещё раз.",
errLink: "Ссылка не похожа на адрес сайта. Вставьте полный адрес, начиная с https://.",
errNeedSource: "Без источника опубликовать нельзя. Добавьте ссылку на источник или файл.",
errFileType: "Файл не подходит. Загрузите PDF или EPUB.",
errFileSize: "Файл слишком большой или пустой. Загрузите файл до 20 МБ.",
errRights: "Не указано, почему файл можно выложить. Выберите основание и загрузите файл ещё раз.",
errCycle: "Раздел нельзя перенести внутрь самого себя. Выберите другое место.",
errDepth: "Получается слишком глубокая вложенность. Выберите раздел уровнем выше.",
errNotFound: "Раздел или материал не найден. Обновите страницу и попробуйте снова.",
};
export type Dict = typeof ru;

View File

@ -0,0 +1,494 @@
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import type { Db, TxDb } from "../../db/db.ts";
import { loadSessionUser } from "../accounts/index.ts";
import { RateLimiter } from "../accounts/rate-limit.ts";
import { many, multipartBoundary, one, parseMultipart, parseUrlEncoded, type FormFields } from "./forms.ts";
import { isLang, LANGS, type Dict, type Lang } from "./i18n/index.ts";
import { LIBRARY_CSS, renderCatalog, renderEditor, renderItem, renderItemForm, renderLogin, renderMessage, type ItemView } from "./page.ts";
import { buildTree, flatten, MAX_DEPTH, subtreeHeight, visibleOnly, type SectionNode, type SectionRow } from "./tree.ts";
export const MAX_FILE_BYTES = 20 * 1024 * 1024;
export const EDITOR_SESSION_TTL_MS = 12 * 60 * 60 * 1000;
const UPLOAD_BODY_LIMIT = MAX_FILE_BYTES + 1024 * 1024;
const COOKIE = "lib_sid";
const LANG_COOKIE = "lib_lang";
export interface LibraryOptions {
db: TxDb;
/** Пароль владелицы для редактора (LIBRARY_EDITOR_PASSWORD); без него редактор выключен. */
editorPassword?: string;
/** Secure-флаг cookie; по умолчанию — NODE_ENV=production. */
secureCookie?: boolean;
now?: () => number;
}
interface ItemRow {
id: string;
title: string;
author: string;
edition: string;
language: string;
annotation: string;
tags: string[];
link_url: string | null;
file_name: string | null;
file_type: string | null;
file_size: number | null;
file_access: "public" | "closed";
rights_basis: "own" | "licensed" | "public_domain" | null;
status: "draft" | "published";
section_ids: string[] | null;
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const RIGHTS = ["own", "licensed", "public_domain"] as const;
const sha = (s: string) => createHash("sha256").update(s).digest();
const ITEM_COLS = `i.id, i.title, i.author, i.edition, i.language, i.annotation, i.tags, i.link_url, i.file_name, i.file_type,
i.file_size, i.file_access, i.rights_basis, i.status,
ARRAY(SELECT s.section_id::text FROM library_item_sections s WHERE s.item_id = i.id) AS section_ids`;
const toView = (r: ItemRow): ItemView => ({
id: r.id,
title: r.title,
author: r.author,
edition: r.edition,
language: r.language,
annotation: r.annotation,
tags: r.tags ?? [],
linkUrl: r.link_url,
fileName: r.file_name,
fileSize: r.file_size,
fileAccess: r.file_access,
rightsBasis: r.rights_basis,
status: r.status,
sectionIds: r.section_ids ?? [],
});
function parseCookies(header: string | undefined): Record<string, string> {
const out: Record<string, string> = {};
for (const part of (header ?? "").split(";")) {
const i = part.indexOf("=");
if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim();
}
return out;
}
/** Тип файла по содержимому: только PDF и EPUB. */
export function sniffFile(data: Buffer): "application/pdf" | "application/epub+zip" | null {
if (data.length < 5) return null;
if (data.subarray(0, 5).toString("latin1") === "%PDF-") return "application/pdf";
if (data.length >= 58 && data.readUInt32LE(0) === 0x04034b50 && data.subarray(30, 58).toString("latin1") === "mimetypeapplication/epub+zip") return "application/epub+zip";
return null;
}
const safeName = (name: string): string =>
(name.split(/[\\/]/).pop() ?? "").replace(/[\p{Cc}"]/gu, "").trim().slice(0, 200) || "file";
const isHttpUrl = (s: string): boolean => {
try {
const u = new URL(s);
return (u.protocol === "https:" || u.protocol === "http:") && Boolean(u.hostname);
} catch {
return false;
}
};
type ItemFields = Omit<ItemView, "id" | "fileName" | "fileSize" | "rightsBasis">;
export async function libraryModule(app: FastifyInstance, opts: LibraryOptions): Promise<void> {
const { db } = opts;
const now = opts.now ?? Date.now;
const secure = opts.secureCookie ?? process.env.NODE_ENV === "production";
const passwordHash = opts.editorPassword ? sha(opts.editorPassword) : null;
const loginLimiter = new RateLimiter(5, undefined, now);
// Формы редактора; парсеры только внутри плагина — другие модули по-прежнему принимают лишь JSON.
app.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string" }, (_req, body, done) =>
done(null, parseUrlEncoded(body as string)),
);
app.addContentTypeParser("multipart/form-data", { parseAs: "buffer", bodyLimit: UPLOAD_BODY_LIMIT }, (req, body, done) => {
const boundary = multipartBoundary(req.headers["content-type"]);
const parsed = boundary ? parseMultipart(body as Buffer, boundary) : null;
if (!parsed) return done(Object.assign(new Error("bad multipart"), { statusCode: 400 }), undefined);
done(null, parsed);
});
// ---------- общие помощники ----------
function langOf(req: FastifyRequest, reply: FastifyReply): Lang {
const q = (req.query as Record<string, unknown> | undefined)?.lang;
if (isLang(q)) {
reply.header("set-cookie", `${LANG_COOKIE}=${q}; Path=/library; SameSite=Lax; Max-Age=31536000${secure ? "; Secure" : ""}`);
return q;
}
const c = parseCookies(req.headers.cookie)[LANG_COOKIE];
return isLang(c) ? c : "ru";
}
const html = (reply: FastifyReply, code: number, body: string) =>
reply.code(code).type("text/html; charset=utf-8").header("cache-control", "no-store").send(body);
async function sections(d: Db = db): Promise<SectionNode[]> {
return buildTree((await d.query<SectionRow>("SELECT id, parent_id, title, position, hidden FROM library_sections")).rows);
}
async function items(where: string, params: unknown[] = []): Promise<ItemView[]> {
const r = await db.query<ItemRow>(`SELECT ${ITEM_COLS} FROM library_items i ${where} ORDER BY lower(i.title), i.id`, params);
return r.rows.map(toView);
}
const findItem = async (id: string): Promise<ItemView | null> => (UUID_RE.test(id) ? ((await items("WHERE i.id = $1", [id]))[0] ?? null) : null);
// ---------- сессия редактора ----------
interface Editor { csrf: string }
async function editorSession(req: FastifyRequest): Promise<Editor | null> {
if (!passwordHash) return null;
const token = parseCookies(req.headers.cookie)[COOKIE];
if (!token) return null;
const r = await db.query<{ csrf_token: string }>("SELECT csrf_token FROM library_editor_sessions WHERE token_hash = $1 AND expires_at > $2", [
sha(token),
new Date(now()),
]);
return r.rows[0] ? { csrf: r.rows[0].csrf_token } : null;
}
const sameOrigin = (req: FastifyRequest): boolean => {
const origin = req.headers.origin;
if (origin === undefined || origin === "null") return origin === undefined;
try {
return new URL(origin).host === req.headers.host;
} catch {
return false;
}
};
/** Для форм редактора: сессия + CSRF + свой Origin. При отказе отвечает сам и возвращает null. */
async function guard(req: FastifyRequest, reply: FastifyReply): Promise<{ t: Dict; lang: Lang; csrf: string; form: FormFields } | null> {
const lang = langOf(req, reply);
const t = LANGS[lang];
const ed = await editorSession(req);
if (!ed) {
void html(reply, 401, renderLogin(t, lang, { disabled: !passwordHash }));
return null;
}
const body = req.body as FormFields | { fields: FormFields } | undefined;
const form = (body && "fields" in body && typeof body.fields === "object" && !Array.isArray(body.fields) ? body.fields : body) as FormFields | undefined;
const sent = form ? one(form, "csrf") : "";
if (!sameOrigin(req) || !sent || sent.length !== ed.csrf.length || !timingSafeEqual(Buffer.from(sent), Buffer.from(ed.csrf))) {
void html(reply, 403, renderMessage(t, lang, t.editorTitle, t.staleForm));
return null;
}
return { t, lang, csrf: ed.csrf, form: form as FormFields };
}
const back = (reply: FastifyReply, path: string) => reply.code(303).header("location", path).send();
// ---------- публичная часть ----------
app.get("/library/library.css", async (_req, reply) =>
reply.type("text/css; charset=utf-8").header("cache-control", "public, max-age=3600").send(LIBRARY_CSS),
);
app.get("/library", async (req, reply) => {
const lang = langOf(req, reply);
const t = LANGS[lang];
const tree = visibleOnly(await sections());
const published = await items("WHERE i.status = 'published'");
const raw = (req.query as Record<string, unknown>).q;
const q = typeof raw === "string" ? raw.trim().slice(0, 100) : "";
if (q) {
const needle = q.toLocaleLowerCase();
const has = (s: string) => s.toLocaleLowerCase().includes(needle);
const found = published.filter((i) => has(i.title) || has(i.author) || i.tags.some(has));
return html(reply, 200, renderCatalog(t, lang, tree, new Map(), { q, found }));
}
const bySection = new Map<string, ItemView[]>();
for (const i of published) for (const s of i.sectionIds) bySection.set(s, [...(bySection.get(s) ?? []), i]);
return html(reply, 200, renderCatalog(t, lang, tree, bySection));
});
app.get<{ Params: { id: string } }>("/library/items/:id", async (req, reply) => {
const lang = langOf(req, reply);
const t = LANGS[lang];
const item = await findItem(req.params.id);
const editor = item ? Boolean(await editorSession(req)) : false;
if (!item || (item.status !== "published" && !editor)) return html(reply, 404, renderMessage(t, lang, t.notFoundTitle, t.notFoundText));
const all = flatten(await sections());
const secs = all.filter((n) => item.sectionIds.includes(n.id) && (editor || !n.hidden));
return html(reply, 200, renderItem(t, lang, item, secs, { editor }));
});
app.get<{ Params: { id: string } }>("/library/items/:id/file", async (req, reply) => {
const lang = langOf(req, reply);
const t = LANGS[lang];
const item = await findItem(req.params.id);
const editor = item ? Boolean(await editorSession(req)) : false;
if (!item || !item.fileName || (item.status !== "published" && !editor)) return html(reply, 404, renderMessage(t, lang, t.notFoundTitle, t.notFoundText));
if (item.fileAccess === "closed" && !editor && !(await loadSessionUser(db, req, now))) {
return html(reply, 403, renderMessage(t, lang, t.forbiddenTitle, t.forbiddenText));
}
const r = await db.query<{ file_data: Buffer | Uint8Array; file_type: string; file_name: string }>(
"SELECT file_data, file_type, file_name FROM library_items WHERE id = $1",
[item.id],
);
const f = r.rows[0];
if (!f) return html(reply, 404, renderMessage(t, lang, t.notFoundTitle, t.notFoundText));
const ascii = f.file_name.replace(/[^\x20-\x7e]/g, "_").replace(/[\\"]/g, "_");
return reply
.type(f.file_type)
.header("content-disposition", `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(f.file_name)}`)
.header("cache-control", item.fileAccess === "closed" || item.status !== "published" ? "private, no-store" : "public, max-age=300")
.send(Buffer.from(f.file_data));
});
// ---------- редактор: вход ----------
async function editorPage(reply: FastifyReply, t: Dict, lang: Lang, csrf: string, code = 200, o: { error?: string; saved?: boolean } = {}) {
const all = await items("");
return html(reply, code, renderEditor(t, lang, csrf, await sections(), all, o));
}
app.get("/library/editor", async (req, reply) => {
const lang = langOf(req, reply);
const t = LANGS[lang];
const ed = await editorSession(req);
if (!ed) return html(reply, 200, renderLogin(t, lang, { disabled: !passwordHash }));
return editorPage(reply, t, lang, ed.csrf, 200, { saved: (req.query as Record<string, unknown>).saved === "1" });
});
app.post("/library/editor/login", async (req, reply) => {
const lang = langOf(req, reply);
const t = LANGS[lang];
if (!passwordHash) return html(reply, 404, renderLogin(t, lang, { disabled: true }));
if (!sameOrigin(req)) return html(reply, 403, renderMessage(t, lang, t.editorTitle, t.staleForm));
const key = req.ip;
if (loginLimiter.blocked(key)) return html(reply, 429, renderLogin(t, lang, { error: t.tooManyAttempts }));
const form = (req.body ?? {}) as FormFields;
const pw = typeof form === "object" ? one(form, "password") : "";
if (!pw || !timingSafeEqual(sha(pw), passwordHash)) {
loginLimiter.hit(key);
return html(reply, 401, renderLogin(t, lang, { error: t.wrongPassword }));
}
loginLimiter.reset(key);
const token = randomBytes(32).toString("base64url");
await db.query("DELETE FROM library_editor_sessions WHERE expires_at <= $1", [new Date(now())]);
await db.query("INSERT INTO library_editor_sessions (token_hash, csrf_token, expires_at) VALUES ($1, $2, $3)", [
sha(token),
randomBytes(24).toString("base64url"),
new Date(now() + EDITOR_SESSION_TTL_MS),
]);
reply.header("set-cookie", `${COOKIE}=${token}; Path=/library; HttpOnly; SameSite=Strict; Max-Age=${EDITOR_SESSION_TTL_MS / 1000}${secure ? "; Secure" : ""}`);
return back(reply, "/library/editor");
});
app.post("/library/editor/logout", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const token = parseCookies(req.headers.cookie)[COOKIE] ?? "";
await db.query("DELETE FROM library_editor_sessions WHERE token_hash = $1", [sha(token)]);
reply.header("set-cookie", `${COOKIE}=; Path=/library; HttpOnly; SameSite=Strict; Max-Age=0${secure ? "; Secure" : ""}`);
return back(reply, "/library");
});
// ---------- редактор: оглавление ----------
const titleOf = (f: FormFields): string | null => {
const s = one(f, "title").trim();
return s && s.length <= 200 ? s : null;
};
app.post("/library/editor/sections", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const title = titleOf(g.form);
const parent = one(g.form, "parent") || null;
if (!title) return editorPage(reply, g.t, g.lang, g.csrf, 422, { error: g.t.errTitle });
const all = flatten(await sections());
const p = parent ? all.find((n) => n.id === parent) : null;
if (parent && !p) return editorPage(reply, g.t, g.lang, g.csrf, 404, { error: g.t.errNotFound });
if (p && p.depth + 1 >= MAX_DEPTH) return editorPage(reply, g.t, g.lang, g.csrf, 422, { error: g.t.errDepth });
await db.query(
`INSERT INTO library_sections (id, parent_id, title, position)
VALUES ($1, $2, $3, (SELECT COALESCE(MAX(position) + 1, 0) FROM library_sections WHERE parent_id IS NOT DISTINCT FROM $2::uuid))`,
[randomUUID(), parent, title],
);
return back(reply, "/library/editor?saved=1");
});
/** Переставляет братьев по новому порядку ids (позиции 0..n). */
async function renumber(d: Db, ids: string[]): Promise<void> {
for (const [i, id] of ids.entries()) await d.query("UPDATE library_sections SET position = $2 WHERE id = $1", [id, i]);
}
const siblings = (all: SectionNode[], parentId: string | null) => all.filter((n) => n.parentId === parentId).map((n) => n.id);
app.post<{ Params: { id: string } }>("/library/editor/sections/:id", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const all = flatten(await sections());
const node = all.find((n) => n.id === req.params.id);
if (!node) return editorPage(reply, g.t, g.lang, g.csrf, 404, { error: g.t.errNotFound });
const action = one(g.form, "action");
if (action === "rename") {
const title = titleOf(g.form);
if (!title) return editorPage(reply, g.t, g.lang, g.csrf, 422, { error: g.t.errTitle });
await db.query("UPDATE library_sections SET title = $2 WHERE id = $1", [node.id, title]);
} else if (action === "hide" || action === "restore") {
await db.query("UPDATE library_sections SET hidden = $2 WHERE id = $1", [node.id, action === "hide"]);
} else if (action === "up" || action === "down") {
const ids = siblings(all, node.parentId);
const i = ids.indexOf(node.id);
const j = action === "up" ? i - 1 : i + 1;
if (j >= 0 && j < ids.length) {
[ids[i], ids[j]] = [ids[j] as string, ids[i] as string];
await db.tx((d) => renumber(d, ids));
}
} else {
return editorPage(reply, g.t, g.lang, g.csrf, 400, { error: g.t.staleForm });
}
return back(reply, "/library/editor?saved=1");
});
app.post("/library/editor/move", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const all = flatten(await sections());
const node = all.find((n) => n.id === one(g.form, "section"));
const parentId = one(g.form, "parent") || null;
const target = parentId ? all.find((n) => n.id === parentId) : null;
if (!node || (parentId && !target)) return editorPage(reply, g.t, g.lang, g.csrf, 404, { error: g.t.errNotFound });
if (target && flatten([node]).some((n) => n.id === target.id)) return editorPage(reply, g.t, g.lang, g.csrf, 422, { error: g.t.errCycle });
if ((target ? target.depth + 1 : 0) + subtreeHeight(node) > MAX_DEPTH) return editorPage(reply, g.t, g.lang, g.csrf, 422, { error: g.t.errDepth });
if (node.parentId !== parentId) {
await db.tx(async (d) => {
await d.query(
`UPDATE library_sections SET parent_id = $2,
position = (SELECT COALESCE(MAX(position) + 1, 0) FROM library_sections WHERE parent_id IS NOT DISTINCT FROM $2::uuid)
WHERE id = $1`,
[node.id, parentId],
);
await renumber(d, siblings(all, node.parentId).filter((id) => id !== node.id));
});
}
return back(reply, "/library/editor?saved=1");
});
/** До разбора большого тела: без сессии редактора — сразу 401. */
async function rejectGuests(req: FastifyRequest, reply: FastifyReply): Promise<void> {
if (await editorSession(req)) return;
const lang = langOf(req, reply);
await html(reply, 401, renderLogin(LANGS[lang], lang, { disabled: !passwordHash }));
}
// ---------- редактор: материалы ----------
async function itemForm(reply: FastifyReply, g: { t: Dict; lang: Lang; csrf: string }, item: ItemView | null, code = 200, o: { error?: string; saved?: boolean; values?: Partial<ItemView> } = {}) {
return html(reply, code, renderItemForm(g.t, g.lang, g.csrf, await sections(), item, o));
}
/** Проверка полей карточки; ошибка — текст для владелицы. */
async function readItem(t: Dict, f: FormFields, cur: ItemView | null): Promise<{ error: string; values: Partial<ItemView> } | { ok: ItemFields }> {
const s = (k: string) => one(f, k).trim();
const tags = [...new Set(s("tags").split(",").map((x) => x.trim()).filter(Boolean))];
const link = s("link");
const known = new Set(flatten(await sections()).map((n) => n.id));
const values: ItemFields = {
title: s("title"),
author: s("author"),
edition: s("edition"),
language: s("language"),
annotation: one(f, "annotation").trim(),
tags,
linkUrl: link || null,
fileAccess: s("access") === "closed" ? "closed" : "public",
status: s("status") === "published" ? "published" : "draft",
sectionIds: [...new Set(many(f, "sections"))].filter((id) => known.has(id)),
};
const fail = (error: string) => ({ error, values });
if (!values.title) return fail(t.errTitle);
if (values.title.length > 300 || values.author.length > 300 || values.edition.length > 200 || values.language.length > 60) return fail(t.errTooLong);
if (values.annotation.length > 5000 || tags.length > 30 || tags.some((x) => x.length > 60) || link.length > 2000) return fail(t.errTooLong);
if (link && !isHttpUrl(link)) return fail(t.errLink);
if (values.status === "published" && !values.linkUrl && !cur?.fileName) return fail(t.errNeedSource);
return { ok: values };
}
async function saveItem(id: string, v: ItemFields, isNew: boolean): Promise<void> {
await db.tx(async (d) => {
const params = [id, v.title, v.author, v.edition, v.language, v.annotation, v.tags, v.linkUrl, v.fileAccess, v.status, new Date(now())];
if (isNew) {
await d.query(
`INSERT INTO library_items (id, title, author, edition, language, annotation, tags, link_url, file_access, status, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
params,
);
} else {
await d.query(
`UPDATE library_items SET title=$2, author=$3, edition=$4, language=$5, annotation=$6, tags=$7, link_url=$8, file_access=$9, status=$10, updated_at=$11 WHERE id=$1`,
params,
);
}
await d.query("DELETE FROM library_item_sections WHERE item_id = $1", [id]);
for (const s of v.sectionIds) await d.query("INSERT INTO library_item_sections (item_id, section_id) VALUES ($1, $2)", [id, s]);
});
}
app.get("/library/editor/items/new", async (req, reply) => {
const lang = langOf(req, reply);
const ed = await editorSession(req);
if (!ed) return html(reply, 401, renderLogin(LANGS[lang], lang, { disabled: !passwordHash }));
return itemForm(reply, { t: LANGS[lang], lang, csrf: ed.csrf }, null);
});
app.post("/library/editor/items", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const r = await readItem(g.t, g.form, null);
if ("error" in r) return itemForm(reply, g, null, 422, { error: r.error, values: r.values });
const id = randomUUID();
await saveItem(id, r.ok, true);
return back(reply, `/library/editor/items/${id}?saved=1`);
});
app.get<{ Params: { id: string } }>("/library/editor/items/:id", async (req, reply) => {
const lang = langOf(req, reply);
const t = LANGS[lang];
const ed = await editorSession(req);
if (!ed) return html(reply, 401, renderLogin(t, lang, { disabled: !passwordHash }));
const item = await findItem(req.params.id);
if (!item) return html(reply, 404, renderMessage(t, lang, t.notFoundTitle, t.notFoundText));
return itemForm(reply, { t, lang, csrf: ed.csrf }, item, 200, { saved: (req.query as Record<string, unknown>).saved === "1" });
});
app.post<{ Params: { id: string } }>("/library/editor/items/:id", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const item = await findItem(req.params.id);
if (!item) return html(reply, 404, renderMessage(g.t, g.lang, g.t.notFoundTitle, g.t.notFoundText));
const r = await readItem(g.t, g.form, item);
if ("error" in r) return itemForm(reply, g, item, 422, { error: r.error, values: r.values });
await saveItem(item.id, r.ok, false);
return back(reply, `/library/editor/items/${item.id}?saved=1`);
});
app.post<{ Params: { id: string } }>("/library/editor/items/:id/file", { bodyLimit: UPLOAD_BODY_LIMIT, onRequest: rejectGuests }, async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const item = await findItem(req.params.id);
if (!item) return html(reply, 404, renderMessage(g.t, g.lang, g.t.notFoundTitle, g.t.notFoundText));
const file = (req.body as { files?: Record<string, { filename: string; data: Buffer }> }).files?.file;
const rights = one(g.form, "rights");
if (!RIGHTS.includes(rights as (typeof RIGHTS)[number])) return itemForm(reply, g, item, 422, { error: g.t.errRights });
if (!file || file.data.length === 0 || file.data.length > MAX_FILE_BYTES) return itemForm(reply, g, item, 422, { error: g.t.errFileSize });
const type = sniffFile(file.data);
if (!type) return itemForm(reply, g, item, 422, { error: g.t.errFileType });
await db.query(
"UPDATE library_items SET file_name=$2, file_type=$3, file_size=$4, file_data=$5, rights_basis=$6, updated_at=$7 WHERE id=$1",
[item.id, safeName(file.filename), type, file.data.length, file.data, rights, new Date(now())],
);
return back(reply, `/library/editor/items/${item.id}?saved=1`);
});
app.post<{ Params: { id: string } }>("/library/editor/items/:id/file/remove", async (req, reply) => {
const g = await guard(req, reply);
if (!g) return;
const item = await findItem(req.params.id);
if (!item) return html(reply, 404, renderMessage(g.t, g.lang, g.t.notFoundTitle, g.t.notFoundText));
if (item.status === "published" && !item.linkUrl) return itemForm(reply, g, item, 422, { error: g.t.errNeedSource });
await db.query("UPDATE library_items SET file_name=NULL, file_type=NULL, file_size=NULL, file_data=NULL, rights_basis=NULL, updated_at=$2 WHERE id=$1", [
item.id,
new Date(now()),
]);
return back(reply, `/library/editor/items/${item.id}?saved=1`);
});
}

173
src/modules/library/page.ts Normal file
View File

@ -0,0 +1,173 @@
import { escapeHtml as e } from "../../html.ts";
import { fmt, LANG_NAMES, LANGS, type Dict, type Lang } from "./i18n/index.ts";
import { flatten, label, MAX_DEPTH, type SectionNode } from "./tree.ts";
export const LIBRARY_CSS = `:root{--bg:#f7f6f2;--fg:#1d1d1b;--muted:#5d5d58;--card:#fff;--line:#e2e0d8;--accent:#2f5d50;--warn:#9a3412}
@media (prefers-color-scheme:dark){:root{--bg:#141413;--fg:#ecebe6;--muted:#a3a29b;--card:#1e1e1c;--line:#33332f;--accent:#8cc1b0;--warn:#fdba74}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
main{max-width:880px;margin:0 auto;padding:32px 16px}a{color:var(--accent)}h1{margin:8px 0}.lead,.meta,.note{color:var(--muted)}
nav.top{display:flex;gap:16px;flex-wrap:wrap;font-size:.875rem;justify-content:space-between}nav.top span a{margin-left:8px}
form.search{display:flex;gap:8px;margin:16px 0 24px}form.search input{flex:1}
input,select,textarea,button{font:inherit;padding:6px 10px;border:1px solid var(--line);border-radius:6px;background:var(--card);color:var(--fg)}
button{cursor:pointer;border-color:var(--accent);color:var(--accent)}textarea{width:100%;min-height:120px}
details{margin:4px 0}details>div,ul.toc ul{margin-left:20px}summary{cursor:pointer;font-weight:600}
ul{padding-left:20px}ul.toc{list-style:none;padding-left:0}.items{list-style:"📖 ";padding-left:24px}
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:20px;margin:16px 0}
.error{border:1px solid var(--warn);color:var(--warn);border-radius:8px;padding:8px 12px}.ok{color:var(--accent)}
.tag{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:0 8px;margin:0 4px 4px 0;font-size:.875rem}
.btn{display:inline-block;margin:8px 8px 0 0;padding:8px 16px;border:1px solid var(--accent);border-radius:8px;text-decoration:none}
.inline{display:inline-flex;gap:6px;margin:2px 8px 2px 0;align-items:center}.hidden{opacity:.55}
label{display:block;margin:10px 0 2px}label.check{display:flex;gap:6px;margin:2px 0;font-weight:normal}
.f input[type=text],.f input[type=url]{width:100%}table{border-collapse:collapse;width:100%}td,th{border-bottom:1px solid var(--line);padding:6px;text-align:left}
.d1{padding-left:20px}.d2{padding-left:40px}.d3{padding-left:60px}.d4{padding-left:80px}`;
export interface ItemView {
id: string;
title: string;
author: string;
edition: string;
language: string;
annotation: string;
tags: string[];
linkUrl: string | null;
fileName: string | null;
fileSize: number | null;
fileAccess: "public" | "closed";
rightsBasis: "own" | "licensed" | "public_domain" | null;
status: "draft" | "published";
sectionIds: string[];
}
interface ShellOpts { lang: Lang; title: string; switchPath?: string }
function shell(t: Dict, o: ShellOpts, inner: string): string {
const langs = o.switchPath
? `<span>${e(t.languages)}:${(Object.keys(LANGS) as Lang[])
.map((l) => (l === o.lang ? ` <strong>${e(LANG_NAMES[l])}</strong>` : ` <a href="${e(withLang(o.switchPath as string, l))}" hreflang="${l}">${e(LANG_NAMES[l])}</a>`))
.join("")}</span>`
: "";
return `<!doctype html><html lang="${e(t.htmlLang)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${e(o.title)}</title><link rel="stylesheet" href="/library/library.css"></head><body><main>
<nav class="top"><span><a href="/">${e(t.home)}</a> · <a href="/library">${e(t.title)}</a></span>${langs}</nav>${inner}</main></body></html>`;
}
const withLang = (path: string, lang: Lang): string => `${path}${path.includes("?") ? "&" : "?"}lang=${lang}`;
const err = (msg: string | undefined) => (msg ? `<p class="error" role="alert">${e(msg)}</p>` : "");
// ---------- публичная часть ----------
function itemLink(i: ItemView): string {
const by = i.author ? ` <span class="meta">— ${e(i.author)}</span>` : "";
return `<li><a href="/library/items/${e(i.id)}">${e(i.title)}</a>${by}</li>`;
}
export function renderCatalog(t: Dict, lang: Lang, tree: SectionNode[], itemsBySection: Map<string, ItemView[]>, search?: { q: string; found: ItemView[] }): string {
const node = (n: SectionNode): string => {
const items = itemsBySection.get(n.id) ?? [];
const inner = `${items.length ? `<ul class="items">${items.map(itemLink).join("")}</ul>` : ""}${n.children.map(node).join("")}`;
const title = e(label(n));
if (!inner) return `<div class="leaf">${title}</div>`;
return `<details${n.depth === 0 ? " open" : ""}><summary>${title}</summary><div>${inner}</div></details>`;
};
const q = search?.q ?? "";
const form = `<form class="search" method="get" action="/library" role="search"><input type="search" name="q" value="${e(q)}" aria-label="${e(t.searchLabel)}" placeholder="${e(t.searchLabel)}" maxlength="100"><button type="submit">${e(t.searchButton)}</button></form>`;
const body = search
? `<h2>${e(fmt(t.searchResults, { q }))}</h2>${search.found.length ? `<ul class="items">${search.found.map(itemLink).join("")}</ul>` : `<p>${e(t.nothingFound)}</p>`}<p><a href="/library">${e(t.allLibrary)}</a></p>`
: `<h2>${e(t.tocHeading)}</h2>${tree.map(node).join("")}`;
const switchPath = search ? `/library?q=${encodeURIComponent(q)}` : "/library";
return shell(t, { lang, title: t.title, switchPath }, `<h1>${e(t.title)}</h1><p class="lead">${e(t.lead)}</p>${form}${body}`);
}
export function renderItem(t: Dict, lang: Lang, i: ItemView, sections: SectionNode[], opts: { editor: boolean }): string {
const row = (k: string, v: string) => (v ? `<div><span class="meta">${e(k)}:</span> ${e(v)}</div>` : "");
const tags = i.tags.length ? `<div><span class="meta">${e(t.tags)}:</span> ${i.tags.map((x) => `<span class="tag">${e(x)}</span>`).join("")}</div>` : "";
const secs = sections.length ? `<div><span class="meta">${e(t.sections)}:</span><ul>${sections.map((s) => `<li>${e(label(s))}</li>`).join("")}</ul></div>` : "";
const ann = i.annotation ? `<h2>${e(t.annotation)}</h2>${i.annotation.split(/\n{2,}/).map((p) => `<p>${e(p.trim())}</p>`).join("")}` : "";
const link = i.linkUrl ? `<a class="btn" href="${e(i.linkUrl)}" rel="noopener noreferrer nofollow">${e(t.openLink)}</a>` : "";
const file = i.fileName ? `<a class="btn" href="/library/items/${e(i.id)}/file">${e(t.download)}</a>${i.fileAccess === "closed" ? `<p class="note">${e(t.closedFileNote)}</p>` : ""}` : "";
const draft = i.status === "draft" ? `<p class="error">${e(t.draftNote)}</p>` : "";
const back = opts.editor ? ` · <a href="/library/editor/items/${e(i.id)}">${e(t.backToEditor)}</a>` : "";
return shell(
t,
{ lang, title: `${i.title} — ${t.title}`, switchPath: `/library/items/${i.id}` },
`${draft}<article class="card"><h1>${e(i.title)}</h1>${row(t.author, i.author)}${row(t.edition, i.edition)}${row(t.language, i.language)}${tags}${secs}${ann}<p>${link}${file}</p></article><p><a href="/library">${e(t.allLibrary)}</a>${back}</p>`,
);
}
export function renderMessage(t: Dict, lang: Lang, title: string, text: string): string {
return shell(t, { lang, title }, `<h1>${e(title)}</h1><p>${e(text)}</p><p><a href="/library">${e(t.allLibrary)}</a></p>`);
}
// ---------- редактор ----------
const csrfInput = (csrf: string) => `<input type="hidden" name="csrf" value="${e(csrf)}">`;
export function renderLogin(t: Dict, lang: Lang, opts: { error?: string; disabled?: boolean }): string {
const form = opts.disabled
? ""
: `<form method="post" action="/library/editor/login" class="f"><label for="pw">${e(t.password)}</label><input id="pw" type="password" name="password" autocomplete="current-password" required><p><button type="submit">${e(t.loginButton)}</button></p></form>`;
return shell(t, { lang, title: t.loginTitle, switchPath: "/library/editor" }, `<h1>${e(t.loginTitle)}</h1><p class="lead">${e(opts.disabled ? t.editorOff : t.loginLead)}</p>${err(opts.error)}${form}`);
}
export function renderEditor(t: Dict, lang: Lang, csrf: string, tree: SectionNode[], items: ItemView[], opts: { error?: string; saved?: boolean }): string {
const act = (n: SectionNode, action: string, text: string) =>
`<form method="post" action="/library/editor/sections/${e(n.id)}" class="inline">${csrfInput(csrf)}<input type="hidden" name="action" value="${action}"><button type="submit">${e(text)}</button></form>`;
const node = (n: SectionNode): string => {
const addChild =
n.depth < MAX_DEPTH - 1
? `<form method="post" action="/library/editor/sections" class="inline">${csrfInput(csrf)}<input type="hidden" name="parent" value="${e(n.id)}"><input type="text" name="title" required maxlength="200" aria-label="${e(t.newTitle)}" placeholder="${e(t.newTitle)}"><button type="submit">${e(t.addChild)}</button></form>`
: "";
const rename = `<form method="post" action="/library/editor/sections/${e(n.id)}" class="inline">${csrfInput(csrf)}<input type="hidden" name="action" value="rename"><input type="text" name="title" value="${e(n.title)}" required maxlength="200" aria-label="${e(t.newTitle)}"><button type="submit">${e(t.rename)}</button></form>`;
const hide = n.selfHidden ? act(n, "restore", t.restore) : act(n, "hide", t.hide);
return `<li${n.hidden ? ' class="hidden"' : ""}><details><summary>${e(label(n))}${n.hidden ? ` <em>(${e(t.hiddenMark)})</em>` : ""}</summary><div>${rename}${act(n, "up", t.up)}${act(n, "down", t.down)}${hide}${addChild}</div></details>${n.children.length ? `<ul class="toc">${n.children.map(node).join("")}</ul>` : ""}</li>`;
};
const all = flatten(tree);
const opt = (n: SectionNode) => `<option value="${e(n.id)}">${"— ".repeat(n.depth)}${e(label(n))}</option>`;
const move = `<h3>${e(t.moveHeading)}</h3><form method="post" action="/library/editor/move" class="f">${csrfInput(csrf)}<label for="mv-what">${e(t.moveWhat)}</label><select id="mv-what" name="section" required>${all.map(opt).join("")}</select><label for="mv-where">${e(t.moveWhere)}</label><select id="mv-where" name="parent"><option value="">${e(t.topLevel)}</option>${all.filter((n) => n.depth < MAX_DEPTH - 1).map(opt).join("")}</select><p><button type="submit">${e(t.moveButton)}</button></p></form>`;
const addPart = `<form method="post" action="/library/editor/sections" class="inline">${csrfInput(csrf)}<input type="text" name="title" required maxlength="200" aria-label="${e(t.newTitle)}" placeholder="${e(t.newTitle)}"><button type="submit">${e(t.addPart)}</button></form>`;
const status = (i: ItemView) => (i.status === "published" ? t.statusPublished : t.statusDraft);
const list = items.length
? `<table><tbody>${items.map((i) => `<tr><td><a href="/library/editor/items/${e(i.id)}">${e(i.title)}</a></td><td>${e(i.author)}</td><td>${e(status(i))}</td></tr>`).join("")}</tbody></table>`
: `<p class="note">${e(t.noMaterials)}</p>`;
const top = `<form method="post" action="/library/editor/logout" class="inline">${csrfInput(csrf)}<a href="/library">${e(t.openCatalog)}</a> <button type="submit">${e(t.logout)}</button></form>`;
return shell(
t,
{ lang, title: t.editorTitle, switchPath: "/library/editor" },
`<h1>${e(t.editorTitle)}</h1><p class="lead">${e(t.editorLead)}</p>${top}${err(opts.error)}${opts.saved ? `<p class="ok" role="status">${e(t.saved)}</p>` : ""}
<h2>${e(t.materialsHeading)}</h2><p><a class="btn" href="/library/editor/items/new">${e(t.newMaterial)}</a></p>${list}
<h2>${e(t.tocHeading)}</h2>${addPart}<ul class="toc">${tree.map(node).join("")}</ul>${move}`,
);
}
export function renderItemForm(t: Dict, lang: Lang, csrf: string, tree: SectionNode[], item: ItemView | null, opts: { error?: string; saved?: boolean; values?: Partial<ItemView> }): string {
const v: Partial<ItemView> = { ...(item ?? {}), ...(opts.values ?? {}) };
const text = (name: string, lbl: string, value: string | null | undefined, type = "text", max = 300, required = false) =>
`<label for="f-${name}">${e(lbl)}</label><input id="f-${name}" type="${type}" name="${name}" value="${e(value ?? "")}" maxlength="${max}"${required ? " required" : ""}>`;
const radio = (name: string, value: string, lbl: string, checked: boolean) =>
`<label class="check"><input type="radio" name="${name}" value="${value}"${checked ? " checked" : ""}> ${e(lbl)}</label>`;
const selected = new Set(v.sectionIds ?? []);
const secs = flatten(tree)
.map((n) => `<label class="check d${n.depth}"><input type="checkbox" name="sections" value="${e(n.id)}"${selected.has(n.id) ? " checked" : ""}> ${e(label(n))}${n.hidden ? ` (${e(t.hiddenMark)})` : ""}</label>`)
.join("");
const action = item ? `/library/editor/items/${e(item.id)}` : "/library/editor/items";
const main = `<form method="post" action="${action}" class="f">${csrfInput(csrf)}
${text("title", t.fieldTitle, v.title, "text", 300, true)}${text("author", t.author, v.author)}${text("edition", t.edition, v.edition, "text", 200)}${text("language", t.language, v.language, "text", 60)}
<label for="f-annotation">${e(t.annotation)}</label><textarea id="f-annotation" name="annotation" maxlength="5000">${e(v.annotation ?? "")}</textarea>
${text("tags", t.fieldTags, (v.tags ?? []).join(", "), "text", 1000)}${text("link", t.fieldLink, v.linkUrl, "url", 2000)}
<fieldset><legend>${e(t.fieldAccess)}</legend>${radio("access", "public", t.accessPublic, v.fileAccess !== "closed")}${radio("access", "closed", t.accessClosed, v.fileAccess === "closed")}</fieldset>
<fieldset><legend>${e(t.sections)}</legend>${secs}</fieldset>
<fieldset><legend>${e(t.status)}</legend>${radio("status", "draft", t.statusDraft, v.status !== "published")}${radio("status", "published", t.statusPublished, v.status === "published")}</fieldset>
<p><button type="submit">${e(t.save)}</button></p></form>`;
const file = item
? `<h2>${e(t.fileHeading)}</h2>${item.fileName ? `<p>${e(fmt(t.currentFile, { name: item.fileName, size: Math.ceil((item.fileSize ?? 0) / 1024) }))}</p><form method="post" action="/library/editor/items/${e(item.id)}/file/remove" class="inline">${csrfInput(csrf)}<button type="submit">${e(t.removeFile)}</button></form>` : ""}
<form method="post" action="/library/editor/items/${e(item.id)}/file" enctype="multipart/form-data" class="f">${csrfInput(csrf)}<label for="f-file">${e(t.fieldFile)}</label><input id="f-file" type="file" name="file" accept=".pdf,.epub,application/pdf,application/epub+zip" required>
<fieldset><legend>${e(t.fieldRights)}</legend>${radio("rights", "own", t.rightsOwn, item.rightsBasis === "own")}${radio("rights", "licensed", t.rightsLicensed, item.rightsBasis === "licensed")}${radio("rights", "public_domain", t.rightsPublicDomain, item.rightsBasis === "public_domain")}</fieldset>
<p><button type="submit">${e(t.upload)}</button></p></form>`
: "";
const links = `<p><a href="/library/editor">${e(t.backToEditor)}</a>${item ? ` · <a href="/library/items/${e(item.id)}">${e(t.preview)}</a>` : ""}</p>`;
return shell(
t,
{ lang, title: `${item?.title ?? t.newMaterial} — ${t.editorTitle}`, switchPath: item ? `/library/editor/items/${item.id}` : "/library/editor/items/new" },
`<h1>${e(item?.title ?? t.newMaterial)}</h1>${links}${err(opts.error)}${opts.saved ? `<p class="ok" role="status">${e(t.saved)}</p>` : ""}${main}${file}`,
);
}

View File

@ -0,0 +1,62 @@
export const MAX_DEPTH = 5;
export interface SectionRow {
id: string;
parent_id: string | null;
title: string;
position: number;
hidden: boolean;
}
export interface SectionNode {
id: string;
title: string;
hidden: boolean;
/** Скрыт сам раздел (а не только его предок). */
selfHidden: boolean;
depth: number;
/** «I.» для частей, «3.» для глав, пусто для пунктов и скрытых. */
number: string;
parentId: string | null;
children: SectionNode[];
}
const ROMAN: [number, string][] = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]];
export function roman(n: number): string {
let out = "";
for (const [v, s] of ROMAN) while (n >= v) { out += s; n -= v; }
return out;
}
/** Дерево разделов. Номера считаются только по видимым разделам: части — римские, главы — сквозные. */
export function buildTree(rows: SectionRow[]): SectionNode[] {
const byParent = new Map<string | null, SectionRow[]>();
for (const r of rows) byParent.set(r.parent_id, [...(byParent.get(r.parent_id) ?? []), r]);
for (const list of byParent.values()) list.sort((a, b) => a.position - b.position || a.id.localeCompare(b.id));
let part = 0;
let chapter = 0;
const walk = (parent: string | null, depth: number, hiddenAbove: boolean): SectionNode[] =>
(byParent.get(parent) ?? []).map((r) => {
const hidden = hiddenAbove || r.hidden;
let number = "";
if (!hidden && depth === 0) number = `${roman(++part)}.`;
if (!hidden && depth === 1) number = `${++chapter}.`;
return { id: r.id, title: r.title, hidden, selfHidden: r.hidden, depth, number, parentId: r.parent_id, children: walk(r.id, depth + 1, hidden) };
});
return walk(null, 0, false);
}
export function flatten(nodes: SectionNode[]): SectionNode[] {
return nodes.flatMap((n) => [n, ...flatten(n.children)]);
}
export function subtreeHeight(n: SectionNode): number {
return 1 + Math.max(0, ...n.children.map(subtreeHeight));
}
/** Видимое дерево для гостей: без скрытых разделов и их потомков. */
export function visibleOnly(nodes: SectionNode[]): SectionNode[] {
return nodes.filter((n) => !n.hidden).map((n) => ({ ...n, children: visibleOnly(n.children) }));
}
export const label = (n: SectionNode): string => (n.number ? `${n.number} ${n.title}` : n.title);