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

@@ -36,4 +36,4 @@
- vendor: created, deleted, merged, updated
- vendorcredit: created, deleted, updated
Страница ручных тестов: `https://services.khbuild.freeddns.org/api/qbo/tests` (форма открыта, действия требуют токен qbo_auth).
Страница ручных тестов: секретная ссылка `https://services.khbuild.freeddns.org/api/qbo/tests/<slug>` (slug выводится из служебного токена, адрес в `temp_keys/qbo_tests_url.txt`).

View File

@@ -4,11 +4,11 @@
# Manual testing
Выполняет Юрий в самом конце, на последней развёрнутой версии. Статусы: TBD, затем дата и done (ставлю я со слов Юрия «успех»). Всё делается в обычном браузере. Основная точка входа: страница https://services.khbuild.freeddns.org/api/qbo/tests (кнопки Статус, Подключить, Отключить, Синхронизация и поле заметки; нужен служебный токен qbo_auth, он вводится в поле и хранится только во вкладке; токен лежит в `temp_keys/qbo_tests_token.txt`).
Выполняет Юрий в самом конце, на последней развёрнутой версии. Статусы: TBD, затем дата и done (ставлю я со слов Юрия «успех»). Всё делается в обычном браузере. Основная точка входа: страница тестов по секретной ссылке (адрес в `temp_keys/qbo_tests_url.txt`, вида https://services.khbuild.freeddns.org/api/qbo/tests/<секрет>): кнопки Статус, Подключить, Отключить, Синхронизация и поле заметки. Ничего вводить не нужно: секрет входит в адрес и выводится из служебного токена; без правильного адреса страница и действия недоступны (404).
- M1. TBD. Подключение, отключение, повторное подключение на sandbox (анкета: Authorization 1). На /tests: (а) «Отключить», «Статус» (connected: false), «Подключить», в открывшейся вкладке Intuit войти администратором, выбрать sandbox-компанию, Connect; ожидается страница «QuickBooks подключён», затем «Статус» (connected: true) и «Синхронизация» проходит. (б) В https://app.sandbox.qbo.intuit.com отключить приложение (Apps, KHBuild_assistant, Disconnect); на /tests «Синхронизация»: ожидается 409 reauth_needed; затем «Отключить». (в) «Подключить» заново, пройти авторизацию, «Синхронизация» проходит.
- M2. TBD. Вебхуки (анкета: Accounting API 4). В https://developer.intuit.com приложение KHBuild_assistant, Webhooks, вкладка development: «Send test event», событие `qbo.bill.created.v1`, Send. Проверка по логам: я.
- M3. TBD. Изменение данных доходит до зеркала. В https://app.sandbox.qbo.intuit.com создать Bill (Expenses, Bills, Add bill), на /tests в поле заметки написать, что создано (сумма, вендор), «Отправить». Проверка по таблицам `qbo_*`: я.
- M1. TBD. Подключение, отключение, повторное подключение на sandbox (анкета: Authorization 1). На странице тестов: (а) «Отключить», «Статус» (connected: false), «Подключить», в открывшейся вкладке Intuit войти администратором, выбрать sandbox-компанию, Connect; ожидается страница «QuickBooks подключён», затем «Статус» (connected: true) и «Синхронизация» проходит. (б) В https://app.sandbox.qbo.intuit.com отключить приложение (Apps, KHBuild_assistant, Disconnect); на странице тестов «Синхронизация»: ожидается 409 reauth_needed; затем «Отключить». (в) «Подключить» заново, пройти авторизацию, «Синхронизация» проходит.
- M2. TBD. Вебхуки (анкета: Accounting API 4). 2026-11-23 Юрий отправил тест из портала (показал SUCCESS), но наш сервер ответил 415 из-за типа `application/cloudevents+json`; исправлено в тот же день (парсер и тест), тест из портала нужно повторить. В https://developer.intuit.com приложение KHBuild_assistant, Webhooks, вкладка development: «Send test event», событие `qbo.bill.created.v1`, Send. Проверка по логам: я.
- M3. TBD. Изменение данных доходит до зеркала. В https://app.sandbox.qbo.intuit.com создать Bill (Expenses, Bills, Add bill), на странице тестов в поле заметки написать, что создано (сумма, вендор), «Отправить». Проверка по таблицам `qbo_*`: я.
- M4. TBD. Страницы (окно инкогнито): https://services.khbuild.freeddns.org/legal/index.html, а также privacy.html, eula.html, connect.html, disconnect.html по тому же пути; текст читается, контакты верны.
- M5. Не требует Юрия (автоматически). После M1(в) я ставлю задачу по расписанию, через час с лишним запускается `claude -p`, проверяет `GET /status` (свежий `refreshedAt`, connected: true), лог в `temp/logs/`. Статус: TBD, результат сообщу.
- M6. done 2026-11-23. Security 4 (MFA): решение Юрия: двухфакторную аутентификацию не включаем; ответ: No.
@@ -28,6 +28,8 @@
- A7. Сценарии expired access token, expired refresh token, invalid grant, CSRF: автотесты. Статус: сделано (`service.test.ts`, `intuit-requirements.test.ts`).
- A8. Не использовать OAuth Playground и ручные токены. Статус: соблюдается.
- A9. Защита от случайного подключения чужой компании (по просьбе Юрия): настройка `qbo_auth.allowedRealmIds`; при возврате с Intuit realmId не из списка отклоняется до обмена кода (токены не выдаются), администратору уходит уведомление; тест есть. Сейчас список: sandbox-компания KHBuild (9341458717054536). При переходе на production добавить realmId боевой компании. Статус: сделано 2026-11-23.
## B. Обработка ошибок
- B1. Ошибки API (синтаксис, валидация, 401, 403, 429, 5xx): единый клиент `QboApi` (`api.ts`) с разбором Fault, повторами и тестами; чтение (`sync.ts`) и запись (`post`, с `requestid` для идемпотентных повторов) идут через него. Статус: сделано 2026-11-19.

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 () => {