qbo_auth: вебхуки Intuit (/webhook, подпись HMAC, фоновая загрузка по событиям); токены вебхуков в настройках
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user