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) => {

View File

@@ -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();
});

View File

@@ -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<typeof qboAuthSchema>;

View File

@@ -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();
});
});

View File

@@ -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<typeof setTimeout> | null = null;
constructor(
private readonly run: () => Promise<void>,
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;
}
}