qbo_auth: вебхуки Intuit (/webhook, подпись HMAC, фоновая загрузка по событиям); токены вебхуков в настройках
Some checks failed
ci / test (push) Successful in 40s
ci / deploy (push) Failing after 2m48s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 23:21:57 +03:00
parent dc224e375b
commit 2806941fb3
5 changed files with 159 additions and 3 deletions

View File

@@ -1,6 +1,13 @@
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>`;
@@ -9,14 +16,33 @@ const page = (title: string, text: string) =>
* Служебные ручки закрыты токеном (settings.json5 `qbo_auth.http.token`); открыты /healthz и /callback.
* /callback защищён одноразовым state; наружу (nginx services) публикуется только он: /api/qbo/callback.
*/
export function buildApi(auth: QboAuth, token: string, sync?: QboSync): FastifyInstance {
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") return;
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) => {