Files
khb_microservices/packages/qbo_auth/src/webhook.test.ts
2026-11-23 09:28:24 +03:00

92 lines
5.9 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 { createHmac } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import { buildApi, testsSlug } 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("разбор CloudEvents: один объект и массив", () => {
const ev = { specversion: "1.0", type: "qbo.bill.created.v1", intuitentityid: "7", intuitaccountid: "R1" };
expect(parseWebhook(JSON.stringify(ev))).toEqual([{ realmId: "R1", name: "Bill", id: "7", operation: "Create" }]);
expect(parseWebhook(JSON.stringify([ev, { ...ev, type: "qbo.vendor.deleted.v1", intuitentityid: "8" }])).map((e) => `${e.name}:${e.operation}`)).toEqual(["Bill:Create", "Vendor:Delete"]);
});
it("страница тестов: только по секретному адресу, заголовки без кэша, заметка принимается", async () => {
const app = buildApi({} as QboAuth, "svc");
const slug = testsSlug("svc");
expect(slug).toMatch(/^[0-9a-f]{32}$/);
expect((await app.inject({ url: "/tests/wrong" })).statusCode).toBe(404);
expect((await app.inject({ url: "/tests/wrong/status" })).statusCode).toBe(404);
expect((await app.inject({ method: "POST", url: "/tests/wrong/disconnect" })).statusCode).toBe(404);
const page = await app.inject({ url: `/tests/${slug}` });
expect(page.statusCode).toBe(200);
expect(page.body).toContain("location.pathname");
expect(page.headers["cache-control"]).toBe("no-cache, no-store");
expect(page.headers["referrer-policy"]).toBe("no-referrer");
const h = { "content-type": "application/json" };
expect((await app.inject({ method: "POST", url: `/tests/${slug}/note`, headers: h, payload: { text: "Bill 12.50" } })).statusCode).toBe(200);
expect((await app.inject({ method: "POST", url: `/tests/${slug}/note`, headers: h, payload: { text: " " } })).statusCode).toBe(400);
});
it("вебхук с типом application/cloudevents+json принимается (раньше было 415)", async () => {
const onEvents = vi.fn();
const app = buildApi({} as QboAuth, "svc", undefined, { tokens: ["tok"], onEvents });
const body = JSON.stringify({ specversion: "1.0", type: "qbo.bill.created.v1", intuitentityid: "1234", intuitaccountid: "310687" });
const r = await app.inject({ method: "POST", url: "/webhook", headers: { "content-type": "application/cloudevents+json", "intuit-signature": sign(body, "tok") }, payload: body });
expect(r.statusCode).toBe(200);
expect(onEvents).toHaveBeenCalledTimes(1);
});
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();
});
});