qbo_auth: discovery-документ, клиент API с разбором Fault, отключение с отзывом токена; анкета и требования Intuit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
171
packages/qbo_auth/src/intuit-requirements.test.ts
Normal file
171
packages/qbo_auth/src/intuit-requirements.test.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { QboApi, QboApiError, parseFault } from "./api.js";
|
||||
import { DISCOVERY_URL, FALLBACK_ENDPOINTS, discoveryEndpoints } from "./discovery.js";
|
||||
import { intuitTid, type FetchFn } from "./oauth.js";
|
||||
import { QboAuth } from "./service.js";
|
||||
import { MemoryStore } from "./store.js";
|
||||
|
||||
type Resp = { status: number; body?: unknown; tid?: string };
|
||||
|
||||
/** Заглушка API QuickBooks: ответы по очереди, запоминает запросы. */
|
||||
function mkApi(responses: Resp[]) {
|
||||
const calls: Array<{ url: string; method: string; body?: string }> = [];
|
||||
const logs: Array<Record<string, unknown>> = [];
|
||||
const forced: boolean[] = [];
|
||||
const api = new QboApi({
|
||||
getToken: async (o) => { forced.push(!!o?.force); return { accessToken: "at", realmId: "R1", apiBase: "https://api.test" }; },
|
||||
fetchFn: async (url, init) => {
|
||||
calls.push({ url, method: init.method, body: init.body });
|
||||
const r = responses.shift() ?? { status: 500 };
|
||||
return { ok: r.status < 400, status: r.status, json: async () => r.body ?? {}, headers: { get: (n: string) => (n === "intuit_tid" ? (r.tid ?? null) : null) } };
|
||||
},
|
||||
sleep: async () => undefined,
|
||||
log: (_m, extra) => { logs.push(extra ?? {}); },
|
||||
});
|
||||
return { api, calls, logs, forced };
|
||||
}
|
||||
|
||||
const fault = (type: string, code: string, message: string, detail = "") => ({ Fault: { type, Error: [{ Message: message, Detail: detail, code }] } });
|
||||
|
||||
describe("API QuickBooks: ошибки (требование B1)", () => {
|
||||
it("400 ValidationFault: без повторов, разобранный Fault и intuit_tid в ошибке и логе", async () => {
|
||||
const t = mkApi([{ status: 400, tid: "tid-1", body: fault("ValidationFault", "2020", "Required param missing", "Account is required") }]);
|
||||
const err = await t.api.post("purchase", { Line: [] }).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(QboApiError);
|
||||
expect(err).toMatchObject({ status: 400, faultType: "ValidationFault", code: "2020", detail: "Account is required", intuitTid: "tid-1", isValidation: true });
|
||||
expect(err.message).toContain("intuit_tid=tid-1");
|
||||
expect(t.calls).toHaveLength(1);
|
||||
expect(t.logs[0]).toMatchObject({ status: 400, intuit_tid: "tid-1", code: "2020" });
|
||||
});
|
||||
|
||||
it("синтаксическая ошибка запроса (400 без Fault) не повторяется", async () => {
|
||||
const t = mkApi([{ status: 400, tid: "t2", body: { Fault: { type: "ValidationFault", Error: [{ Message: "Syntax error", code: "4000" }] } } }]);
|
||||
await expect(t.api.get("query?query=bad")).rejects.toMatchObject({ status: 400, code: "4000" });
|
||||
expect(t.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("403 (недостаточно прав): сразу ошибка", async () => {
|
||||
const t = mkApi([{ status: 403, body: fault("AUTHORIZATION", "120", "Authorization failure") }]);
|
||||
await expect(t.api.get("account/1")).rejects.toMatchObject({ status: 403, code: "120" });
|
||||
expect(t.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("401 (просрочен access token): один повтор с принудительным обновлением токена", async () => {
|
||||
const t = mkApi([{ status: 401, body: fault("AUTHENTICATION", "3200", "token expired") }, { status: 200, body: { ok: 1 } }]);
|
||||
expect(await t.api.get("account/1")).toEqual({ ok: 1 });
|
||||
expect(t.forced).toEqual([false, true]);
|
||||
});
|
||||
|
||||
it("повторный 401 после обновления: ошибка, а не бесконечный цикл", async () => {
|
||||
const t = mkApi([{ status: 401 }, { status: 401 }]);
|
||||
await expect(t.api.get("account/1")).rejects.toMatchObject({ status: 401 });
|
||||
expect(t.calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("429 и 5xx: повторы с паузой, затем успех", async () => {
|
||||
const t = mkApi([{ status: 429 }, { status: 503 }, { status: 200, body: { ok: 2 } }]);
|
||||
expect(await t.api.get("query?query=x")).toEqual({ ok: 2 });
|
||||
expect(t.calls).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("постоянный 500: ошибка после всех попыток", async () => {
|
||||
const t = mkApi(Array.from({ length: 5 }, () => ({ status: 500 })));
|
||||
await expect(t.api.get("query?query=x")).rejects.toThrow(/5 попыток/);
|
||||
});
|
||||
|
||||
it("запись: requestid одинаков при повторе (идемпотентность), тело отправляется как JSON", async () => {
|
||||
const t = mkApi([{ status: 503 }, { status: 200, body: { Purchase: { Id: "1" } } }]);
|
||||
await t.api.post("purchase", { TotalAmt: 5 });
|
||||
const ids = t.calls.map((c) => new URL(c.url).searchParams.get("requestid"));
|
||||
expect(ids[0]).toBeTruthy();
|
||||
expect(ids[0]).toBe(ids[1]);
|
||||
expect(t.calls[0]!.method).toBe("POST");
|
||||
expect(JSON.parse(t.calls[0]!.body!)).toEqual({ TotalAmt: 5 });
|
||||
expect(new URL(t.calls[0]!.url).searchParams.get("minorversion")).toBe("75");
|
||||
});
|
||||
|
||||
it("parseFault: пустое и чужое тело не ломает разбор", () => {
|
||||
expect(parseFault(null)).toEqual({});
|
||||
expect(parseFault({ x: 1 })).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("intuit_tid (требование B2)", () => {
|
||||
it("читается из заголовков ответа; без заголовков - undefined", () => {
|
||||
expect(intuitTid({ headers: { get: (n: string) => (n === "intuit_tid" ? "abc" : null) } })).toBe("abc");
|
||||
expect(intuitTid({})).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("discovery-документ (требование A6)", () => {
|
||||
it("адреса берутся из документа и кэшируются на сутки", async () => {
|
||||
let n = 0;
|
||||
let clock = 1000;
|
||||
const get = discoveryEndpoints("sandbox", async (url) => {
|
||||
n++;
|
||||
expect(url).toBe(DISCOVERY_URL.sandbox);
|
||||
return { authorization_endpoint: "https://appcenter.intuit.com/connect/oauth2", token_endpoint: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer", revocation_endpoint: "https://developer.api.intuit.com/v2/oauth2/tokens/revoke" };
|
||||
}, () => clock);
|
||||
const a = await get();
|
||||
await get();
|
||||
expect(n).toBe(1);
|
||||
expect(a.token).toBe("https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer");
|
||||
clock += 25 * 3600_000;
|
||||
await get();
|
||||
expect(n).toBe(2);
|
||||
});
|
||||
|
||||
it("недоступный документ или чужой домен: запасные адреса", async () => {
|
||||
expect(await discoveryEndpoints("production", async () => { throw new Error("down"); })()).toEqual(FALLBACK_ENDPOINTS);
|
||||
const evil = discoveryEndpoints("production", async () => ({ authorization_endpoint: "https://evil.example/x", token_endpoint: "https://evil.example/t" }));
|
||||
expect(await evil()).toEqual(FALLBACK_ENDPOINTS);
|
||||
});
|
||||
|
||||
it("QboAuth использует адреса из документа для ссылки авторизации и обмена токена", async () => {
|
||||
const urls: string[] = [];
|
||||
const fn: FetchFn = async (url) => { urls.push(url); return { ok: true, status: 200, json: async () => ({ access_token: "a", refresh_token: "r", expires_in: 3600 }) }; };
|
||||
const auth = new QboAuth({
|
||||
store: new MemoryStore(), fetchFn: fn, env: "sandbox", clientId: "c", clientSecret: "s", redirectUri: "https://x/cb", scope: "sc", keepAliveHours: 20,
|
||||
endpoints: async () => ({ authorization: "https://appcenter.intuit.com/new/auth", token: "https://oauth.platform.intuit.com/new/token", revocation: "https://developer.api.intuit.com/new/revoke" }),
|
||||
});
|
||||
const { url } = await auth.startConnect();
|
||||
expect(url.startsWith("https://appcenter.intuit.com/new/auth?")).toBe(true);
|
||||
await auth.handleCallback({ code: "c", state: new URL(url).searchParams.get("state")!, realmId: "R" });
|
||||
expect(urls[0]).toBe("https://oauth.platform.intuit.com/new/token");
|
||||
});
|
||||
});
|
||||
|
||||
describe("отключение (страница Disconnect обещает удаление токенов)", () => {
|
||||
async function connected(revokeStatus: number) {
|
||||
const urls: Array<{ url: string; body: string }> = [];
|
||||
const fn: FetchFn = async (url, init) => {
|
||||
urls.push({ url, body: init.body });
|
||||
if (url.includes("revoke")) return { ok: revokeStatus < 400, status: revokeStatus, json: async () => ({}) };
|
||||
return { ok: true, status: 200, json: async () => ({ access_token: "a", refresh_token: "r1", expires_in: 3600 }) };
|
||||
};
|
||||
const store = new MemoryStore();
|
||||
const auth = new QboAuth({ store, fetchFn: fn, env: "sandbox", clientId: "c", clientSecret: "s", redirectUri: "https://x/cb", scope: "sc", keepAliveHours: 20 });
|
||||
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
|
||||
await auth.handleCallback({ code: "c", state, realmId: "R" });
|
||||
return { auth, store, urls };
|
||||
}
|
||||
|
||||
it("токен отзывается у Intuit и удаляется из хранилища", async () => {
|
||||
const { auth, store, urls } = await connected(200);
|
||||
expect(await auth.disconnect()).toEqual({ revoked: true, removed: true });
|
||||
expect(JSON.parse(urls.at(-1)!.body)).toEqual({ token: "r1" });
|
||||
expect(store.conns.size).toBe(0);
|
||||
expect((await auth.status()).connected).toBe(false);
|
||||
});
|
||||
|
||||
it("если отзыв не удался (токен уже отозван в QuickBooks), токены всё равно удаляются", async () => {
|
||||
const { auth, store } = await connected(400);
|
||||
expect(await auth.disconnect()).toEqual({ revoked: false, removed: true });
|
||||
expect(store.conns.size).toBe(0);
|
||||
});
|
||||
|
||||
it("без подключения: ничего не удалено", async () => {
|
||||
const auth = new QboAuth({ store: new MemoryStore(), fetchFn: async () => ({ ok: true, status: 200, json: async () => ({}) }), env: "sandbox", clientId: "c", clientSecret: "s", redirectUri: "x", scope: "s", keepAliveHours: 20 });
|
||||
expect(await auth.disconnect()).toEqual({ revoked: false, removed: false });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user