All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
82 lines
2.9 KiB
TypeScript
82 lines
2.9 KiB
TypeScript
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 { catalogModule, type CatalogOptions } from "./modules/catalog/index.ts";
|
||
|
||
export const BODY_LIMIT = 1024 * 1024;
|
||
|
||
export interface AppOptions {
|
||
logger?: FastifyServerOptions["logger"];
|
||
catalog?: CatalogOptions;
|
||
/** БД; без неё модуль учётных записей не регистрируется. */
|
||
db?: TxDb;
|
||
accounts?: Omit<AccountsOptions, "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 ?? {});
|
||
|
||
if (opts.db) {
|
||
await app.register(accountsModule, { ...opts.accounts, db: opts.db });
|
||
}
|
||
|
||
return app;
|
||
}
|