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 { const out: Record = {}; 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; export async function libraryModule(app: FastifyInstance, opts: LibraryOptions): Promise { 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 | 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 { return buildTree((await d.query("SELECT id, parent_id, title, position, hidden FROM library_sections")).rows); } async function items(where: string, params: unknown[] = []): Promise { const r = await db.query(`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 => (UUID_RE.test(id) ? ((await items("WHERE i.id = $1", [id]))[0] ?? null) : null); // ---------- сессия редактора ---------- interface Editor { csrf: string } async function editorSession(req: FastifyRequest): Promise { 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).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(); 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).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 { 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 { 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 } = {}) { 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 } | { 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 { 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).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 }).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`); }); }