import { createHash } from "node:crypto"; import { describe, expect, it, vi } from "vitest"; import { buildDesiredLagoCatalog } from "./catalog"; import { LagoCatalogClient } from "./lago-client"; const organizationId = "organization_test"; const organizationDigest = createHash("sha256").update(organizationId).digest("hex"); function response(status: number, body: unknown): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" }, }); } describe("LagoCatalogClient", () => { it("pins organization identity before every provider mutation", async () => { const fetchImpl = vi .fn() .mockResolvedValueOnce(response(200, { organization: { lago_id: organizationId, name: "HiveGrid Test" } })) .mockResolvedValueOnce(response(200, { tax: { ...buildDesiredLagoCatalog().tax } })); const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret", expectedOrganizationName: "Other", expectedOrganizationIdSha256: organizationDigest, fetchImpl, }); await expect(client.applyTax(buildDesiredLagoCatalog(), false)).rejects.toThrow("pinned target identity"); expect(fetchImpl).toHaveBeenCalledTimes(1); }); it("creates and updates plans using only redacted-safe endpoints", async () => { const desired = buildDesiredLagoCatalog(); const fetchImpl = vi.fn().mockImplementation(async (url, init) => { if (String(url).endsWith("/organizations")) { return response(200, { organization: { lago_id: organizationId, name: "HiveGrid Test" }, }); } const requestBody = JSON.parse(String(init?.body)) as { plan: Record }; return response(200, { plan: { ...requestBody.plan, taxes: [{ code: "de-vat-19" }], }, }); }); const client = new LagoCatalogClient({ apiUrl: "https://lago.example.test", apiKey: "secret", expectedOrganizationName: "HiveGrid Test", expectedOrganizationIdSha256: organizationDigest, fetchImpl, }); await client.applyPlan(desired.plans[0]!, false); await client.applyPlan(desired.plans[1]!, true); expect(fetchImpl.mock.calls[1]?.[0]).toBe("https://lago.example.test/api/v1/plans"); expect(fetchImpl.mock.calls[3]?.[0]).toBe(`https://lago.example.test/api/v1/plans/${desired.plans[1]!.code}`); expect(fetchImpl.mock.calls[3]?.[1]?.method).toBe("PUT"); }); });