Files
khb_microservices/packages/qbo_auth/src/http-api.ts
2026-11-19 20:18:06 +03:00

92 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Fastify, { type FastifyInstance } from "fastify";
import { QboAuth, ReauthNeeded } from "./service.js";
import type { QboSync } from "./sync.js";
import { parseWebhook, verifyWebhook } from "./webhook.js";
export interface WebhookOptions {
tokens: string[];
/** Вызывается после проверки подписи, если в вебхуке есть изменённые объекты. */
onEvents(events: ReturnType<typeof parseWebhook>): void;
}
const page = (title: string, text: string) =>
`<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="robots" content="noindex"><title>${title}</title><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1>${title}</h1><p>${text}</p></body></html>`;
/**
* Служебные ручки закрыты токеном (settings.json5 `qbo_auth.http.token`); открыты /healthz и /callback.
* /callback защищён одноразовым state; наружу (nginx services) публикуется только он: /api/qbo/callback.
*/
export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: WebhookOptions): 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);
}
});
app.addHook("onRequest", async (req, reply) => {
const path = req.url.split("?")[0];
if (path === "/healthz" || path === "/callback" || path === "/webhook") 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 });
});
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);
return reply.type("text/html").send(page("QuickBooks подключён", "Авторизация сохранена. Эту вкладку можно закрыть."));
} catch (e) {
req.log.warn({ err: String(e) }, "callback отклонён");
return 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;
}