import { timingSafeEqual } from "node:crypto"; import path from "node:path"; import { fileURLToPath } from "node:url"; import fastifyStatic from "@fastify/static"; import Fastify, { type FastifyInstance } from "fastify"; import { sortForDisplay } from "./domain/internship.js"; import { Notifier, NotifierError } from "./notify/notifier.js"; import { SearchAlreadyRunningError, type SearchService } from "./search/searchService.js"; import type { CatalogStore } from "./store/catalogStore.js"; export interface ServerOptions { store: CatalogStore; search: SearchService; /** Привязка Телеграма и регулярный поиск; без него эндпоинты настроек не регистрируются. */ notifier?: Notifier; /** Код доступа к запуску поиска; пустой — без кода. */ searchToken?: string; /** Каталог со статикой страницы. */ publicDir?: string; /** Имя провайдера для страницы (mock / claude). */ providerName?: string; logger?: boolean; /** Вызывается до регистрации маршрутов (например, обработчик ошибок Sentry). */ setup?: (app: FastifyInstance) => void; } const defaultPublicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "public"); function tokenMatches(expected: string, header: string | undefined): boolean { const given = header?.replace(/^Bearer\s+/i, "") ?? ""; const a = Buffer.from(expected); const b = Buffer.from(given); return a.length === b.length && timingSafeEqual(a, b); } export async function buildServer(options: ServerOptions): Promise { const app = Fastify({ logger: options.logger ?? false }); options.setup?.(app); app.get("/healthz", async () => ({ ok: true })); app.get("/api/internships", async () => { const catalog = await options.store.load(); return { internships: sortForDisplay(catalog), lastRun: catalog.lastRun }; }); app.get("/api/search/status", async () => { const catalog = await options.store.load(); return { state: options.search.running ? "running" : "idle", lastRun: catalog.lastRun, provider: options.providerName ?? "unknown", tokenRequired: Boolean(options.searchToken), }; }); const unauthorized = (header: string | undefined) => Boolean(options.searchToken) && !tokenMatches(options.searchToken as string, header); const { notifier } = options; if (notifier) { app.get("/api/settings", async () => notifier.view()); // Изменения настроек защищены тем же токеном, что и запуск поиска. app.addHook("preHandler", async (request, reply) => { const isSettingsWrite = request.url.startsWith("/api/settings") && request.method !== "GET"; if (isSettingsWrite && unauthorized(request.headers.authorization)) { return reply.code(401).send({ error: "Неверный код доступа" }); } }); app.setErrorHandler((error, _request, reply) => { if (error instanceof NotifierError) return reply.code(error.status).send({ error: error.message }); return reply.send(error); }); app.post("/api/settings/telegram/link", async () => ({ url: await notifier.startLink() })); app.delete("/api/settings/telegram", async () => { await notifier.unlink(); return notifier.view(); }); app.post("/api/settings/telegram/mock-confirm", async (_request, reply) => { if ((await notifier.view()).telegram !== "mock") return reply.code(404).send({ error: "Недоступно" }); await notifier.mockConfirmLink(); return notifier.view(); }); app.put<{ Body: { enabled?: unknown } }>("/api/settings", async (request, reply) => { if (typeof request.body?.enabled !== "boolean") { return reply.code(400).send({ error: "Поле enabled должно быть true или false" }); } await notifier.setEnabled(request.body.enabled); return notifier.view(); }); } app.post("/api/search", async (request, reply) => { if (unauthorized(request.headers.authorization)) { return reply.code(401).send({ error: "Неверный код доступа" }); } try { options.search.start().catch((error: unknown) => request.log.error(error, "search run failed")); } catch (error) { if (error instanceof SearchAlreadyRunningError) { return reply.code(409).send({ error: error.message }); } throw error; } return reply.code(202).send({ state: "running" }); }); await app.register(fastifyStatic, { root: options.publicDir ?? defaultPublicDir }); return app; }