qbo_auth: вебхук cloudevents+json (был 415), страница тестов по секретной ссылке, allowedRealmIds; требования Intuit
All checks were successful
ci / test (push) Successful in 36s
ci / deploy (push) Successful in 2m37s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 09:28:24 +03:00
parent e90b9f352d
commit 9a1a2a8a6b
9 changed files with 85 additions and 28 deletions

View File

@@ -1,3 +1,4 @@
import { createHmac } from "node:crypto";
import Fastify, { type FastifyInstance } from "fastify";
import { QboAuth, ReauthNeeded } from "./service.js";
import type { QboSync } from "./sync.js";
@@ -35,9 +36,13 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
reply.header("Referrer-Policy", "no-referrer");
reply.header("X-Content-Type-Options", "nosniff");
});
// CloudEvents-вебхуки Intuit приходят с типом application/cloudevents+json (и batch-вариантом): подпись считается по сырой строке
app.addContentTypeParser(/^application\/cloudevents(-batch)?\+json/i, { parseAs: "string" }, (_req, body, done) => done(null, body));
const slug = testsSlug(token);
app.addHook("onRequest", async (req, reply) => {
const path = req.url.split("?")[0];
if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/tests" || path === "/connected") return;
const path = req.url.split("?")[0] ?? "";
if (path === "/healthz" || path === "/callback" || path === "/webhook" || path === "/connected") return;
if (path.startsWith("/tests/")) return; // защита по секретному адресу (см. ниже)
if (req.headers.authorization !== `Bearer ${token}`) return reply.code(401).send({ error: "unauthorized" });
});
@@ -51,12 +56,17 @@ 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) => {
/**
* Страница ручных тестов: секретный адрес /tests/<slug> (slug выводится из служебного токена, вводить ничего не нужно); при неверном slug - 404.
* Наружу: /api/qbo/tests/<slug>.
*/
const tests = (req: { params: unknown }): boolean => (req.params as { slug?: string }).slug === slug;
app.get("/tests/:slug", async (req, reply) => (tests(req) ? reply.type("text/html").send(TESTS_PAGE) : reply.code(404).send({ error: "not_found" })));
app.get("/tests/:slug/status", async (req, reply) => (tests(req) ? auth.status() : reply.code(404).send({ error: "not_found" })));
app.post("/tests/:slug/connect", async (req, reply) => (tests(req) ? auth.startConnect() : reply.code(404).send({ error: "not_found" })));
app.post("/tests/:slug/disconnect", async (req, reply) => (tests(req) ? auth.disconnect() : reply.code(404).send({ error: "not_found" })));
app.post("/tests/:slug/sync", async (req, reply) => {
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
if (!sync) return reply.code(501).send({ error: "sync_not_configured" });
if (sync.isRunning) return reply.code(409).send({ error: "already_running" });
try {
@@ -69,7 +79,8 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
}
});
/** Заметка администратора о ручном тесте: пишется в журнал сервиса. */
app.post("/tests/note", async (req, reply) => {
app.post("/tests/:slug/note", async (req, reply) => {
if (!tests(req)) return reply.code(404).send({ error: "not_found" });
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 }, "заметка ручного теста");
@@ -129,3 +140,8 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync, webhook?:
app.post("/keepalive", async () => ({ result: await auth.keepAlive() }));
return app;
}
/** Секретная часть адреса страницы тестов: стабильно выводится из служебного токена (токен остаётся только в настройках). */
export function testsSlug(token: string): string {
return createHmac("sha256", token).update("qbo-tests-page").digest("hex").slice(0, 32);
}