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

View File

@@ -21,6 +21,7 @@ const auth = new QboAuth({
redirectUri: s.redirectUri,
scope: s.scope,
keepAliveHours: s.keepAliveHours,
allowedRealmIds: s.allowedRealmIds,
endpoints: discoveryEndpoints(s.environment, async (url) => (await fetch(url, { headers: { Accept: "application/json" } })).json(), Date.now, (msg, extra) => log.warn(extra ?? {}, msg)),
notify: async (text) => {
await itNotify(common, text).catch(() => false);

View File

@@ -123,6 +123,26 @@ describe("токены", () => {
});
});
describe("защита от чужой компании", () => {
it("realmId вне списка отклоняется до обмена кода; из списка подключается", async () => {
const st = new MemoryStore();
const f = fakeFetch([{ body: tokens(1) }]);
const notes: string[] = [];
const auth = new QboAuth({
store: st, fetchFn: f.fn, env: "sandbox", clientId: "cid", clientSecret: "csec", redirectUri: "https://x/cb", scope: "s", keepAliveHours: 20,
allowedRealmIds: ["R-OK"], notify: async (t) => { notes.push(t); },
});
const s1 = new URL((await auth.startConnect()).url).searchParams.get("state")!;
await expect(auth.handleCallback({ code: "c", state: s1, realmId: "R-OTHER" })).rejects.toThrow(/allowedRealmIds/);
expect(f.calls.length).toBe(0);
expect(notes[0]).toContain("R-OTHER");
expect(await st.read("sandbox")).toBeNull();
const s2 = new URL((await auth.startConnect()).url).searchParams.get("state")!;
await auth.handleCallback({ code: "c", state: s2, realmId: "R-OK" });
expect((await st.read("sandbox"))?.realmId).toBe("R-OK");
});
});
describe("HTTP", () => {
it("служебные ручки требуют токен; /healthz и /callback открыты; в status нет секретов", async () => {
const ctx = mk([{ body: tokens(1) }]);

View File

@@ -16,6 +16,8 @@ export interface QboAuthDeps {
notify?: (text: string) => Promise<void>;
/** Адреса OAuth из discovery-документа (по умолчанию запасные константы). */
endpoints?: () => Promise<Endpoints>;
/** Защита от случайного подключения чужой компании: если список не пуст, принимается только realmId из него. */
allowedRealmIds?: string[];
}
/** Человек должен заново авторизовать приложение (или подключение ещё не делали). */
@@ -42,6 +44,10 @@ export class QboAuth {
if (!env) throw new Error("неизвестный или просроченный state: начните подключение заново");
if (q.error) throw new Error(`Intuit вернул ошибку: ${q.error}`);
if (!q.code || !q.realmId) throw new Error("в ответе Intuit нет code или realmId");
if (this.d.allowedRealmIds?.length && !this.d.allowedRealmIds.includes(q.realmId)) {
await this.d.notify?.(`QuickBooks: попытка подключить неразрешённую компанию (realmId ${q.realmId}); подключение отклонено`).catch(() => undefined);
throw new Error(`компания ${q.realmId} не входит в список разрешённых (allowedRealmIds); код авторизации не обменивался`);
}
const t = await exchangeCode(this.d.fetchFn, this.creds(), q.code, this.d.redirectUri, (await this.ep()).token);
const conn = this.fromTokens(env, q.realmId, t, this.now());
await this.d.store.withLock(env, (c) => c.save(conn));

View File

@@ -17,6 +17,8 @@ export const qboAuthSchema = z.object({
/** Обновлять токены, если последнее обновление старше, часов (refresh token скользящий, до 100 дней). */
keepAliveHours: z.number().default(20),
/** Verifier token вебхуков Intuit (раздел Webhooks приложения: отдельный для development и production); пусто - вебхуки отклоняются. */
/** Компании QuickBooks (realmId), которые разрешено подключать (sandbox и production); пусто - без ограничения. */
allowedRealmIds: z.array(z.string().min(1)).default([]),
webhookVerifierTokens: z.array(z.string().min(1)).default([]),
});
export type QboAuthSettings = z.infer<typeof qboAuthSchema>;

View File

@@ -1,9 +1,7 @@
/** Страница ручных тестов для администратора (/api/qbo/tests). Сама страница открыта (только форма), все действия требуют служебный токен qbo_auth, который вводится в поле и хранится в sessionStorage браузера. */
/** Страница ручных тестов для администратора: секретный адрес /api/qbo/tests/<slug> (slug выводится из служебного токена; без него страница и действия недоступны). */
export const TESTS_PAGE = `<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Тесты qbo_auth</title>
<style>body{font:15px/1.5 system-ui,sans-serif;max-width:760px;margin:24px auto;padding:0 16px}button{margin:4px 4px 4px 0;padding:6px 12px}input,textarea{width:100%;box-sizing:border-box;margin:4px 0}pre{background:#f3f4f6;padding:10px;white-space:pre-wrap;word-break:break-all}h2{margin-top:24px}</style></head><body>
<h1>Ручные тесты QuickBooks (qbo_auth)</h1>
<p>Служебный токен qbo_auth (хранится только в этой вкладке):</p>
<input id="tok" type="password" autocomplete="off" placeholder="токен">
<h2>M1. Подключение</h2>
<p>1) «Отключить» (удаляет токены и отзывает их у Intuit). 2) «Подключить» и пройти авторизацию в открывшейся вкладке. 3) «Статус». 4) Отключите приложение в QuickBooks (Apps, KHBuild_assistant, Disconnect) и нажмите «Синхронизация»: ожидается 409 reauth_needed.</p>
<button data-a="status" data-m="GET">Статус</button>
@@ -17,11 +15,10 @@ export const TESTS_PAGE = `<!doctype html><html lang="ru"><head><meta charset="u
<pre id="out">Результат появится здесь.</pre>
<script>
const $=id=>document.getElementById(id), out=$('out');
try{$('tok').value=sessionStorage.getItem('qbo_tok')||''}catch(e){}
const base=location.pathname.replace(/[/]$/,"");
async function call(a,m,body){
try{sessionStorage.setItem('qbo_tok',$('tok').value)}catch(e){}
out.textContent='...';
const r=await fetch('/api/qbo/tests/'+a,{method:m,headers:{'Authorization':'Bearer '+$('tok').value,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});
const r=await fetch(base+'/'+a,{method:m,headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});
const t=await r.text(); let j; try{j=JSON.parse(t)}catch(e){}
out.textContent=r.status+' '+(j?JSON.stringify(j,null,2):t);
if(a==='connect'&&j&&j.url){const l=document.createElement('a');l.href=j.url;l.target='_blank';l.textContent='Открыть авторизацию Intuit';out.appendChild(document.createElement('br'));out.appendChild(l);window.open(j.url,'_blank')}

View File

@@ -1,6 +1,6 @@
import { createHmac } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import { buildApi } from "./http-api.js";
import { buildApi, testsSlug } from "./http-api.js";
import { parseWebhook, SyncTrigger, verifyWebhook } from "./webhook.js";
import type { QboAuth } from "./service.js";
@@ -31,17 +31,30 @@ describe("вебхук Intuit", () => {
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 () => {
it("страница тестов: только по секретному адресу, заголовки без кэша, заметка принимается", async () => {
const app = buildApi({} as QboAuth, "svc");
const page = await app.inject({ url: "/tests" });
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");
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);
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 () => {