import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; import type { Pool } from "khb_common"; import { AccessError, type Caller } from "./access.js"; import { Auth, safeEqual } from "./auth.js"; import { HttpError, type ListFilters, type TodoCore, type WriteResult } from "./core.js"; import { handleMcpMessage } from "./mcp.js"; import type { TodoServiceSettings } from "./settings.js"; import type { Watchers } from "./watchers.js"; export interface ApiDeps { pool: Pool; core: TodoCore; watchers: Watchers; settings: TodoServiceSettings; auth: Auth; } type Q = Record; type B = Record; // eslint-disable-line @typescript-eslint/no-explicit-any export function buildApi(deps: ApiDeps): FastifyInstance { const { core, settings } = deps; const app = Fastify({ bodyLimit: 1_000_000 }); const caller = (req: FastifyRequest): Promise => deps.auth.internal(req.headers.authorization, one(req.headers["x-caller-person"])); const one = (h: string | string[] | undefined): string | undefined => (Array.isArray(h) ? h[0] : h); const key = (req: FastifyRequest): string | undefined => one(req.headers["idempotency-key"]); const reply202 = (r: WriteResult): { code: number; body: WriteResult } => ({ code: r.status === "queued" ? 202 : 200, body: r }); app.setErrorHandler((e: Error & { statusCode?: number }, _req, reply) => { if (e instanceof AccessError || e instanceof HttpError) return reply.code(e instanceof AccessError ? e.status : e.status).send({ error: e.message }); if (e.statusCode && e.statusCode < 500) return reply.code(e.statusCode).send({ error: e.message }); return reply.code(500).send({ error: e.message }); }); app.get("/healthz", async () => { let db = false; try { await deps.pool.query("select 1"); db = true; } catch { /* db=false */ } return { ok: db, db, time: new Date().toISOString() }; }); // --- приём вебхуков JobTread: секрет в пути (подписи у JobTread нет) app.post<{ Params: { secret: string }; Body: unknown }>("/webhooks/jobtread/:secret", async (req, reply) => { const secret = settings.webhook.secret; if (!secret || !safeEqual(req.params.secret, secret)) return reply.code(404).send({ error: "not found" }); try { const r = await core.applyWebhook(req.body); return reply.code(202).send(r); } catch (e) { req.log.error({ err: String(e) }, "вебхук не обработан (опрос подберёт изменение)"); return reply.code(202).send({ handled: false }); } }); // --- todo app.get<{ Querystring: Q }>("/todos", async (req) => { const q = req.query; const f: ListFilters = { assignee: q.assignee, job: q.job, kind: q.kind as ListFilters["kind"], status: q.status as ListFilters["status"], dueBefore: q.due_before, reviewDue: q.review_due === "1" || q.review_due === "true", q: q.q, limit: q.limit ? Number(q.limit) : undefined, offset: q.offset ? Number(q.offset) : undefined, }; return core.list(await caller(req), f); }); app.get<{ Querystring: Q }>("/todos/stale", async (req) => core.stale(await caller(req), { personId: req.query.person, days: req.query.days ? Number(req.query.days) : undefined })); app.post<{ Body: B }>("/todos/close-batch", async (req) => core.closeMany(await caller(req), (req.body?.ids as string[]) ?? [])); app.get<{ Params: { id: string } }>("/todos/:id", async (req) => core.get(await caller(req), req.params.id)); app.get<{ Params: { id: string } }>("/todos/:id/links", async (req) => core.links(await caller(req), req.params.id)); app.post<{ Body: B }>("/todos", async (req, reply) => { const r = reply202(await core.create(await caller(req), req.body as never, key(req))); return reply.code(r.code).send(r.body); }); app.patch<{ Params: { id: string }; Body: B }>("/todos/:id", async (req, reply) => { const r = reply202(await core.update(await caller(req), req.params.id, (req.body ?? {}) as never, key(req))); return reply.code(r.code).send(r.body); }); app.delete<{ Params: { id: string } }>("/todos/:id", async (req, reply) => { const r = reply202(await core.remove(await caller(req), req.params.id, key(req))); return reply.code(r.code).send(r.body); }); app.post<{ Params: { id: string } }>("/todos/:id/close", async (req, reply) => { const r = reply202(await core.close(await caller(req), req.params.id, key(req))); return reply.code(r.code).send(r.body); }); app.post<{ Params: { id: string } }>("/todos/:id/reopen", async (req, reply) => { const r = reply202(await core.reopen(await caller(req), req.params.id, key(req))); return reply.code(r.code).send(r.body); }); app.post<{ Params: { id: string }; Body: B }>("/todos/:id/snooze", async (req, reply) => { const r = reply202(await core.snooze(await caller(req), req.params.id, { until: req.body?.until, days: req.body?.days })); return reply.code(r.code).send(r.body); }); app.post<{ Params: { id: string } }>("/todos/:id/keep", async (req, reply) => { const r = reply202(await core.keep(await caller(req), req.params.id)); return reply.code(r.code).send(r.body); }); app.post<{ Body: B }>("/control", async (req, reply) => { const r = reply202(await core.createControl(await caller(req), req.body as never, key(req))); return reply.code(r.code).send(r.body); }); app.get<{ Params: { id: string } }>("/requests/:id", async (req) => core.request(await caller(req), req.params.id)); // --- события для агентов app.get<{ Querystring: Q }>("/events", async (req) => core.events(await caller(req), { personId: req.query.person, afterId: req.query.after ? Number(req.query.after) : undefined, pending: req.query.pending === "1" }), ); app.post<{ Body: B }>("/events/ack", async (req) => ({ acked: await core.ackEvents(await caller(req), ((req.body?.ids as number[]) ?? []).map(Number)) })); // --- служебное (только внутренний токен без person) app.post("/admin/sync", async (req) => { const c = await caller(req); if (!c.all || c.kind !== "admin") throw new AccessError("только администратор"); return { backfilled: await core.backfill(), polled: await core.pollEvents() }; }); app.post("/admin/webhook", async (req) => { const c = await caller(req); if (!c.all || c.kind !== "admin") throw new AccessError("только администратор"); return { webhookId: await core.ensureWebhook() }; }); app.post("/admin/tick", async (req) => { const c = await caller(req); if (!c.all || c.kind !== "admin") throw new AccessError("только администратор"); return { control: await deps.watchers.controlTick(), review: await deps.watchers.reviewTick(), requests: await core.processRequests(), delivered: await deps.watchers.deliverEvents() }; }); // --- MCP (Streamable HTTP, без сессий) if (settings.mcp.enabled) { const base = settings.mcp.publicUrl?.replace(/\/$/, ""); app.get("/.well-known/oauth-protected-resource", async (_req, reply) => { if (!base) return reply.code(404).send({ error: "not configured" }); return { resource: `${base}/mcp`, ...(settings.mcp.issuer ? { authorization_servers: [settings.mcp.issuer] } : {}), bearer_methods_supported: ["header"] }; }); app.get("/mcp", async (_req, reply) => reply.code(405).header("allow", "POST").send({ error: "use POST" })); app.delete("/mcp", async (_req, reply) => reply.code(405).send({ error: "no sessions" })); app.post<{ Body: unknown }>("/mcp", async (req, reply) => { let c: Caller; try { c = await deps.auth.mcp(req.headers.authorization, one(req.headers["x-caller-person"])); } catch (e) { if (e instanceof AccessError && e.status === 401 && base) reply.header("www-authenticate", `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`); throw e; } const body = req.body; if (Array.isArray(body)) { const out = (await Promise.all(body.map((m) => handleMcpMessage(core, c, m as never)))).filter((x) => x); return out.length ? out : reply.code(202).send(); } const res = await handleMcpMessage(core, c, (body ?? {}) as never); return res ?? reply.code(202).send(); }); } return app; }