import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { healthCheck } from "../plugins/db.js"; import * as authService from "../services/auth.js"; export async function healthRoutes(app: FastifyInstance) { app.get("/health", async (request, reply) => { healthCheck(request.server.sqlite); return { status: "ok" }; }); app.get("/ready", async (request, reply) => { healthCheck(request.server.sqlite); let cloudflare = false; if (request.server.config.cloudflareApiToken) { try { await request.server.cf.listZones(); cloudflare = true; } catch { cloudflare = false; } } return { status: cloudflare || !request.server.config.cloudflareApiToken ? "ready" : "degraded", database: true, cloudflare, }; }); } export async function authRoutes(app: FastifyInstance) { app.get("/auth/config", async (request) => { const { config } = request.server; return { required: config.authRequired, portal_url: config.authPortalUrl, }; }); const loginSchema = z.object({ username: z.string(), password: z.string(), }); app.post("/auth/login", async (request, reply) => { if (request.server.config.authRequired) { return reply.code(403).send({ error: { code: "FORBIDDEN", message: "Локальный вход отключён — используйте auth-portal", }, }); } const body = loginSchema.parse(request.body); const result = await authService.login( request.server.config, (payload) => request.server.jwt.sign(payload), body, ); return result; }); }