Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,124 @@
import { describe, expect, it } from "vitest";
import { assessLagoCatalog, buildDesiredLagoCatalog, toLagoPlanPayload, toLagoTaxPayload, type LagoCatalogSnapshot } from "./catalog";
const desired = buildDesiredLagoCatalog();
function matchingSnapshot(): LagoCatalogSnapshot {
return {
organization: { name: "HiveGrid Test", idSha256: "a".repeat(64) },
tax: {
code: desired.tax.code,
name: desired.tax.name,
description: desired.tax.description,
rate: desired.tax.rate,
applied_to_organization: desired.tax.appliedToOrganization,
},
plans: desired.plans.map((plan) => ({
code: plan.code,
name: plan.name,
invoice_display_name: plan.invoiceDisplayName,
description: plan.description,
interval: plan.interval,
amount_cents: plan.amountCents,
amount_currency: plan.amountCurrency,
pay_in_advance: plan.payInAdvance,
taxes: plan.taxCodes.map((code) => ({ code })),
metadata: { ...plan.metadata },
})),
};
}
describe("HiveGrid Lago billing catalog", () => {
it("builds base plans, recurring storage products, and five email-marketing tiers", () => {
expect(desired.plans.map((plan) => plan.code)).toEqual([
"business",
"business_annual_sepa",
"email_marketing_l",
"email_marketing_m",
"email_marketing_s",
"email_marketing_xl",
"email_marketing_xxl",
"pro",
"pro_annual_sepa",
"starter",
"starter_annual_sepa",
"storage_100gb",
"storage_1tb",
"storage_500gb",
"storage_5tb",
]);
expect(desired.plans.every((plan) => plan.interval === "monthly")).toBe(true);
expect(desired.plans.every((plan) => plan.taxCodes.includes("de-vat-19"))).toBe(true);
expect(desired.plans.find((plan) => plan.code === "email_marketing_m")).toMatchObject({
amountCents: 14_900,
metadata: {
hivegrid_resource_kind: "email_marketing_add_on",
hivegrid_monthly_email_limit: "50000",
},
});
expect(desired.plans.find((plan) => plan.code === "pro")).toMatchObject({
metadata: {
hivegrid_included_storage_gb: "500",
hivegrid_storage_per_additional_seat_gb: "20",
},
});
expect(desired.plans.find((plan) => plan.code === "storage_1tb")).toMatchObject({
amountCents: 1_299,
metadata: {
hivegrid_resource_kind: "storage_add_on",
hivegrid_included_storage_gb: "1000",
hivegrid_purchasable: "true",
},
});
expect(desired.plans.find((plan) => plan.code === "storage_100gb")).toMatchObject({
amountCents: 125,
metadata: {
hivegrid_resource_kind: "storage_add_on",
hivegrid_included_storage_gb: "100",
hivegrid_purchasable: "false",
},
});
});
it("produces a deterministic machine-readable contract digest", () => {
expect(buildDesiredLagoCatalog()).toEqual(desired);
expect(desired.digestSha256).toMatch(/^[a-f0-9]{64}$/u);
});
it("reports a complete idempotent catalog as noops", () => {
const assessment = assessLagoCatalog(matchingSnapshot());
expect(assessment.complete).toBe(true);
expect(assessment.actions.every((action) => action.action === "noop")).toBe(true);
});
it("detects price, tax, and catalog-version drift", () => {
const snapshot = matchingSnapshot();
snapshot.tax!.rate = 7;
snapshot.plans[0]!.amount_cents += 1;
snapshot.plans[1]!.metadata = {
...snapshot.plans[1]!.metadata,
hivegrid_catalog_version: "old",
};
const assessment = assessLagoCatalog(snapshot);
expect(assessment.complete).toBe(false);
expect(assessment.actions.find((action) => action.resource === "tax")?.driftFields).toContain("rate");
expect(assessment.actions.find((action) => action.code === snapshot.plans[0]!.code)?.driftFields).toContain("amountCents");
expect(assessment.actions.find((action) => action.code === snapshot.plans[1]!.code)?.driftFields).toContain("metadata");
});
it("creates explicit Lago tax and non-cascading plan update payloads", () => {
expect(toLagoTaxPayload(desired.tax)).toMatchObject({
tax: { code: "de-vat-19", rate: 19, applied_to_organization: false },
});
expect(toLagoPlanPayload(desired.plans[0]!, true)).toMatchObject({
plan: {
interval: "monthly",
amount_currency: "EUR",
tax_codes: ["de-vat-19"],
cascade_updates: false,
},
});
});
});
@@ -0,0 +1,318 @@
import { createHash } from "node:crypto";
import { emailMarketingCommercialProducts, hiveGridBasePlans, hiveGridBillingCatalogVersion, hiveGridStorageAddOns, hiveGridVat } from "@hivegrid/entitlements";
import { z } from "zod";
const CURRENCY = "EUR";
export const billingCatalogResourceKinds = Object.freeze({
basePlan: "base_plan",
emailMarketingAddOn: "email_marketing_add_on",
storageAddOn: "storage_add_on",
} as const);
export type BillingCatalogResourceKind = (typeof billingCatalogResourceKinds)[keyof typeof billingCatalogResourceKinds];
export type DesiredLagoTax = {
readonly code: string;
readonly name: string;
readonly description: string;
readonly rate: number;
readonly appliedToOrganization: boolean;
};
export type DesiredLagoPlan = {
readonly code: string;
readonly name: string;
readonly invoiceDisplayName: string;
readonly description: string;
readonly interval: "monthly";
readonly amountCents: number;
readonly amountCurrency: typeof CURRENCY;
readonly payInAdvance: true;
readonly taxCodes: readonly string[];
readonly metadata: Readonly<Record<string, string>>;
};
export type DesiredLagoCatalog = {
readonly version: string;
readonly digestSha256: string;
readonly tax: DesiredLagoTax;
readonly plans: readonly DesiredLagoPlan[];
};
function desiredPlan(input: {
code: string;
name: string;
description: string;
amountCents: number;
kind: BillingCatalogResourceKind;
metadata?: Readonly<Record<string, string>>;
}): DesiredLagoPlan {
return Object.freeze({
code: input.code,
name: input.name,
invoiceDisplayName: input.name,
description: `${input.description} · HiveGrid Katalog ${hiveGridBillingCatalogVersion}`,
interval: "monthly",
amountCents: input.amountCents,
amountCurrency: CURRENCY,
payInAdvance: true,
taxCodes: Object.freeze([hiveGridVat.code]),
metadata: Object.freeze({
hivegrid_catalog_version: hiveGridBillingCatalogVersion,
hivegrid_resource_kind: input.kind,
...input.metadata,
}),
});
}
function buildDesiredPlans(): readonly DesiredLagoPlan[] {
const basePlans = hiveGridBasePlans.flatMap((plan) =>
plan.variants.map((variant) =>
desiredPlan({
code: variant.code,
name: variant.contractMonths === 12 ? `${plan.publicName} · 12 Monate` : `${plan.publicName} · monatlich`,
description:
variant.contractMonths === 12 ? `${plan.publicName}, monatliche SEPA-Rate bei 12 Monaten Mindestlaufzeit` : `${plan.publicName}, monatlich kuendbar`,
amountCents: variant.baseAmountCents,
kind: billingCatalogResourceKinds.basePlan,
metadata: {
hivegrid_technical_plan_code: plan.technicalCode,
hivegrid_billing_cadence: variant.cadence,
hivegrid_contract_months: String(variant.contractMonths),
hivegrid_included_office_seats: String(plan.includedSeats.office),
hivegrid_included_field_seats: String(plan.includedSeats.field),
hivegrid_included_storage_gb: String(plan.includedStorageGb),
hivegrid_storage_per_additional_seat_gb: String(plan.storagePerAdditionalSeatGb),
hivegrid_extra_office_seat_cents: String(variant.extraSeatAmountCents.office),
hivegrid_extra_field_seat_cents: String(variant.extraSeatAmountCents.field),
},
})
)
);
const storagePlans = hiveGridStorageAddOns.map((addOn) =>
desiredPlan({
code: addOn.code,
name: addOn.publicName,
description: `${addOn.publicName}, festes wiederkehrendes Speicherpaket`,
amountCents: addOn.amountCents,
kind: billingCatalogResourceKinds.storageAddOn,
metadata: {
hivegrid_included_storage_gb: String(addOn.includedStorageGb),
hivegrid_billing_cadence: "monthly",
hivegrid_purchasable: String(addOn.purchasable),
},
})
);
const emailMarketingPlans = emailMarketingCommercialProducts.map((addOn) =>
desiredPlan({
code: addOn.code,
name: addOn.title,
description: `${addOn.title}, festes wiederkehrendes Monatskontingent`,
amountCents: addOn.amountCents!,
kind: billingCatalogResourceKinds.emailMarketingAddOn,
metadata: {
hivegrid_monthly_email_limit: String(addOn.monthlyEmailLimit),
hivegrid_billing_cadence: "monthly",
},
})
);
return Object.freeze([...basePlans, ...storagePlans, ...emailMarketingPlans].sort((left, right) => left.code.localeCompare(right.code)));
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value !== null && typeof value === "object") {
return `{${Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, nested]) => `${JSON.stringify(key)}:${stableJson(nested)}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
export function buildDesiredLagoCatalog(): DesiredLagoCatalog {
const tax = Object.freeze({
code: hiveGridVat.code,
name: hiveGridVat.name,
description: `HiveGrid Deutschland · Katalog ${hiveGridBillingCatalogVersion}`,
rate: hiveGridVat.rateBasisPoints / 100,
appliedToOrganization: false,
});
const plans = buildDesiredPlans();
const digestInput = {
version: hiveGridBillingCatalogVersion,
tax,
plans,
};
return Object.freeze({
...digestInput,
digestSha256: createHash("sha256").update(stableJson(digestInput)).digest("hex"),
});
}
const lagoTaxSchema = z.object({
code: z.string(),
name: z.string(),
description: z.string().nullable().optional(),
rate: z.coerce.number(),
applied_to_organization: z.boolean(),
});
const lagoPlanSchema = z.object({
code: z.string(),
name: z.string(),
invoice_display_name: z.string().nullable().optional(),
description: z.string().nullable().optional(),
interval: z.string(),
amount_cents: z.number().int(),
amount_currency: z.string(),
pay_in_advance: z.boolean(),
taxes: z
.array(
z.object({
code: z.string(),
})
)
.default([]),
metadata: z.record(z.string(), z.unknown()).nullable().optional(),
});
export const lagoTaxResponseSchema = z.object({ tax: lagoTaxSchema });
export const lagoPlanResponseSchema = z.object({ plan: lagoPlanSchema });
export const lagoOrganizationResponseSchema = z.object({
organization: z.object({ lago_id: z.string().min(1), name: z.string().min(1) }),
});
export type LagoTaxSnapshot = z.infer<typeof lagoTaxSchema>;
export type LagoPlanSnapshot = z.infer<typeof lagoPlanSchema>;
export type LagoCatalogSnapshot = {
readonly organization: {
readonly name: string;
readonly idSha256: string;
};
readonly tax: LagoTaxSnapshot | null;
readonly plans: readonly LagoPlanSnapshot[];
};
export type LagoCatalogAction = {
readonly resource: "tax" | "plan";
readonly code: string;
readonly action: "create" | "update" | "noop";
readonly driftFields: readonly string[];
};
export type LagoCatalogAssessment = {
readonly catalogVersion: string;
readonly catalogDigestSha256: string;
readonly complete: boolean;
readonly actions: readonly LagoCatalogAction[];
};
function normalizedMetadata(metadata: Record<string, unknown> | null | undefined): Record<string, string> {
return Object.fromEntries(
Object.entries(metadata ?? {})
.filter(([, value]) => typeof value === "string")
.map(([key, value]) => [key, value as string])
.sort(([left], [right]) => left.localeCompare(right))
);
}
function differentFields(actual: Readonly<Record<string, unknown>>, desired: Readonly<Record<string, unknown>>): string[] {
return Object.keys(desired)
.filter((field) => stableJson(actual[field]) !== stableJson(desired[field]))
.sort();
}
export function assessLagoCatalog(snapshot: LagoCatalogSnapshot, desired = buildDesiredLagoCatalog()): LagoCatalogAssessment {
const taxDrift = snapshot.tax
? differentFields(
{
code: snapshot.tax.code,
name: snapshot.tax.name,
description: snapshot.tax.description ?? "",
rate: snapshot.tax.rate,
appliedToOrganization: snapshot.tax.applied_to_organization,
},
desired.tax
)
: [];
const actions: LagoCatalogAction[] = [
{
resource: "tax",
code: desired.tax.code,
action: snapshot.tax ? (taxDrift.length > 0 ? "update" : "noop") : "create",
driftFields: taxDrift,
},
];
for (const plan of desired.plans) {
const matches = snapshot.plans.filter((candidate) => candidate.code === plan.code);
if (matches.length > 1) {
throw new Error(`billing catalog: Lago returned duplicate plan code ${plan.code}`);
}
const actual = matches[0];
const driftFields = actual
? differentFields(
{
code: actual.code,
name: actual.name,
invoiceDisplayName: actual.invoice_display_name ?? "",
description: actual.description ?? "",
interval: actual.interval,
amountCents: actual.amount_cents,
amountCurrency: actual.amount_currency.toUpperCase(),
payInAdvance: actual.pay_in_advance,
taxCodes: actual.taxes.map((tax) => tax.code).sort(),
metadata: normalizedMetadata(actual.metadata),
},
plan
)
: [];
actions.push({
resource: "plan",
code: plan.code,
action: actual ? (driftFields.length > 0 ? "update" : "noop") : "create",
driftFields,
});
}
return Object.freeze({
catalogVersion: desired.version,
catalogDigestSha256: desired.digestSha256,
complete: actions.every((action) => action.action === "noop"),
actions: Object.freeze(actions),
});
}
export function toLagoTaxPayload(tax: DesiredLagoTax): Record<string, unknown> {
return {
tax: {
name: tax.name,
code: tax.code,
rate: tax.rate,
description: tax.description,
applied_to_organization: tax.appliedToOrganization,
},
};
}
export function toLagoPlanPayload(plan: DesiredLagoPlan, update: boolean): Record<string, unknown> {
return {
plan: {
name: plan.name,
code: plan.code,
invoice_display_name: plan.invoiceDisplayName,
description: plan.description,
interval: plan.interval,
amount_cents: plan.amountCents,
amount_currency: plan.amountCurrency,
pay_in_advance: plan.payInAdvance,
tax_codes: plan.taxCodes,
metadata: plan.metadata,
...(update ? { cascade_updates: false } : {}),
},
};
}
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { hiveGridBillingCatalogVersion } from "@hivegrid/entitlements";
import { parseBillingCatalogCommand } from "./contracts";
const baseEnv = {
NODE_ENV: "production",
LAGO_API_URL: "http://127.0.0.1:3108",
LAGO_API_KEY: "lago_secret",
};
describe("billing catalog operator contracts", () => {
it("parses read-only staging plan mode with the canonical identity", () => {
expect(parseBillingCatalogCommand(["--target=staging", "--plan"], baseEnv)).toMatchObject({
target: "staging",
mode: "plan",
expectedOrganizationName: "HiveGrid Staging",
});
});
it("requires exact versioned confirmation for apply", () => {
expect(() => parseBillingCatalogCommand(["--target=staging", "--apply"], baseEnv)).toThrow(`--confirm=staging:${hiveGridBillingCatalogVersion}`);
expect(parseBillingCatalogCommand(["--target=staging", "--apply", `--confirm=staging:${hiveGridBillingCatalogVersion}`], baseEnv).mode).toBe("apply");
});
it("uses the pinned production organization identity", () => {
expect(parseBillingCatalogCommand(["--target=production", "--verify"], baseEnv)).toMatchObject({
target: "production",
expectedOrganizationName: "HiveGrid",
expectedOrganizationIdSha256: "c54f682e7528f2f1d556a5f539d6d200aa7d9163c9aec31f8fb5b21be632505e",
});
});
it("rejects unsafe runtime mode and credential-bearing URLs", () => {
expect(() => parseBillingCatalogCommand(["--target=staging"], { ...baseEnv, NODE_ENV: "development" })).toThrow("NODE_ENV must be production");
expect(() =>
parseBillingCatalogCommand(["--target=staging"], {
...baseEnv,
LAGO_API_URL: "https://user:password@lago.example.test/api/v1",
})
).toThrow("HTTP(S) origin");
});
});
@@ -0,0 +1,133 @@
import { hiveGridBillingCatalogVersion } from "@hivegrid/entitlements";
export type BillingCatalogTarget = "staging" | "production";
export type BillingCatalogMode = "plan" | "apply" | "verify";
export type BillingCatalogEnvironment = Readonly<Record<string, string | undefined>>;
export type BillingCatalogCommand = {
readonly target: BillingCatalogTarget;
readonly mode: BillingCatalogMode;
readonly lagoApiUrl: string;
readonly lagoApiKey: string;
readonly expectedOrganizationName: string;
readonly expectedOrganizationIdSha256: string;
readonly snapshotDirectory: string;
};
const STAGING_ORGANIZATION_NAME = "HiveGrid Staging";
const STAGING_ORGANIZATION_ID_SHA256 = "3b1134a731c67b704bb0b3298ce031213079966b348aa762800f9c92556085a8";
const PRODUCTION_ORGANIZATION_NAME = "HiveGrid";
const PRODUCTION_ORGANIZATION_ID_SHA256 = "c54f682e7528f2f1d556a5f539d6d200aa7d9163c9aec31f8fb5b21be632505e";
const MODE_ARGUMENTS = new Map<string, BillingCatalogMode>([
["--plan", "plan"],
["--apply", "apply"],
["--verify", "verify"],
]);
export class BillingCatalogOperatorError extends Error {
constructor(message: string) {
super(message);
this.name = "BillingCatalogOperatorError";
}
}
function required(env: BillingCatalogEnvironment, name: string): string {
const value = env[name]?.trim();
if (!value) throw new BillingCatalogOperatorError(`billing catalog: ${name} is required`);
return value;
}
function valueArgument(argv: readonly string[], name: string): string | undefined {
const prefix = `${name}=`;
const values = argv.filter((argument) => argument.startsWith(prefix)).map((argument) => argument.slice(prefix.length));
if (values.length > 1) throw new BillingCatalogOperatorError(`billing catalog: ${name} may only be provided once`);
return values[0];
}
function parseTarget(argv: readonly string[]): BillingCatalogTarget {
const target = valueArgument(argv, "--target");
if (target !== "staging" && target !== "production") {
throw new BillingCatalogOperatorError("billing catalog: --target=staging|production is required");
}
return target;
}
function parseMode(argv: readonly string[]): BillingCatalogMode {
const modes = argv.flatMap((argument) => {
const mode = MODE_ARGUMENTS.get(argument);
return mode ? [mode] : [];
});
if (modes.length > 1) throw new BillingCatalogOperatorError("billing catalog: provide exactly one mode");
return modes[0] ?? "plan";
}
function assertKnownArguments(argv: readonly string[]): void {
for (const argument of argv) {
if (MODE_ARGUMENTS.has(argument) || argument.startsWith("--target=") || argument.startsWith("--confirm=")) {
continue;
}
throw new BillingCatalogOperatorError("billing catalog: unknown argument");
}
}
function normalizeApiUrl(value: string): string {
let parsed: URL;
try {
parsed = new URL(value);
} catch {
throw new BillingCatalogOperatorError("billing catalog: LAGO_API_URL must be an absolute URL");
}
if (
!new Set(["http:", "https:"]).has(parsed.protocol) ||
parsed.username ||
parsed.password ||
parsed.search ||
parsed.hash ||
(parsed.pathname !== "" && parsed.pathname !== "/")
) {
throw new BillingCatalogOperatorError("billing catalog: LAGO_API_URL must be an HTTP(S) origin");
}
return parsed.origin;
}
function requireOrganizationContract(target: BillingCatalogTarget): { name: string; idSha256: string } {
if (target === "staging") {
return { name: STAGING_ORGANIZATION_NAME, idSha256: STAGING_ORGANIZATION_ID_SHA256 };
}
return {
name: PRODUCTION_ORGANIZATION_NAME,
idSha256: PRODUCTION_ORGANIZATION_ID_SHA256,
};
}
export function parseBillingCatalogCommand(argv: readonly string[], env: BillingCatalogEnvironment): BillingCatalogCommand {
assertKnownArguments(argv);
const target = parseTarget(argv);
const mode = parseMode(argv);
const confirmation = valueArgument(argv, "--confirm");
const expectedConfirmation = `${target}:${hiveGridBillingCatalogVersion}`;
if (mode === "apply" && confirmation !== expectedConfirmation) {
throw new BillingCatalogOperatorError(`billing catalog: apply requires --confirm=${expectedConfirmation}`);
}
if (mode !== "apply" && confirmation !== undefined) {
throw new BillingCatalogOperatorError("billing catalog: --confirm is valid only with --apply");
}
if (env.NODE_ENV?.trim() !== "production") {
throw new BillingCatalogOperatorError("billing catalog: NODE_ENV must be production so the operator path fails closed");
}
const organization = requireOrganizationContract(target);
return {
target,
mode,
lagoApiUrl: normalizeApiUrl(required(env, "LAGO_API_URL")),
lagoApiKey: required(env, "LAGO_API_KEY"),
expectedOrganizationName: organization.name,
expectedOrganizationIdSha256: organization.idSha256,
snapshotDirectory: env.HIVEGRID_BILLING_CATALOG_SNAPSHOT_DIR?.trim() || "tmp/billing-catalog-snapshots",
};
}
export function safeBillingCatalogError(error: unknown): string {
if (error instanceof BillingCatalogOperatorError) return error.message;
return "billing catalog: operator command failed; inspect redacted service logs";
}
@@ -0,0 +1,67 @@
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<typeof fetch>()
.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<typeof fetch>().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<string, unknown> };
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");
});
});
@@ -0,0 +1,118 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import {
buildDesiredLagoCatalog,
lagoOrganizationResponseSchema,
lagoPlanResponseSchema,
lagoTaxResponseSchema,
toLagoPlanPayload,
toLagoTaxPayload,
type DesiredLagoCatalog,
type DesiredLagoPlan,
type LagoCatalogSnapshot,
} from "./catalog";
import { BillingCatalogOperatorError } from "./contracts";
const DEFAULT_TIMEOUT_MS = 10_000;
export class LagoCatalogClient {
private readonly apiUrl: string;
private readonly apiKey: string;
private readonly expectedOrganizationName: string;
private readonly expectedOrganizationIdSha256: string;
private readonly fetchImpl: typeof fetch;
private readonly timeoutMs: number;
constructor(input: {
apiUrl: string;
apiKey: string;
expectedOrganizationName: string;
expectedOrganizationIdSha256: string;
fetchImpl?: typeof fetch;
timeoutMs?: number;
}) {
this.apiUrl = input.apiUrl.replace(/\/+$/u, "");
this.apiKey = input.apiKey;
this.expectedOrganizationName = input.expectedOrganizationName;
this.expectedOrganizationIdSha256 = input.expectedOrganizationIdSha256;
this.fetchImpl = input.fetchImpl ?? fetch;
this.timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
}
async readCatalog(desired = buildDesiredLagoCatalog()): Promise<LagoCatalogSnapshot> {
const organization = await this.assertOrganization();
const [tax, ...plans] = await Promise.all([
this.request(`/taxes/${encodeURIComponent(desired.tax.code)}`, "GET", undefined, lagoTaxResponseSchema, true),
...desired.plans.map((plan) => this.request(`/plans/${encodeURIComponent(plan.code)}`, "GET", undefined, lagoPlanResponseSchema, true)),
]);
return {
organization,
tax: tax?.tax ?? null,
plans: plans.flatMap((response) => (response ? [{ ...response.plan, taxes: response.plan.taxes ?? [] }] : [])),
};
}
async applyTax(catalog: DesiredLagoCatalog, update: boolean): Promise<void> {
await this.assertOrganization();
await this.request(
update ? `/taxes/${encodeURIComponent(catalog.tax.code)}` : "/taxes",
update ? "PUT" : "POST",
toLagoTaxPayload(catalog.tax),
lagoTaxResponseSchema
);
}
async applyPlan(plan: DesiredLagoPlan, update: boolean): Promise<void> {
await this.assertOrganization();
await this.request(
update ? `/plans/${encodeURIComponent(plan.code)}` : "/plans",
update ? "PUT" : "POST",
toLagoPlanPayload(plan, update),
lagoPlanResponseSchema
);
}
private async assertOrganization(): Promise<LagoCatalogSnapshot["organization"]> {
const response = await this.request("/organizations", "GET", undefined, lagoOrganizationResponseSchema);
if (!response) throw new BillingCatalogOperatorError("billing catalog: Lago organization is unavailable");
const idSha256 = createHash("sha256").update(response.organization.lago_id).digest("hex");
if (response.organization.name !== this.expectedOrganizationName || idSha256 !== this.expectedOrganizationIdSha256) {
throw new BillingCatalogOperatorError("billing catalog: Lago organization does not match the pinned target identity");
}
return { name: response.organization.name, idSha256 };
}
private async request<T>(path: string, method: "GET" | "POST" | "PUT", body: unknown, schema: z.ZodType<T>, allowNotFound = false): Promise<T | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, {
method,
headers: {
authorization: `Bearer ${this.apiKey}`,
accept: "application/json",
...(body === undefined ? {} : { "content-type": "application/json" }),
},
body: body === undefined ? undefined : JSON.stringify(body),
redirect: "error",
signal: controller.signal,
});
if (allowNotFound && response.status === 404) return null;
if (!response.ok) {
throw new BillingCatalogOperatorError(`billing catalog: Lago request failed with status ${response.status}`);
}
const parsed = schema.safeParse(await response.json());
if (!parsed.success) {
throw new BillingCatalogOperatorError("billing catalog: Lago response shape is invalid");
}
return parsed.data;
} catch (error) {
if (error instanceof BillingCatalogOperatorError) throw error;
throw new BillingCatalogOperatorError("billing catalog: Lago request failed");
} finally {
clearTimeout(timeout);
}
}
}
@@ -0,0 +1,101 @@
import { chmod, mkdtemp, readFile, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { buildDesiredLagoCatalog, type LagoCatalogSnapshot } from "./catalog";
import type { BillingCatalogCommand } from "./contracts";
import type { LagoCatalogClient } from "./lago-client";
import { executeBillingCatalogCommand, writeRedactedCatalogSnapshot } from "./sync";
const desired = buildDesiredLagoCatalog();
const emptySnapshot: LagoCatalogSnapshot = {
organization: { name: "HiveGrid Staging", idSha256: "a".repeat(64) },
tax: null,
plans: [],
};
function command(mode: BillingCatalogCommand["mode"], snapshotDirectory = "tmp/test"): BillingCatalogCommand {
return {
target: "staging",
mode,
lagoApiUrl: "https://lago.example.test",
lagoApiKey: "secret",
expectedOrganizationName: "HiveGrid Staging",
expectedOrganizationIdSha256: "a".repeat(64),
snapshotDirectory,
};
}
describe("billing catalog sync", () => {
it("plans without mutating and fails verify on drift", async () => {
const client = {
readCatalog: vi.fn().mockResolvedValue(emptySnapshot),
applyTax: vi.fn(),
applyPlan: vi.fn(),
} as unknown as LagoCatalogClient;
const result = await executeBillingCatalogCommand(command("plan"), client);
expect(result.complete).toBe(false);
expect(client.applyTax).not.toHaveBeenCalled();
await expect(executeBillingCatalogCommand(command("verify"), client)).rejects.toThrow("verification found missing or drifted");
});
it("applies all missing resources and proves convergence", async () => {
const directory = await mkdtemp(join(tmpdir(), "hivegrid-billing-catalog-"));
const convergedSnapshot: LagoCatalogSnapshot = {
organization: emptySnapshot.organization,
tax: {
code: desired.tax.code,
name: desired.tax.name,
description: desired.tax.description,
rate: desired.tax.rate,
applied_to_organization: desired.tax.appliedToOrganization,
},
plans: desired.plans.map((plan) => ({
code: plan.code,
name: plan.name,
invoice_display_name: plan.invoiceDisplayName,
description: plan.description,
interval: plan.interval,
amount_cents: plan.amountCents,
amount_currency: plan.amountCurrency,
pay_in_advance: plan.payInAdvance,
taxes: plan.taxCodes.map((code) => ({ code })),
metadata: { ...plan.metadata },
})),
};
const client = {
readCatalog: vi.fn().mockResolvedValueOnce(emptySnapshot).mockResolvedValueOnce(convergedSnapshot),
applyTax: vi.fn(),
applyPlan: vi.fn(),
} as unknown as LagoCatalogClient;
const result = await executeBillingCatalogCommand(command("apply", directory), client);
expect(result.complete).toBe(true);
expect(client.applyTax).toHaveBeenCalledOnce();
expect(client.applyPlan).toHaveBeenCalledTimes(desired.plans.length);
expect(result.snapshotPath).toContain(directory);
});
it("writes only redacted catalog state with owner-only permissions", async () => {
const directory = await mkdtemp(join(tmpdir(), "hivegrid-billing-snapshot-"));
await chmod(directory, 0o700);
const path = await writeRedactedCatalogSnapshot({
directory,
target: "production",
snapshot: emptySnapshot,
assessment: {
catalogVersion: desired.version,
catalogDigestSha256: desired.digestSha256,
complete: false,
actions: [],
},
now: new Date("2026-07-29T08:00:00.000Z"),
});
const contents = await readFile(path, "utf8");
expect(contents).not.toContain("secret");
expect(contents).toContain(desired.digestSha256);
expect((await stat(path)).mode & 0o777).toBe(0o600);
});
});
@@ -0,0 +1,134 @@
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { assessLagoCatalog, buildDesiredLagoCatalog, type LagoCatalogAssessment, type LagoCatalogSnapshot } from "./catalog";
import { BillingCatalogOperatorError, parseBillingCatalogCommand, safeBillingCatalogError, type BillingCatalogCommand } from "./contracts";
import { LagoCatalogClient } from "./lago-client";
type BillingCatalogExecutionResult = {
readonly target: BillingCatalogCommand["target"];
readonly mode: BillingCatalogCommand["mode"];
readonly complete: boolean;
readonly catalogVersion: string;
readonly catalogDigestSha256: string;
readonly snapshotPath: string | null;
readonly actions: LagoCatalogAssessment["actions"];
};
function safeTimestamp(now: Date): string {
return now.toISOString().replace(/[:.]/gu, "-");
}
export async function writeRedactedCatalogSnapshot(input: {
directory: string;
target: BillingCatalogCommand["target"];
snapshot: LagoCatalogSnapshot;
assessment: LagoCatalogAssessment;
now?: Date;
}): Promise<string> {
const path = resolve(input.directory, `${input.target}-${safeTimestamp(input.now ?? new Date())}.json`);
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
await writeFile(
path,
`${JSON.stringify(
{
target: input.target,
capturedAt: (input.now ?? new Date()).toISOString(),
catalogVersion: input.assessment.catalogVersion,
catalogDigestSha256: input.assessment.catalogDigestSha256,
snapshot: input.snapshot,
},
null,
2
)}\n`,
{ encoding: "utf8", mode: 0o600 }
);
return path;
}
export async function executeBillingCatalogCommand(
command: BillingCatalogCommand,
client = new LagoCatalogClient({
apiUrl: command.lagoApiUrl,
apiKey: command.lagoApiKey,
expectedOrganizationName: command.expectedOrganizationName,
expectedOrganizationIdSha256: command.expectedOrganizationIdSha256,
})
): Promise<BillingCatalogExecutionResult> {
const desired = buildDesiredLagoCatalog();
const initialSnapshot = await client.readCatalog(desired);
const initialAssessment = assessLagoCatalog(initialSnapshot, desired);
if (command.mode === "plan") {
return {
target: command.target,
mode: command.mode,
complete: initialAssessment.complete,
catalogVersion: desired.version,
catalogDigestSha256: desired.digestSha256,
snapshotPath: null,
actions: initialAssessment.actions,
};
}
if (command.mode === "verify") {
if (!initialAssessment.complete) {
throw new BillingCatalogOperatorError("billing catalog: verification found missing or drifted Lago resources");
}
return {
target: command.target,
mode: command.mode,
complete: true,
catalogVersion: desired.version,
catalogDigestSha256: desired.digestSha256,
snapshotPath: null,
actions: initialAssessment.actions,
};
}
const snapshotPath = await writeRedactedCatalogSnapshot({
directory: command.snapshotDirectory,
target: command.target,
snapshot: initialSnapshot,
assessment: initialAssessment,
});
for (const action of initialAssessment.actions) {
if (action.action === "noop") continue;
if (action.resource === "tax") {
await client.applyTax(desired, action.action === "update");
continue;
}
const plan = desired.plans.find((candidate) => candidate.code === action.code);
if (!plan) throw new BillingCatalogOperatorError("billing catalog: desired Lago plan is unavailable");
await client.applyPlan(plan, action.action === "update");
}
const finalAssessment = assessLagoCatalog(await client.readCatalog(desired), desired);
if (!finalAssessment.complete) {
throw new BillingCatalogOperatorError("billing catalog: apply did not converge to the canonical contract");
}
return {
target: command.target,
mode: command.mode,
complete: true,
catalogVersion: desired.version,
catalogDigestSha256: desired.digestSha256,
snapshotPath,
actions: finalAssessment.actions,
};
}
async function main(): Promise<void> {
try {
const command = parseBillingCatalogCommand(process.argv.slice(2), process.env);
const result = await executeBillingCatalogCommand(command);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
} catch (error) {
process.stderr.write(`${safeBillingCatalogError(error)}\n`);
process.exitCode = 1;
}
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
void main();
}