From 2806941fb365015043cfcf772bfadec0b80e4c56 Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Wed, 18 Nov 2026 23:21:57 +0300 Subject: [PATCH] =?UTF-8?q?qbo=5Fauth:=20=D0=B2=D0=B5=D0=B1=D1=85=D1=83?= =?UTF-8?q?=D0=BA=D0=B8=20Intuit=20(/webhook,=20=D0=BF=D0=BE=D0=B4=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D1=8C=20HMAC,=20=D1=84=D0=BE=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA=D0=B0?= =?UTF-8?q?=20=D0=BF=D0=BE=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D1=8F?= =?UTF-8?q?=D0=BC);=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=D1=8B=20=D0=B2=D0=B5?= =?UTF-8?q?=D0=B1=D1=85=D1=83=D0=BA=D0=BE=D0=B2=20=D0=B2=20=D0=BD=D0=B0?= =?UTF-8?q?=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- packages/qbo_auth/src/http-api.ts | 30 +++++++++++++- packages/qbo_auth/src/main.ts | 17 +++++++- packages/qbo_auth/src/settings.ts | 2 + packages/qbo_auth/src/webhook.test.ts | 59 +++++++++++++++++++++++++++ packages/qbo_auth/src/webhook.ts | 54 ++++++++++++++++++++++++ 5 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 packages/qbo_auth/src/webhook.test.ts create mode 100644 packages/qbo_auth/src/webhook.ts diff --git a/packages/qbo_auth/src/http-api.ts b/packages/qbo_auth/src/http-api.ts index 9371858..5841bed 100644 --- a/packages/qbo_auth/src/http-api.ts +++ b/packages/qbo_auth/src/http-api.ts @@ -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): void; +} const page = (title: string, text: string) => `${title}

${title}

${text}

`; @@ -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) => { diff --git a/packages/qbo_auth/src/main.ts b/packages/qbo_auth/src/main.ts index 8e553f0..c4a4929 100644 --- a/packages/qbo_auth/src/main.ts +++ b/packages/qbo_auth/src/main.ts @@ -1,6 +1,7 @@ import { createLogger, createPool, itNotify, loadServiceSettings, withTx } from "khb_common"; import { parseKey } from "./crypto.js"; import { buildApi } from "./http-api.js"; +import { SyncTrigger } from "./webhook.js"; import { QboAuth } from "./service.js"; import { qboAuthSchema } from "./settings.js"; import { PgStore } from "./store.js"; @@ -31,7 +32,20 @@ const sync = new QboSync({ environment: s.environment, log: (msg, extra) => log.info(extra ?? {}, msg), }); -const app = buildApi(auth, s.http.token, sync); +const trigger = new SyncTrigger( + async () => { + const r = await sync.run().catch((e) => ({ status: "error", error: String(e) })); + log.info({ status: r.status }, "загрузка по вебхуку"); + }, + () => sync.isRunning, +); +const app = buildApi(auth, s.http.token, sync, { + tokens: s.webhookVerifierTokens, + onEvents: (events) => { + log.info({ count: events.length, entities: [...new Set(events.map((e) => `${e.name}:${e.operation}`))].slice(0, 20) }, "вебхук QuickBooks"); + trigger.poke(); + }, +}); await app.listen({ host: s.http.host, port: s.http.port }); log.info({ port: s.http.port, environment: s.environment }, "qbo_auth запущен"); @@ -39,5 +53,6 @@ log.info({ port: s.http.port, environment: s.environment }, "qbo_auth запущ const timer = setInterval(() => void auth.keepAlive().catch((e) => log.error({ err: String(e) }, "keepalive")), 60 * 60_000); process.on("SIGTERM", () => { clearInterval(timer); + trigger.stop(); void app.close(); }); diff --git a/packages/qbo_auth/src/settings.ts b/packages/qbo_auth/src/settings.ts index 5e1c1a4..209b9e7 100644 --- a/packages/qbo_auth/src/settings.ts +++ b/packages/qbo_auth/src/settings.ts @@ -16,5 +16,7 @@ export const qboAuthSchema = z.object({ encryptionKey: z.string().min(32), /** Обновлять токены, если последнее обновление старше, часов (refresh token скользящий, до 100 дней). */ keepAliveHours: z.number().default(20), + /** Verifier token вебхуков Intuit (раздел Webhooks приложения: отдельный для development и production); пусто - вебхуки отклоняются. */ + webhookVerifierTokens: z.array(z.string().min(1)).default([]), }); export type QboAuthSettings = z.infer; diff --git a/packages/qbo_auth/src/webhook.test.ts b/packages/qbo_auth/src/webhook.test.ts new file mode 100644 index 0000000..e36b9ec --- /dev/null +++ b/packages/qbo_auth/src/webhook.test.ts @@ -0,0 +1,59 @@ +import { createHmac } from "node:crypto"; +import { describe, expect, it, vi } from "vitest"; +import { buildApi } from "./http-api.js"; +import { parseWebhook, SyncTrigger, verifyWebhook } from "./webhook.js"; +import type { QboAuth } from "./service.js"; + +const BODY = JSON.stringify({ eventNotifications: [{ realmId: "R1", dataChangeEvent: { entities: [{ name: "Bill", id: "5", operation: "Create", lastUpdated: "2026-11-18T10:00:00Z" }, { name: "Purchase", id: "9", operation: "Update" }] } }] }); +const sign = (body: string, token: string) => createHmac("sha256", token).update(body).digest("base64"); + +describe("вебхук Intuit", () => { + it("подпись: верный токен (в том числе второй из списка) проходит, чужой, пустой и повреждённая подпись - нет", () => { + expect(verifyWebhook(BODY, sign(BODY, "tok-prod"), ["tok-dev", "tok-prod"])).toBe(true); + expect(verifyWebhook(BODY, sign(BODY, "other"), ["tok-prod"])).toBe(false); + expect(verifyWebhook(BODY + " ", sign(BODY, "tok-prod"), ["tok-prod"])).toBe(false); + expect(verifyWebhook(BODY, undefined, ["tok-prod"])).toBe(false); + expect(verifyWebhook(BODY, sign(BODY, "tok-prod"), [])).toBe(false); + }); + + it("разбор тела: плоский список изменённых объектов, чужой формат - пусто", () => { + expect(parseWebhook(BODY)).toEqual([ + { realmId: "R1", name: "Bill", id: "5", operation: "Create" }, + { realmId: "R1", name: "Purchase", id: "9", operation: "Update" }, + ]); + expect(parseWebhook("не json")).toEqual([]); + expect(parseWebhook("{}")).toEqual([]); + }); + + it("маршрут /webhook: без токенов 503, плохая подпись 401, верная 200 и вызов onEvents без Bearer-токена сервиса", async () => { + const onEvents = vi.fn(); + const auth = {} as QboAuth; + const none = buildApi(auth, "svc", undefined, { tokens: [], onEvents }); + expect((await none.inject({ method: "POST", url: "/webhook", headers: { "content-type": "application/json" }, payload: BODY })).statusCode).toBe(503); + const app = buildApi(auth, "svc", undefined, { tokens: ["tok-prod"], onEvents }); + const h = { "content-type": "application/json" }; + expect((await app.inject({ method: "POST", url: "/webhook", headers: { ...h, "intuit-signature": sign(BODY, "bad") }, payload: BODY })).statusCode).toBe(401); + expect(onEvents).not.toHaveBeenCalled(); + const ok = await app.inject({ method: "POST", url: "/webhook", headers: { ...h, "intuit-signature": sign(BODY, "tok-prod") }, payload: BODY }); + expect(ok.statusCode).toBe(200); + expect(ok.json()).toEqual({ ok: true, events: 2 }); + expect(onEvents).toHaveBeenCalledTimes(1); + // остальные ручки по-прежнему закрыты токеном, JSON в них разбирается как раньше + expect((await app.inject({ method: "GET", url: "/status" })).statusCode).toBe(401); + }); + + it("SyncTrigger: пачка вызовов склеивается в один запуск; если загрузка идёт - ждёт", async () => { + vi.useFakeTimers(); + let busy = true; + const run = vi.fn(async () => undefined); + const t = new SyncTrigger(run, () => busy, 1000); + t.poke(); t.poke(); t.poke(); + await vi.advanceTimersByTimeAsync(1000); + expect(run).not.toHaveBeenCalled(); + busy = false; + await vi.advanceTimersByTimeAsync(1000); + expect(run).toHaveBeenCalledTimes(1); + t.stop(); + vi.useRealTimers(); + }); +}); diff --git a/packages/qbo_auth/src/webhook.ts b/packages/qbo_auth/src/webhook.ts new file mode 100644 index 0000000..208d23e --- /dev/null +++ b/packages/qbo_auth/src/webhook.ts @@ -0,0 +1,54 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; + +/** Подпись вебхука Intuit: заголовок intuit-signature = base64(HMAC-SHA256(тело, verifier token)). Токенов может быть несколько (development и production). */ +export function verifyWebhook(rawBody: string, signature: string | undefined, tokens: string[]): boolean { + if (!signature || tokens.length === 0) return false; + const got = Buffer.from(signature, "base64"); + return tokens.some((t) => { + const want = createHmac("sha256", t).update(rawBody).digest(); + return want.length === got.length && timingSafeEqual(want, got); + }); +} + +export interface WebhookEntity { + realmId: string; + name: string; + id: string; + operation: string; +} + +/** Плоский список изменённых объектов из тела вебхука; чужой формат даёт пустой список. */ +export function parseWebhook(rawBody: string): WebhookEntity[] { + try { + const j = JSON.parse(rawBody) as { eventNotifications?: Array<{ realmId?: string; dataChangeEvent?: { entities?: Array<{ name?: string; id?: string; operation?: string }> } }> }; + return (j.eventNotifications ?? []).flatMap((n) => + (n.dataChangeEvent?.entities ?? []).map((e) => ({ realmId: String(n.realmId ?? ""), name: String(e.name ?? ""), id: String(e.id ?? ""), operation: String(e.operation ?? "") })), + ); + } catch { + return []; + } +} + +/** Склеивает пачку вебхуков в один запуск загрузки через delayMs; если загрузка уже идёт, повторяет попытку позже. */ +export class SyncTrigger { + private timer: ReturnType | null = null; + constructor( + private readonly run: () => Promise, + private readonly busy: () => boolean, + private readonly delayMs = 10_000, + ) {} + + poke(): void { + if (this.timer) return; + this.timer = setTimeout(() => { + this.timer = null; + if (this.busy()) return this.poke(); + void this.run(); + }, this.delayMs); + } + + stop(): void { + if (this.timer) clearTimeout(this.timer); + this.timer = null; + } +}