customer/src/app.ts

103 lines
4.6 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 Fastify, { type FastifyError, type FastifyInstance, type FastifyServerOptions } from "fastify";
import helmet from "@fastify/helmet";
import { captureError } from "./sentry.ts";
import type { TxDb } from "./db/db.ts";
import { accountsModule, type AccountsOptions } from "./modules/accounts/index.ts";
import { privacyModule, type PrivacyOptions } from "./modules/privacy/index.ts";
import { billingModule, type BillingOptions } from "./modules/billing/index.ts";
import { catalogModule, type CatalogOptions } from "./modules/catalog/index.ts";
import { auditsModule, type AuditsOptions } from "./modules/audits/index.ts";
import { kitsModule, type KitsOptions } from "./modules/kits/index.ts";
import { trainerModule, type TrainerOptions } from "./modules/trainer/index.ts";
export const BODY_LIMIT = 1024 * 1024;
export interface AppOptions {
logger?: FastifyServerOptions["logger"];
catalog?: CatalogOptions;
/** БД; без неё модуль учётных записей не регистрируется. */
db?: TxDb;
accounts?: Omit<AccountsOptions, "db">;
/** Хранилище загрузок: нужны `db` и `privacy.keys`; юридические страницы — всегда. */
privacy?: Omit<PrivacyOptions, "db">;
/** Платёжный провайдер; без БД или провайдера модуль биллинга не регистрируется. */
billing?: Omit<BillingOptions, "db">;
/** Цифровые комплекты; без БД или linkSecret модуль не регистрируется. */
kits?: Omit<KitsOptions, "db">;
/** Экспресс-аудит; нужны БД, хранилище загрузок (privacy.keys), LLM и шрифт PDF. */
audits?: Omit<AuditsOptions, "db">;
/** AI-тренажёр; нужны БД, хранилище загрузок и LLM; Telegram — по желанию. */
trainer?: Omit<TrainerOptions, "db">;
}
const CLIENT_ERROR_CODES: Record<number, string> = {
400: "bad_request",
404: "not_found",
405: "method_not_allowed",
413: "payload_too_large",
415: "unsupported_media_type",
};
export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance> {
const app = Fastify({
logger: opts.logger ?? false,
bodyLimit: BODY_LIMIT,
// За Traefik: клиентский IP (только для счётчиков rate-limit в памяти) — из X-Forwarded-For одного прокси.
trustProxy: (_address: string, hop: number) => hop < 1,
});
await app.register(helmet, {
contentSecurityPolicy: {
useDefaults: false,
directives: {
defaultSrc: ["'self'"],
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'none'"],
objectSrc: ["'none'"],
imgSrc: ["'self'", "data:"],
styleSrc: ["'self'"],
scriptSrc: ["'self'"],
},
},
xFrameOptions: { action: "deny" },
referrerPolicy: { policy: "strict-origin-when-cross-origin" },
});
// Тело больше лимита отклоняем до маршрутизации — и для несуществующих маршрутов тоже.
app.addHook("onRequest", async (req, reply) => {
const len = Number(req.headers["content-length"] ?? 0);
if (Number.isFinite(len) && len > BODY_LIMIT) {
return reply.code(413).send({ error: "payload_too_large" });
}
});
app.setNotFoundHandler(async (_req, reply) => reply.code(404).send({ error: "not_found" }));
app.setErrorHandler(async (err: FastifyError, req, reply) => {
const status = err.statusCode ?? 500;
if (status >= 400 && status < 500) {
return reply.code(status).send({ error: CLIENT_ERROR_CODES[status] ?? "client_error" });
}
req.log.error({ err }, "unhandled error");
captureError(err, { method: req.method, url: req.url });
return reply.code(500).send({ error: "internal_error" });
});
app.get("/healthz", async () => ({ status: "ok" }));
await app.register(catalogModule, opts.catalog ?? {});
await app.register(privacyModule, { ...opts.privacy, db: opts.db });
if (opts.db) {
await app.register(accountsModule, { ...opts.accounts, db: opts.db });
if (opts.billing) await app.register(billingModule, { now: opts.accounts?.now, ...opts.billing, db: opts.db });
if (opts.kits) await app.register(kitsModule, { now: opts.accounts?.now, ...opts.kits, db: opts.db });
if (opts.audits && app.uploads) await app.register(auditsModule, { now: opts.accounts?.now, ...opts.audits, db: opts.db });
if (opts.trainer && app.uploads) await app.register(trainerModule, { now: opts.accounts?.now, ...opts.trainer, db: opts.db });
}
return app;
}