From 6cca0c508b8aadf71012fba41266b2efdf78319a Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Mon, 23 Nov 2026 08:48:28 +0300 Subject: [PATCH] =?UTF-8?q?qbo=5Fauth:=20=D1=81=D1=82=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=86=D0=B0=20=D1=80=D1=83=D1=87=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2=20/tests,=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B7=D0=B1=D0=BE=D1=80=20CloudEvents=20=D0=B2=20=D0=B2=D0=B5?= =?UTF-8?q?=D0=B1=D1=85=D1=83=D0=BA=D0=B5;=20=D1=81=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=BE=D0=BA=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2=D1=8B=D1=85?= =?UTF-8?q?=20=D1=81=D0=BE=D0=B1=D1=8B=D1=82=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .../08-qbo-webhook-test-events.md | 39 +++++++++++++++++++ packages/qbo_auth/src/http-api.ts | 28 ++++++++++++- packages/qbo_auth/src/tests-page.ts | 31 +++++++++++++++ packages/qbo_auth/src/webhook.test.ts | 16 ++++++++ packages/qbo_auth/src/webhook.ts | 15 +++++-- 5 files changed, 125 insertions(+), 4 deletions(-) create mode 100644 docs/agent_memories/08-qbo-webhook-test-events.md create mode 100644 packages/qbo_auth/src/tests-page.ts diff --git a/docs/agent_memories/08-qbo-webhook-test-events.md b/docs/agent_memories/08-qbo-webhook-test-events.md new file mode 100644 index 0000000..39d4a4f --- /dev/null +++ b/docs/agent_memories/08-qbo-webhook-test-events.md @@ -0,0 +1,39 @@ +# Тестовые события вебхуков Intuit (portal, Send test event) + +Портал Intuit (приложение KHBuild_assistant, Webhooks, development) включён в формате **cloud events** («Enable cloud event payload format»): тело содержит `type` вида `qbo.bill.created.v1`, `intuitentityid`, `intuitaccountid` (realm). `parseWebhook` в `qbo_auth` понимает оба формата (классический eventNotifications и CloudEvents, объект или массив). + +Для теста M2 слать: `qbo.bill.created.v1` (Bill входит в подписки). Ожидаем 200 от `/api/qbo/webhook` и в логах `khb-qbo-auth` запись «вебхук QuickBooks». + +Полный список типов, доступных в «Send test event» (шаблон `qbo.<объект>.<действие>.v1`): +- account: created, deleted, merged, updated +- bill: created, deleted, updated +- billpayment: created, deleted, updated, void +- budget: created, updated +- changeorder: created, deleted, updated +- class: created, deleted, merged, updated +- creditmemo: created, deleted, emailed, updated, void +- currency: created, deleted, updated +- customer: created, deleted, merged, updated +- department: created, merged, updated +- deposit: created, deleted, updated +- employee: created, deleted, merged, updated +- estimate: created, deleted, emailed, updated +- invoice: created, deleted, emailed, updated, void +- item: created, deleted, merged, updated +- journalcode: created, updated +- journalentry: created, deleted, updated +- payment: created, deleted, emailed, updated, void +- paymentmethod: created, merged, updated +- preferences: updated +- purchase: created, deleted, updated, void +- purchaseorder: created, deleted, emailed, updated +- refundreceipt: created, deleted, emailed, updated, void +- salesreceipt: created, deleted, emailed, updated, void +- taxagency: created, updated +- term: created, updated +- timeactivity: created, deleted, updated +- transfer: created, deleted, updated, void +- vendor: created, deleted, merged, updated +- vendorcredit: created, deleted, updated + +Страница ручных тестов: `https://services.khbuild.freeddns.org/api/qbo/tests` (форма открыта, действия требуют токен qbo_auth). diff --git a/packages/qbo_auth/src/http-api.ts b/packages/qbo_auth/src/http-api.ts index cf11e4f..65bfe28 100644 --- a/packages/qbo_auth/src/http-api.ts +++ b/packages/qbo_auth/src/http-api.ts @@ -1,6 +1,7 @@ import Fastify, { type FastifyInstance } from "fastify"; import { QboAuth, ReauthNeeded } from "./service.js"; import type { QboSync } from "./sync.js"; +import { TESTS_PAGE } from "./tests-page.js"; import { parseWebhook, verifyWebhook } from "./webhook.js"; export interface WebhookOptions { @@ -29,7 +30,7 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: }); app.addHook("onRequest", async (req, reply) => { const path = req.url.split("?")[0]; - if (path === "/healthz" || path === "/callback" || path === "/webhook") return; + if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/tests") return; if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" }); }); @@ -43,6 +44,31 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?: return reply.code(200).send({ ok: true, events: events.length }); }); + /** Страница ручных тестов (форма открыта, действия /tests/* закрыты Bearer-токеном). Наружу: /api/qbo/tests. */ + app.get("/tests", async (_req, reply) => reply.type("text/html").send(TESTS_PAGE)); + app.get("/tests/status", async () => auth.status()); + app.post("/tests/connect", async () => auth.startConnect()); + app.post("/tests/disconnect", async () => auth.disconnect()); + app.post("/tests/sync", async (req, reply) => { + if (!sync) return reply.code(501).send({ error: "sync_not_configured" }); + if (sync.isRunning) return reply.code(409).send({ error: "already_running" }); + try { + const r = await sync.run({ full: false }); + return reply.code(r.status === "ok" ? 200 : 502).send(r); + } catch (e) { + if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message }); + req.log.error({ err: String(e) }, "sync (tests)"); + return reply.code(502).send({ error: "sync_failed" }); + } + }); + /** Заметка администратора о ручном тесте: пишется в журнал сервиса. */ + app.post("/tests/note", async (req, reply) => { + const text = String((req.body as { text?: string } | undefined)?.text ?? "").slice(0, 500).trim(); + if (!text) return reply.code(400).send({ error: "empty" }); + req.log.info({ note: text }, "заметка ручного теста"); + return { ok: true }; + }); + app.get("/healthz", async () => ({ ok: true, time: new Date().toISOString() })); app.get("/callback", async (req, reply) => { diff --git a/packages/qbo_auth/src/tests-page.ts b/packages/qbo_auth/src/tests-page.ts new file mode 100644 index 0000000..faf3e08 --- /dev/null +++ b/packages/qbo_auth/src/tests-page.ts @@ -0,0 +1,31 @@ +/** Страница ручных тестов для администратора (/api/qbo/tests). Сама страница открыта (только форма), все действия требуют служебный токен qbo_auth, который вводится в поле и хранится в sessionStorage браузера. */ +export const TESTS_PAGE = `Тесты qbo_auth + +

Ручные тесты QuickBooks (qbo_auth)

+

Служебный токен qbo_auth (хранится только в этой вкладке):

+ +

M1. Подключение

+

1) «Отключить» (удаляет токены и отзывает их у Intuit). 2) «Подключить» и пройти авторизацию в открывшейся вкладке. 3) «Статус». 4) Отключите приложение в QuickBooks (Apps, KHBuild_assistant, Disconnect) и нажмите «Синхронизация»: ожидается 409 reauth_needed.

+ + + + +

M3. Заметка

+

Например: «создал Bill на сумму 123.45 для вендора X».

+ + +
Результат появится здесь.
+`; diff --git a/packages/qbo_auth/src/webhook.test.ts b/packages/qbo_auth/src/webhook.test.ts index e36b9ec..10fcebe 100644 --- a/packages/qbo_auth/src/webhook.test.ts +++ b/packages/qbo_auth/src/webhook.test.ts @@ -25,6 +25,22 @@ describe("вебхук Intuit", () => { 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("страница /tests открыта, действия /tests/* закрыты токеном, заметка принимается", async () => { + const app = buildApi({} as QboAuth, "svc"); + expect((await app.inject({ url: "/tests" })).statusCode).toBe(200); + expect((await app.inject({ url: "/tests/status" })).statusCode).toBe(401); + expect((await app.inject({ method: "POST", url: "/tests/disconnect" })).statusCode).toBe(401); + const h = { authorization: "Bearer svc", "content-type": "application/json" }; + expect((await app.inject({ method: "POST", url: "/tests/note", headers: h, payload: { text: "Bill 12.50" } })).statusCode).toBe(200); + expect((await app.inject({ method: "POST", url: "/tests/note", headers: h, payload: { text: " " } })).statusCode).toBe(400); + }); + it("маршрут /webhook: без токенов 503, плохая подпись 401, верная 200 и вызов onEvents без Bearer-токена сервиса", async () => { const onEvents = vi.fn(); const auth = {} as QboAuth; diff --git a/packages/qbo_auth/src/webhook.ts b/packages/qbo_auth/src/webhook.ts index 208d23e..35af526 100644 --- a/packages/qbo_auth/src/webhook.ts +++ b/packages/qbo_auth/src/webhook.ts @@ -17,13 +17,22 @@ export interface WebhookEntity { operation: string; } -/** Плоский список изменённых объектов из тела вебхука; чужой формат даёт пустой список. */ +const CE_OPS: Record = { created: "Create", updated: "Update", deleted: "Delete", merged: "Merge", void: "Void", emailed: "Emailed" }; + +/** Плоский список изменённых объектов из тела вебхука: классический формат (eventNotifications) и CloudEvents (type вида qbo.bill.created.v1, один объект или массив); чужой формат даёт пустой список. */ 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) => + const j = JSON.parse(rawBody) as unknown; + const classic = (j as { eventNotifications?: Array<{ realmId?: string; dataChangeEvent?: { entities?: Array<{ name?: string; id?: string; operation?: string }> } }> }).eventNotifications; + const out: WebhookEntity[] = (classic ?? []).flatMap((n) => (n.dataChangeEvent?.entities ?? []).map((e) => ({ realmId: String(n.realmId ?? ""), name: String(e.name ?? ""), id: String(e.id ?? ""), operation: String(e.operation ?? "") })), ); + for (const e of Array.isArray(j) ? j : [j]) { + const c = e as { type?: string; intuitentityid?: string; intuitaccountid?: string }; + const m = /^qbo\.([a-z]+)\.([a-z]+)\.v\d+$/.exec(String(c?.type ?? "")); + if (m && m[1] && m[2]) out.push({ realmId: String(c.intuitaccountid ?? ""), name: m[1].charAt(0).toUpperCase() + m[1].slice(1), id: String(c.intuitentityid ?? ""), operation: CE_OPS[m[2]] ?? m[2] }); + } + return out; } catch { return []; }