Files
khb_microservices/packages/qbo_auth/src/service.test.ts
2026-11-23 09:28:24 +03:00

198 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from "vitest";
import { buildApi } from "./http-api.js";
import { decrypt, encrypt, parseKey } from "./crypto.js";
import type { FetchFn } from "./oauth.js";
import { QboAuth, ReauthNeeded } from "./service.js";
import { MemoryStore } from "./store.js";
const T0 = new Date("2026-11-16T12:00:00.000Z");
/** Заглушка token endpoint: отдаёт заданные ответы по очереди и запоминает тела запросов. */
function fakeFetch(responses: Array<{ status?: number; body: Record<string, unknown> }>) {
const calls: Array<{ url: string; body: URLSearchParams; auth: string }> = [];
const fn: FetchFn = async (url, init) => {
calls.push({ url, body: new URLSearchParams(init.body), auth: init.headers.Authorization ?? "" });
const r = responses.shift() ?? { status: 500, body: {} };
const status = r.status ?? 200;
return { ok: status < 400, status, json: async () => r.body };
};
return { fn, calls };
}
const tokens = (n: number) => ({ access_token: `at${n}`, refresh_token: `rt${n}`, expires_in: 3600, x_refresh_token_expires_in: 8726400 });
function mk(responses: Array<{ status?: number; body: Record<string, unknown> }>, clock = { t: T0 }) {
const store = new MemoryStore();
const f = fakeFetch(responses);
const notes: string[] = [];
const auth = new QboAuth({
store, fetchFn: f.fn, env: "sandbox", clientId: "cid", clientSecret: "csec", redirectUri: "https://x/api/qbo/callback",
scope: "com.intuit.quickbooks.accounting", keepAliveHours: 20, now: () => clock.t, notify: async (t) => { notes.push(t); },
});
return { auth, store, f, notes, clock };
}
describe("подключение", () => {
it("startConnect: ссылка Intuit с redirect_uri и одноразовым state", async () => {
const { auth, store } = mk([]);
const { url } = await auth.startConnect();
const u = new URL(url);
expect(u.origin + u.pathname).toBe("https://appcenter.intuit.com/connect/oauth2");
expect(u.searchParams.get("redirect_uri")).toBe("https://x/api/qbo/callback");
expect(u.searchParams.get("client_id")).toBe("cid");
expect(store.states.has(u.searchParams.get("state")!)).toBe(true);
});
it("callback: обмен кода, сохранение токенов; повтор того же state отклоняется", async () => {
const { auth, store, f } = mk([{ body: tokens(1) }]);
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
expect(await auth.handleCallback({ code: "c1", state, realmId: "R1" })).toEqual({ realmId: "R1" });
expect(f.calls[0]!.body.get("grant_type")).toBe("authorization_code");
expect(f.calls[0]!.body.get("code")).toBe("c1");
expect(f.calls[0]!.auth).toBe("Basic " + Buffer.from("cid:csec").toString("base64"));
expect(store.conns.get("sandbox")).toMatchObject({ realmId: "R1", accessToken: "at1", refreshToken: "rt1", status: "ok" });
await expect(auth.handleCallback({ code: "c1", state, realmId: "R1" })).rejects.toThrow(/state/);
});
it("callback: чужой state и просроченный state отклоняются без обращения к Intuit", async () => {
const { auth, store, f } = mk([]);
store.now = () => T0.getTime();
await expect(auth.handleCallback({ code: "c", state: "bad", realmId: "R" })).rejects.toThrow(/state/);
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
store.now = () => T0.getTime() + 11 * 60_000;
await expect(auth.handleCallback({ code: "c", state, realmId: "R" })).rejects.toThrow(/state/);
expect(f.calls).toHaveLength(0);
});
it("callback: ошибка Intuit (access_denied) не сохраняет токены", async () => {
const { auth, store } = mk([]);
const state = new URL((await auth.startConnect()).url).searchParams.get("state")!;
await expect(auth.handleCallback({ state, error: "access_denied" })).rejects.toThrow(/access_denied/);
expect(store.conns.size).toBe(0);
});
});
describe("токены", () => {
async function connected(extra: Array<{ status?: number; body: Record<string, unknown> }> = []) {
const ctx = mk([{ body: tokens(1) }, ...extra]);
const state = new URL((await ctx.auth.startConnect()).url).searchParams.get("state")!;
await ctx.auth.handleCallback({ code: "c", state, realmId: "R1" });
return ctx;
}
it("действующий токен отдаётся без обращения к Intuit; за 5 минут до конца - обновляется и сохраняется новый refresh token", async () => {
const ctx = await connected([{ body: tokens(2) }]);
expect((await ctx.auth.getAccessToken()).accessToken).toBe("at1");
expect(ctx.f.calls).toHaveLength(1);
ctx.clock.t = new Date(T0.getTime() + 56 * 60_000);
const t = await ctx.auth.getAccessToken();
expect(t).toMatchObject({ accessToken: "at2", realmId: "R1", apiBase: "https://sandbox-quickbooks.api.intuit.com" });
expect(ctx.f.calls[1]!.body.get("grant_type")).toBe("refresh_token");
expect(ctx.f.calls[1]!.body.get("refresh_token")).toBe("rt1");
expect(ctx.store.conns.get("sandbox")!.refreshToken).toBe("rt2");
});
it("invalid_grant: статус reauth_needed, уведомление, дальше 409 без обращения к Intuit", async () => {
const ctx = await connected([{ status: 400, body: { error: "invalid_grant" } }]);
ctx.clock.t = new Date(T0.getTime() + 2 * 3600_000);
await expect(ctx.auth.getAccessToken()).rejects.toBeInstanceOf(ReauthNeeded);
expect(ctx.notes).toHaveLength(1);
const calls = ctx.f.calls.length;
await expect(ctx.auth.getAccessToken()).rejects.toBeInstanceOf(ReauthNeeded);
expect(ctx.f.calls).toHaveLength(calls);
expect((await ctx.auth.status()).connected).toBe(false);
});
it("прочие ошибки Intuit не переводят подключение в reauth_needed", async () => {
const ctx = await connected([{ status: 500, body: { error: "server_error" } }]);
ctx.clock.t = new Date(T0.getTime() + 2 * 3600_000);
await expect(ctx.auth.getAccessToken()).rejects.toThrow(/500/);
expect(ctx.store.conns.get("sandbox")!.status).toBe("ok");
});
it("keepAlive: свежие токены не трогает, старые обновляет", async () => {
const ctx = await connected([{ body: tokens(2) }]);
expect(await ctx.auth.keepAlive()).toBe("fresh");
ctx.clock.t = new Date(T0.getTime() + 21 * 3600_000);
expect(await ctx.auth.keepAlive()).toBe("refreshed");
expect(ctx.store.conns.get("sandbox")!.refreshToken).toBe("rt2");
});
it("keepAlive без подключения", async () => {
expect(await mk([]).auth.keepAlive()).toBe("not_connected");
});
});
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) }]);
const app = buildApi(ctx.auth, "tok");
expect((await app.inject({ url: "/healthz" })).statusCode).toBe(200);
expect((await app.inject({ url: "/status" })).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url: "/token" })).statusCode).toBe(401);
const url = (await app.inject({ method: "POST", url: "/connect", headers: { authorization: "Bearer tok" } })).json().url as string;
const state = new URL(url).searchParams.get("state")!;
const cb = await app.inject({ url: `/callback?code=c&state=${state}&realmId=R1` });
expect(cb.statusCode).toBe(302);
expect(cb.headers.location).toBe("/api/qbo/connected?ok=1");
expect(cb.body).not.toContain("html");
expect((await app.inject({ url: "/connected?ok=1" })).body).toContain("подключён");
const st = await app.inject({ url: "/status", headers: { authorization: "Bearer tok" } });
expect(st.json()).toMatchObject({ connected: true, realmId: "R1" });
expect(st.body).not.toContain("at1");
expect(st.body).not.toContain("rt1");
});
it("/callback с плохим state: 400 и страница без подробностей", async () => {
const app = buildApi(mk([]).auth, "tok");
const r = await app.inject({ url: "/callback?code=c&state=bad&realmId=R" });
expect(r.statusCode).toBe(302);
expect(r.headers.location).toBe("/api/qbo/connected?ok=0");
expect((await app.inject({ url: "/connected?ok=0" })).statusCode).toBe(400);
});
it("/token: без подключения - 409 reauth_needed; с подключением - токен", async () => {
const ctx = mk([{ body: tokens(1) }]);
const app = buildApi(ctx.auth, "tok");
const h = { authorization: "Bearer tok" };
expect((await app.inject({ method: "POST", url: "/token", headers: h })).statusCode).toBe(409);
const state = new URL((await ctx.auth.startConnect()).url).searchParams.get("state")!;
await ctx.auth.handleCallback({ code: "c", state, realmId: "R1" });
const r = await app.inject({ method: "POST", url: "/token", headers: h });
expect(r.statusCode).toBe(200);
expect(r.json()).toMatchObject({ accessToken: "at1", realmId: "R1" });
});
});
describe("шифрование", () => {
it("туда-обратно; разные шифртексты; подмена ломает расшифровку; плохой ключ отклоняется", () => {
const key = parseKey("00".repeat(32));
const a = encrypt("secret", key), b = encrypt("secret", key);
expect(a).not.toBe(b);
expect(a).not.toContain("secret");
expect(decrypt(a, key)).toBe("secret");
expect(() => decrypt(a.slice(0, -2) + "AA", key)).toThrow();
expect(() => parseKey("short")).toThrow();
});
});