freetravel/src/server.ts
Peppa 39d6884f34
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 3с
peppa/test test: success за 1с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 24s
deploy / deploy (pull_request) Successful in 14s
FRTVL-35: итог подтверждения привязки Телеграма с понятной причиной
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 03:36:06 +05:00

118 lines
4.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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

import { 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<FastifyInstance> {
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/confirm", async () => {
const result = await notifier.checkLink();
return { result, settings: await 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;
}