import { createHmac } from "node:crypto"; import Fastify, { type FastifyInstance } from "fastify"; import { QboAuth, ReauthNeeded } from "./service.js"; import type { QboSync } from "./sync.js"; import { TESTS_PAGE } from "./tests-page.js"; import { parseWebhook, verifyWebhook } from "./webhook.js"; export interface WebhookOptions { tokens: string[]; /** Вызывается после проверки подписи, если в вебхуке есть изменённые объекты. */ onEvents(events: ReturnType): void; } const page = (title: string, text: string) => `${title}

${title}

${text}

`; /** * Служебные ручки закрыты токеном (settings.json5 `qbo_auth.http.token`); открыты /healthz и /callback. * /callback защищён одноразовым state; наружу (nginx services) публикуется только он: /api/qbo/callback. */ export interface AuditLog { info(obj: Record, msg: string): void; } export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: WebhookOptions, audit?: AuditLog): FastifyInstance { const app = Fastify(); // тело вебхука нужно целиком (подпись считается по сырой строке) app.addContentTypeParser("application/json", { parseAs: "string" }, (req, body, done) => { if (req.url.split("?")[0] === "/webhook") return done(null, body); try { done(null, body === "" ? {} : JSON.parse(body as string)); } catch (e) { done(e as Error, undefined); } }); // требования Intuit: ответы с токенами и страницы действий не кэшируются, адрес с code/state не уходит в Referer app.addHook("onSend", async (_req, reply) => { reply.header("Cache-Control", "no-cache, no-store"); reply.header("Pragma", "no-cache"); reply.header("Referrer-Policy", "no-referrer"); reply.header("X-Content-Type-Options", "nosniff"); }); // CloudEvents-вебхуки Intuit приходят с типом application/cloudevents+json (и batch-вариантом): подпись считается по сырой строке app.addContentTypeParser(/^application\/cloudevents(-batch)?\+json/i, { parseAs: "string" }, (_req, body, done) => done(null, body)); const slug = testsSlug(token); app.addHook("onRequest", async (req, reply) => { const path = req.url.split("?")[0] ?? ""; if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/connected") return; if (path.startsWith("/tests/")) return; // защита по секретному адресу (см. ниже) if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" }); }); /** Вебхук Intuit (публикуется наружу: /api/qbo/webhook). Подпись обязательна; ответ 200 сразу, загрузка идёт в фоне. */ app.post("/webhook", async (req, reply) => { if (!webhook || webhook.tokens.length === 0) return reply.code(503).send({ error: "webhook_not_configured" }); const raw = typeof req.body === "string" ? req.body : ""; if (!verifyWebhook(raw, req.headers["intuit-signature"] as string | undefined, webhook.tokens)) return reply.code(401).send({ error: "bad_signature" }); const events = parseWebhook(raw); if (events.length) webhook.onEvents(events); return reply.code(200).send({ ok: true, events: events.length }); }); /** * Страница ручных тестов: секретный адрес /tests/ (slug выводится из служебного токена, вводить ничего не нужно); при неверном slug - 404. * Наружу: /api/qbo/tests/. */ const tests = (req: { params: unknown }): boolean => (req.params as { slug?: string }).slug === slug; app.get("/tests/:slug", async (req, reply) => (tests(req) ? reply.type("text/html").send(TESTS_PAGE) : reply.code(404).send({ error: "not_found" }))); app.get("/tests/:slug/status", async (req, reply) => { if (!tests(req)) return reply.code(404).send({ error: "not_found" }); const st = await auth.status(); audit?.info({ action: "status", connected: st.connected, status: "status" in st ? st.status : "not_connected" }, "ручной тест"); return st; }); app.post("/tests/:slug/connect", async (req, reply) => { if (!tests(req)) return reply.code(404).send({ error: "not_found" }); const r = await auth.startConnect(); audit?.info({ action: "connect", result: "ссылка авторизации выдана" }, "ручной тест"); return r; }); app.post("/tests/:slug/disconnect", async (req, reply) => { if (!tests(req)) return reply.code(404).send({ error: "not_found" }); const r = await auth.disconnect(); audit?.info({ action: "disconnect", ...r }, "ручной тест"); return r; }); app.post("/tests/:slug/sync", async (req, reply) => { if (!tests(req)) return reply.code(404).send({ error: "not_found" }); if (!sync) return reply.code(501).send({ error: "sync_not_configured" }); if (sync.isRunning) return reply.code(409).send({ error: "already_running" }); try { const r = await sync.run({ full: false }); audit?.info({ action: "sync", result: r.status, http: r.status === "ok" ? 200 : 502 }, "ручной тест"); return reply.code(r.status === "ok" ? 200 : 502).send(r); } catch (e) { if (e instanceof ReauthNeeded) { audit?.info({ action: "sync", result: "reauth_needed", http: 409 }, "ручной тест"); return reply.code(409).send({ error: "reauth_needed", message: e.message }); } audit?.info({ action: "sync", result: "sync_failed", http: 502 }, "ручной тест"); req.log.error({ err: String(e) }, "sync (tests)"); return reply.code(502).send({ error: "sync_failed" }); } }); /** Заметка администратора о ручном тесте: пишется в журнал сервиса. */ app.post("/tests/:slug/note", async (req, reply) => { if (!tests(req)) return reply.code(404).send({ error: "not_found" }); const text = String((req.body as { text?: string } | undefined)?.text ?? "").slice(0, 500).trim(); if (!text) return reply.code(400).send({ error: "empty" }); audit?.info({ action: "note", note: text }, "ручной тест"); return { ok: true }; }); app.get("/healthz", async () => ({ ok: true, time: new Date().toISOString() })); app.get("/callback", async (req, reply) => { const q = req.query as { code?: string; state?: string; realmId?: string; error?: string }; try { await auth.handleCallback(q); audit?.info({ action: "callback", result: "подключено" }, "ручной тест"); return reply.redirect("/api/qbo/connected?ok=1", 302); } catch (e) { audit?.info({ action: "callback", result: "отклонено", reason: String(e).slice(0, 160) }, "ручной тест"); req.log.warn({ err: String(e) }, "callback отклонён"); return reply.redirect("/api/qbo/connected?ok=0", 302); } }); /** Итоговая страница после возврата с Intuit. /callback отвечает 302 сюда (требование Intuit: адрес с code не отдаёт HTML-тело). */ app.get("/connected", async (req, reply) => { const ok = (req.query as { ok?: string }).ok === "1"; return ok ? reply.type("text/html").send(page("QuickBooks подключён", "Авторизация сохранена. Эту вкладку можно закрыть.")) : reply.code(400).type("text/html").send(page("Не удалось подключить QuickBooks", "Начните подключение заново. Причина записана в журнал сервиса.")); }); /** Ссылка авторизации (для администратора компании QuickBooks). */ app.post("/connect", async () => auth.startConnect()); app.get("/status", async () => auth.status()); /** Отключение: отзыв токена у Intuit и удаление сохранённых токенов. */ app.post("/disconnect", async () => auth.disconnect()); /** Действующий access token для других сервисов (только docker-сеть и токен сервиса). `?force=true` - обновить принудительно. */ app.post("/token", async (req, reply) => { try { const force = (req.query as { force?: string }).force === "true"; const t = await auth.getAccessToken({ force }); return { accessToken: t.accessToken, realmId: t.realmId, apiBase: t.apiBase, expiresAt: t.expiresAt.toISOString() }; } catch (e) { if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message }); req.log.error({ err: String(e) }, "получение токена"); return reply.code(502).send({ error: "token_error" }); } }); /** Полная загрузка зеркала QuickBooks в таблицы qbo_* (вызывает scheduler и ручной запуск). Ждёт итога: 200 ok, 502 ошибка, 409 уже идёт. */ app.post("/sync", async (req, reply) => { if (!sync) return reply.code(501).send({ error: "sync_not_configured" }); if (sync.isRunning) return reply.code(409).send({ error: "already_running" }); try { const r = await sync.run({ full: (req.query as { full?: string } | undefined)?.full === "1" }); return reply.code(r.status === "ok" ? 200 : 502).send(r); } catch (e) { if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message }); req.log.error({ err: String(e) }, "sync"); return reply.code(502).send({ error: "sync_failed" }); } }); app.post("/keepalive", async () => ({ result: await auth.keepAlive() })); return app; } /** Секретная часть адреса страницы тестов: стабильно выводится из служебного токена (токен остаётся только в настройках). */ export function testsSlug(token: string): string { return createHmac("sha256", token).update("qbo-tests-page").digest("hex").slice(0, 32); }