/** * BitReport Error Reporting Platform — Fastify API entry point. */ import Fastify from 'fastify'; import cookie from '@fastify/cookie'; import jwt from '@fastify/jwt'; import helmet from '@fastify/helmet'; import rateLimit from '@fastify/rate-limit'; import dbPlugin from './plugins/db.js'; import authPlugin from './plugins/auth.js'; import rbacPlugin from './plugins/rbac.js'; import auditPlugin from './plugins/audit.js'; import rateLimitPlugin from './plugins/rate-limit.js'; import { INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES } from './plugins/rate-limit.js'; import adminAuthRoutes from './routes/admin/auth.js'; import adminStatsRoutes from './routes/admin/stats.js'; import adminIncidentsRoutes from './routes/admin/incidents.js'; import recentErrorsPublicRoutes from './routes/public/recentErrors.js'; import errorMonitoringMutationsRoutes from './routes/public/errorMonitoringMutations.js'; import errorMonitoringStatsRoutes from './routes/public/errorMonitoringStats.js'; import prometheusPlugin from './plugins/prometheus.js'; const IS_PROD = process.env.NODE_ENV === 'production'; const app = Fastify({ logger: { level: process.env.LOG_LEVEL ?? 'info', ...(IS_PROD ? {} : { transport: { target: 'pino-pretty' } }), }, // Use the larger of the two limits as the global hard cap; per-route hooks refine. bodyLimit: Math.max(INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES), trustProxy: IS_PROD, // trust X-Forwarded-For behind reverse proxy in prod }); // Security headers await app.register(helmet, { contentSecurityPolicy: IS_PROD ? undefined : false, }); // Cookies (required before JWT cookie mode) await app.register(cookie, { secret: process.env.COOKIE_SECRET ?? (() => { throw new Error('COOKIE_SECRET is required'); })(), }); // JWT await app.register(jwt, { secret: process.env.JWT_SECRET ?? (() => { throw new Error('JWT_SECRET is required'); })(), cookie: { cookieName: '__Host-access', signed: false }, }); // Global rate limit (per-route limits override this) await app.register(rateLimit, { global: true, max: parseInt(process.env.RATE_GLOBAL_MAX ?? '500', 10), timeWindow: parseInt(process.env.RATE_GLOBAL_WINDOW_MS ?? '60000', 10), }); // Database await app.register(dbPlugin); // App-level plugins (depend on db) await app.register(authPlugin); await app.register(rbacPlugin); await app.register(auditPlugin); await app.register(rateLimitPlugin); await app.register(prometheusPlugin); // Routes await app.register(recentErrorsPublicRoutes); await app.register(errorMonitoringMutationsRoutes); await app.register(errorMonitoringStatsRoutes); await app.register(adminAuthRoutes); await app.register(adminStatsRoutes); await app.register(adminIncidentsRoutes); // Health check app.get('/health', async () => ({ ok: true, ts: new Date().toISOString() })); // Start const host = process.env.HOST ?? '0.0.0.0'; const port = parseInt(process.env.PORT ?? '3200', 10); try { await app.listen({ host, port }); } catch (err) { app.log.error(err); process.exit(1); }