118 lines
7.6 KiB
TypeScript
118 lines
7.6 KiB
TypeScript
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 { ReauthNeeded, type QboAuth } from "./service.js";
|
||
import type { QboSync } from "./sync.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("синхронизация без действующей авторизации: 409 reauth_needed (и на /sync, и на странице тестов), а не 502", async () => {
|
||
const sync = { isRunning: false, run: async () => { throw new ReauthNeeded("нужна новая авторизация QuickBooks"); } } as unknown as QboSync;
|
||
const app = buildApi({} as QboAuth, "svc", sync);
|
||
const r1 = await app.inject({ method: "POST", url: "/sync", headers: { authorization: "Bearer svc" } });
|
||
expect(r1.statusCode).toBe(409);
|
||
expect(r1.json().error).toBe("reauth_needed");
|
||
const r2 = await app.inject({ method: "POST", url: `/tests/${testsSlug("svc")}/sync` });
|
||
expect(r2.statusCode).toBe(409);
|
||
});
|
||
|
||
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 audit = { info: vi.fn() };
|
||
const app = buildApi({} as QboAuth, "svc", undefined, undefined, audit);
|
||
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.body).toContain("Версия:");
|
||
expect(page.body).not.toContain("__BUILD__");
|
||
expect(page.body).toContain("sandbox.qbo.intuit.com/app/appcenter/myapps");
|
||
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);
|
||
expect(audit.info).toHaveBeenCalledWith({ action: "note", note: "Bill 12.50" }, "ручной тест");
|
||
});
|
||
|
||
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();
|
||
});
|
||
});
|
||
|
||
describe("версия сборки на странице тестов", () => {
|
||
it("показывает коммит и дату сборки из окружения", async () => {
|
||
const { renderTestsPage } = await import("./tests-page.js");
|
||
const html = renderTestsPage({ KHB_VERSION: "abc123def456", KHB_BUILD_DATE: "2026-11-23T07:20:00Z" } as NodeJS.ProcessEnv);
|
||
expect(html).toContain("commit/abc123def456");
|
||
expect(html).toContain("2026-11-23 07:20:00 UTC");
|
||
expect(renderTestsPage({} as NodeJS.ProcessEnv)).toContain("неизвестна");
|
||
});
|
||
});
|