πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(billing): implement CHB api client (#15462)
Steffen Schmitze8cdd3d6d407
diff --git a/.env.dev.example b/.env.dev.exampleindex d91e3efa4a..fef4309b4e 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -279,3 +279,13 @@ CLICKHOUSE_DISABLE_TOP_K_THROUGH_JOIN=auto# CHB's EventBridge bus for project lifecycle events, authenticated by IAM from# the task role; unset = no events emitted.# CLICKHOUSE_BILLING_EVENT_BUS_ARN=+# CHB REST API base url; unset = the CHB billing service refuses to construct.+# CLICKHOUSE_BILLING_BASE_URL=+# Auth0 client credentials for CHB's REST API (not the event bus, which uses+# IAM). CHB verifies the token against its Auth0 tenant, so all three are+# required; any one missing = the CHB billing service refuses to construct.+# CLICKHOUSE_BILLING_AUTH0_DOMAIN=+# CLICKHOUSE_BILLING_AUTH0_CLIENT_ID=+# CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET=+# CHB's resource-server identifier; defaults to billing-api.+# CLICKHOUSE_BILLING_AUTH0_AUDIENCE=diff --git a/.env.prod.example b/.env.prod.exampleindex 7a8d181aa0..6d8fbc3bdf 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -443,3 +443,13 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# CHB's EventBridge bus for project lifecycle events, authenticated by IAM from# the task role; unset = no events emitted.# CLICKHOUSE_BILLING_EVENT_BUS_ARN=+# CHB REST API base url; unset = the CHB billing service refuses to construct.+# CLICKHOUSE_BILLING_BASE_URL=+# Auth0 client credentials for CHB's REST API (not the event bus, which uses+# IAM). CHB verifies the token against its Auth0 tenant, so all three are+# required; any one missing = the CHB billing service refuses to construct.+# CLICKHOUSE_BILLING_AUTH0_DOMAIN=+# CLICKHOUSE_BILLING_AUTH0_CLIENT_ID=+# CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET=+# CHB's resource-server identifier; defaults to billing-api.+# CLICKHOUSE_BILLING_AUTH0_AUDIENCE=diff --git a/web/src/__tests__/server/chbCheckoutClaim.servertest.ts b/web/src/__tests__/server/chbCheckoutClaim.servertest.tsnew file mode 100644index 0000000000..696956ea4f--- /dev/null+++ b/web/src/__tests__/server/chbCheckoutClaim.servertest.ts@@ -0,0 +1,188 @@+/**+ * Postgres-backed half of the ChbBillingService suite.+ *+ * The unit suite (`unit/chbBillingService.servertest.ts`) mocks `$executeRaw`,+ * so it can prove *that* checkout claims the CH organization id but not that the+ * statement doing it is correct. These cases run the real guarded UPDATE against+ * a real row, because its failure mode is a silent one: a merge that writes the+ * wrong JSON shape makes `parseDbOrg` discard the org's entire cloudConfig on+ * every later read, not just the field it got wrong. That takes the org's+ * rate-limit and lookback overrides with it, hides the CHB state this very+ * checkout just wrote β so `getBillingProvider` routes the org back to Stripe β+ * and makes `hasPaidBillingState` report a paying org as unpaid, which is the+ * gate keeping it from being ingestion-blocked at the free-tier threshold.+ */++import { randomUUID } from "crypto";++import { parseDbOrg } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ type ChbApiClient,+ type ChbCheckoutSession,+} from "@/src/ee/features/billing/server/chb/chbApiClient";+import { ChbBillingService } from "@/src/ee/features/billing/server/chb/chbBillingService";+import { mapChbPlanCodeToStripeProductId } from "@/src/ee/features/billing/utils/chbCatalogue";+import { type OrgAuthedContext } from "@/src/server/api/trpc";++const CORE_PRODUCT_ID = mapChbPlanCodeToStripeProductId("core")!;++let orgId: string;+let chOrganizationId: string;++/**+ * Set `cloud_config` through raw SQL rather than Prisma: the cases below turn on+ * the difference between a JSON-null and a SQL NULL, and Prisma's JSON handling+ * abstracts exactly that away.+ */+const setCloudConfig = async (json: string | null) => {+ if (json === null) {+ await prisma.$executeRaw`UPDATE organizations SET cloud_config = NULL WHERE id = ${orgId}`;+ return;+ }+ await prisma.$executeRaw`UPDATE organizations SET cloud_config = ${json}::jsonb WHERE id = ${orgId}`;+};++const rawCloudConfig = async (): Promise<unknown> => {+ const [row] = await prisma.$queryRaw<{ cloud_config: unknown }[]>`+ SELECT cloud_config FROM organizations WHERE id = ${orgId}+ `;+ return row?.cloud_config ?? null;+};++/** The org as the rest of the app sees it β through parseDbOrg. */+const parsedCloudConfig = async () => {+ const org = await prisma.organization.findUniqueOrThrow({+ where: { id: orgId },+ });+ return parseDbOrg(org).cloudConfig;+};++const clientMock = {+ createCheckoutSession: vi.fn(),+} as unknown as ChbApiClient;++const service = () => {+ const ctx = {+ prisma,+ session: {+ orgId,+ orgRole: "OWNER",+ user: { id: `user-${randomUUID()}`, email: "[email protected]" },+ },+ } as unknown as OrgAuthedContext;+ return new ChbBillingService(clientMock, ctx);+};++describe("chbBillingService checkout claim (postgres)", () => {+ beforeEach(async () => {+ orgId = `org-chb-claim-${randomUUID()}`;+ chOrganizationId = randomUUID();+ await prisma.organization.create({+ data: { id: orgId, name: "CHB Claim Test Org" },+ });+ vi.mocked(clientMock.createCheckoutSession).mockResolvedValue({+ url: "https://billing.clickhouse.test/checkout/abc",+ organizationId: chOrganizationId,+ } satisfies ChbCheckoutSession);+ });++ afterEach(async () => {+ await prisma.auditLog.deleteMany({ where: { orgId } });+ await prisma.organization.deleteMany({ where: { id: orgId } });+ vi.resetAllMocks();+ });++ it("claims the CH organization id when the org has no cloudConfig at all", async () => {+ await setCloudConfig(null);++ await service().createCheckoutSession(orgId, CORE_PRODUCT_ID);++ expect(await parsedCloudConfig()).toMatchObject({+ clickhouse: { organizationId: chOrganizationId },+ });+ });++ it("keeps unrelated cloudConfig keys when it claims", async () => {+ await setCloudConfig(+ JSON.stringify({+ monthlyObservationLimit: 50_000,+ defaultLookBackDays: 30,+ }),+ );++ await service().createCheckoutSession(orgId, CORE_PRODUCT_ID);++ expect(await parsedCloudConfig()).toMatchObject({+ monthlyObservationLimit: 50_000,+ defaultLookBackDays: 30,+ clickhouse: { organizationId: chOrganizationId },+ });+ });++ it("merges into an existing clickhouse sub-object instead of replacing it", async () => {+ // A webhook may have written plan state before checkout returns; the claim+ // rebuilds the sub-object from the row, so that state must survive.+ await setCloudConfig(JSON.stringify({ clickhouse: { planCode: "core" } }));++ await service().createCheckoutSession(orgId, CORE_PRODUCT_ID);++ expect(await parsedCloudConfig()).toMatchObject({+ clickhouse: { organizationId: chOrganizationId, planCode: "core" },+ });+ });++ /**+ * The regression this file exists for. A stored JSON-null `clickhouse` passes+ * the WHERE guard (`-> 'organizationId'` on a JSON-null yields SQL NULL, which+ * the guard coalesces to 'null'), so the merge runs β and without NULLIF,+ * `'null'::jsonb || '{...}'::jsonb` concatenates into `[null, {...}]` rather+ * than merging. That array fails CloudConfigSchema and takes the whole+ * cloudConfig down with it on every later read.+ *+ * The sibling key is an observation limit rather than a `plan` override on+ * purpose: `plan` and `stripe.customerId` are both checkout interlocks, so an+ * org carrying either never reaches this statement.+ */+ it("merges a JSON-null clickhouse value without corrupting cloudConfig", async () => {+ await setCloudConfig(+ JSON.stringify({ monthlyObservationLimit: 50_000, clickhouse: null }),+ );++ await service().createCheckoutSession(orgId, CORE_PRODUCT_ID);++ // The stored shape stays an object, so the row still parses...+ expect(await rawCloudConfig()).toEqual({+ monthlyObservationLimit: 50_000,+ clickhouse: { organizationId: chOrganizationId },+ });+ // ...and the override survives, rather than the whole config reading as+ // null β which would also hide the CHB state this checkout just wrote.+ expect(await parsedCloudConfig()).toMatchObject({+ monthlyObservationLimit: 50_000,+ clickhouse: { organizationId: chOrganizationId },+ });+ });++ it("refuses a second claim once an organization id is stored", async () => {+ await setCloudConfig(+ JSON.stringify({ clickhouse: { organizationId: chOrganizationId } }),+ );+ // CHB hands back a different org for a request that asked to reuse one:+ // sticky routing is broken, so checkout must refuse rather than clobber.+ vi.mocked(clientMock.createCheckoutSession).mockResolvedValue({+ url: "https://billing.clickhouse.test/checkout/def",+ organizationId: randomUUID(),+ } satisfies ChbCheckoutSession);++ await expect(+ service().createCheckoutSession(orgId, CORE_PRODUCT_ID),+ ).rejects.toThrow(/different organization/i);++ expect(await parsedCloudConfig()).toMatchObject({+ clickhouse: { organizationId: chOrganizationId },+ });+ });+});diff --git a/web/src/__tests__/server/unit/chbAccessToken.servertest.ts b/web/src/__tests__/server/unit/chbAccessToken.servertest.tsnew file mode 100644index 0000000000..d1b39205a3--- /dev/null+++ b/web/src/__tests__/server/unit/chbAccessToken.servertest.ts@@ -0,0 +1,189 @@+import type * as SharedServer from "@langfuse/shared/src/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual = await importOriginal<typeof SharedServer>();+ return { ...actual, logger: mocks.logger };+});++import {+ ChbAccessTokenProvider,+ ChbAuthError,+} from "@/src/ee/features/billing/server/chb/chbAccessToken";++const AUTH0_DOMAIN = "chb-tenant.eu.auth0.com";+const TOKEN_URL = `https://${AUTH0_DOMAIN}/oauth/token`;++const jsonResponse = (status: number, body: unknown) => ({+ status,+ ok: status >= 200 && status < 300,+ json: async () => body,+});++const fetchMock = vi.fn();++const provider = () =>+ new ChbAccessTokenProvider({+ auth0Domain: AUTH0_DOMAIN,+ clientId: "client-id",+ clientSecret: "client-secret",+ audience: "billing-api",+ });++const grant = (accessToken: string, expiresIn = 86_400) =>+ jsonResponse(200, { access_token: accessToken, expires_in: expiresIn });++describe("chbAccessToken", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it("exchanges the client credentials for an access token", async () => {+ fetchMock.mockResolvedValue(grant("token-1"));++ await expect(provider().getToken()).resolves.toBe("token-1");++ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe(TOKEN_URL);+ expect(init.method).toBe("POST");+ // The Auth0 client uses client_secret_post, so the credentials belong in+ // the body β not a Basic header.+ expect(JSON.parse(init.body)).toEqual({+ grant_type: "client_credentials",+ client_id: "client-id",+ client_secret: "client-secret",+ audience: "billing-api",+ });+ // The secret must not ride along to a redirect target.+ expect(init.redirect).toBe("error");+ });++ it("caches the token instead of minting one per request", async () => {+ fetchMock.mockResolvedValue(grant("token-1"));+ const tokens = provider();++ await tokens.getToken();+ await tokens.getToken();+ await tokens.getToken();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("collapses concurrent first calls into one grant", async () => {+ fetchMock.mockResolvedValue(grant("token-1"));+ const tokens = provider();++ const results = await Promise.all([+ tokens.getToken(),+ tokens.getToken(),+ tokens.getToken(),+ ]);++ // A burst of billing requests must not stampede Auth0.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(results).toEqual(["token-1", "token-1", "token-1"]);+ });++ it("mints a new token after invalidate()", async () => {+ fetchMock+ .mockResolvedValueOnce(grant("token-1"))+ .mockResolvedValueOnce(grant("token-2"));+ const tokens = provider();++ await expect(tokens.getToken()).resolves.toBe("token-1");+ tokens.invalidate();+ await expect(tokens.getToken()).resolves.toBe("token-2");+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("renews ahead of expiry rather than at it", async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(grant("token-1", 3_600))+ .mockResolvedValueOnce(grant("token-2", 3_600));+ const tokens = provider();++ await expect(tokens.getToken()).resolves.toBe("token-1");++ // Inside the lifetime but within the renewal margin: a token that expires+ // in transit would come back as a 401 from CHB.+ vi.advanceTimersByTime(3_400 * 1000);+ await expect(tokens.getToken()).resolves.toBe("token-2");+ });++ it("still caches a token whose lifetime is shorter than the margin", async () => {+ vi.useFakeTimers();+ fetchMock.mockResolvedValue(grant("token-1", 60));+ const tokens = provider();++ await tokens.getToken();+ vi.advanceTimersByTime(25 * 1000);+ await tokens.getToken();++ // Otherwise every single call would re-grant.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("keeps a usable buffer for a token barely longer than the margin", async () => {+ vi.useFakeTimers();+ fetchMock+ .mockResolvedValueOnce(grant("token-1", 310))+ .mockResolvedValueOnce(grant("token-2", 310));+ const tokens = provider();++ await expect(tokens.getToken()).resolves.toBe("token-1");++ // Subtracting the full margin from a 310s token would leave a 10s buffer+ // before real expiry, so the margin has to be capped at half the lifetime:+ // this call is past that half and must re-grant rather than hand back a+ // token that can expire in transit.+ vi.advanceTimersByTime(160 * 1000);+ await expect(tokens.getToken()).resolves.toBe("token-2");+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("raises ChbAuthError when the grant is rejected", async () => {+ fetchMock.mockResolvedValue(+ jsonResponse(401, { error: "access_denied", error_description: "..." }),+ );++ const error = await provider()+ .getToken()+ .catch((e) => e);++ expect(error).toBeInstanceOf(ChbAuthError);+ expect(error.status).toBe(401);+ // Auth0 error payloads echo request parameters, so they stay out of logs.+ expect(mocks.logger.error).toHaveBeenCalledWith(+ "[CHB Auth] Client-credentials grant failed",+ { status: 401, audience: "billing-api" },+ );+ });++ it("raises ChbAuthError on a payload without a usable token", async () => {+ fetchMock.mockResolvedValue(jsonResponse(200, { expires_in: 86_400 }));++ await expect(provider().getToken()).rejects.toBeInstanceOf(ChbAuthError);+ });++ it("retries the grant after a failure instead of latching onto it", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse(500, {}))+ .mockResolvedValueOnce(grant("token-1"));+ const tokens = provider();++ await expect(tokens.getToken()).rejects.toBeInstanceOf(ChbAuthError);+ // The single-flight promise must not outlive its own rejection.+ await expect(tokens.getToken()).resolves.toBe("token-1");+ });+});diff --git a/web/src/__tests__/server/unit/chbApiClient.servertest.ts b/web/src/__tests__/server/unit/chbApiClient.servertest.tsnew file mode 100644index 0000000000..a4bce494ad--- /dev/null+++ b/web/src/__tests__/server/unit/chbApiClient.servertest.ts@@ -0,0 +1,478 @@+import type * as SharedServer from "@langfuse/shared/src/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ env: {+ CLICKHOUSE_BILLING_BASE_URL: undefined as string | undefined,+ CLICKHOUSE_BILLING_AUTH0_DOMAIN: undefined as string | undefined,+ CLICKHOUSE_BILLING_AUTH0_CLIENT_ID: undefined as string | undefined,+ CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET: undefined as string | undefined,+ CLICKHOUSE_BILLING_AUTH0_AUDIENCE: "billing-api",+ },+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++vi.mock("@/src/env.mjs", () => ({ env: mocks.env }));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual = await importOriginal<typeof SharedServer>();+ return { ...actual, logger: mocks.logger };+});++import {+ buildChbApiClientFromEnv,+ ChbApiClient,+ ChbApiError,+ ChbPaymentRequiredError,+ getChbApiClient,+ resetChbApiClientForTests,+} from "@/src/ee/features/billing/server/chb/chbApiClient";++const CH_ORG_ID = "6dd6ab1d-9e8d-4c1a-8b4f-9a3d1e2c4b5a";+const AUTH0_DOMAIN = "chb-tenant.eu.auth0.com";+const TOKEN_URL = `https://${AUTH0_DOMAIN}/oauth/token`;++/** Shape a `fetch` result the client will accept, or one it must reject. */+const jsonResponse = (status: number, body: unknown) => ({+ status,+ ok: status >= 200 && status < 300,+ json: async () => body,+});++/**+ * One mock for both legs the client makes: the Auth0 client-credentials grant+ * and the CHB request itself. Responses for the CHB leg are queued, so a test+ * can drive a 401-then-200 replay.+ */+const chbResponses: ReturnType<typeof jsonResponse>[] = [];+let tokenCounter = 0;++const fetchMock = vi.fn(async (url: URL | string, _init: RequestInit) => {+ if (String(url) === TOKEN_URL) {+ tokenCounter += 1;+ return jsonResponse(200, {+ access_token: `chb-access-token-${tokenCounter}`,+ expires_in: 86_400,+ });+ }+ return chbResponses.shift() ?? jsonResponse(200, {});+});++/** Queue the CHB leg's response(s), in order. */+const onChb = (...responses: ReturnType<typeof jsonResponse>[]) => {+ chbResponses.push(...responses);+};++const tokenCalls = () =>+ fetchMock.mock.calls.filter((call) => String(call[0]) === TOKEN_URL);++const chbCalls = () =>+ fetchMock.mock.calls.filter((call) => String(call[0]) !== TOKEN_URL);++/** The client's last request to CHB itself, as (url, init). */+const lastChbCall = () => {+ const call = chbCalls().at(-1);+ if (!call) throw new Error("the client never called CHB");+ return { url: call[0] as URL, init: call[1] };+};++const headersOf = (init: RequestInit) => init.headers as Record<string, string>;++const client = () =>+ new ChbApiClient({+ // Deliberately carries a path prefix: the URL join must keep it.+ baseUrl: "https://chb.example.com/api/v1",+ auth: {+ auth0Domain: AUTH0_DOMAIN,+ clientId: "client-id",+ clientSecret: "client-secret",+ audience: "billing-api",+ },+ });++describe("chbApiClient", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ chbResponses.length = 0;+ tokenCounter = 0;+ mocks.env.CLICKHOUSE_BILLING_BASE_URL = undefined;+ mocks.env.CLICKHOUSE_BILLING_AUTH0_DOMAIN = undefined;+ mocks.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_ID = undefined;+ mocks.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET = undefined;+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ describe("authentication", () => {+ it("presents the Auth0 access token and never follows a redirect", async () => {+ onChb(jsonResponse(200, { url: "https://pay.example.com/s/1" }));++ await client().createPortalSession({+ chOrganizationId: CH_ORG_ID,+ returnUrl: "https://cloud.langfuse.com/back",+ });++ // CHB verifies the token against Auth0, so a static secret would 401.+ const { init } = lastChbCall();+ expect(headersOf(init).authorization).toBe("Bearer chb-access-token-1");+ // A redirect would replay the token against the redirect target.+ expect(init.redirect).toBe("error");+ });++ it("reuses one token across requests", async () => {+ onChb(jsonResponse(200, { id: "bundle_1" }), jsonResponse(200, {}));+ const chb = client();++ await chb.getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "b1" });+ await chb.clearScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "b1",+ });++ expect(tokenCalls()).toHaveLength(1);+ expect(chbCalls()).toHaveLength(2);+ });++ it("mints a fresh token and replays once when CHB rejects the token", async () => {+ onChb(+ jsonResponse(401, { error: "Invalid or expired token" }),+ jsonResponse(200, {}),+ );++ await client().setScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "b1",+ change: { type: "cancel", when: "billing_cycle_end" },+ idempotencyKey: "chb.bundle.scheduled.set:bundleId=b1:op=abc",+ });++ expect(tokenCalls()).toHaveLength(2);+ const [first, second] = chbCalls();+ expect(headersOf(first![1]).authorization).toBe(+ "Bearer chb-access-token-1",+ );+ expect(headersOf(second![1]).authorization).toBe(+ "Bearer chb-access-token-2",+ );+ // The replay must stay idempotent on CHB's side.+ expect(headersOf(second![1])["Idempotency-Key"]).toBe(+ "chb.bundle.scheduled.set:bundleId=b1:op=abc",+ );+ });++ it("surfaces a 401 that survives the replay", async () => {+ onChb(jsonResponse(401, {}), jsonResponse(401, {}));++ const error = await client()+ .getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "b1" })+ .catch((e) => e);++ // One replay, not a loop.+ expect(chbCalls()).toHaveLength(2);+ expect(error).toBeInstanceOf(ChbApiError);+ expect(error.status).toBe(401);+ });+ });++ describe("request wiring", () => {+ it("keeps the base url path prefix when joining the request path", async () => {+ onChb(jsonResponse(200, { id: "bundle_1" }));++ await client().getBundle({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ });++ expect(lastChbCall().url.toString()).toBe(+ "https://chb.example.com/api/v1/bundles/bundle_1?fields=plan%2Cperiod%2Cpayment%2Cscheduled",+ );+ });++ it("url-encodes the bundle id into the path", async () => {+ onChb(jsonResponse(202, {}));++ await client().clearScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "../admin/bundles/other",+ });++ // Escaping matters: an unencoded id would let a caller-supplied value+ // climb out of the bundles collection.+ expect(lastChbCall().url.pathname).toBe(+ "/api/v1/bundles/..%2Fadmin%2Fbundles%2Fother/scheduled",+ );+ });++ it("scopes org endpoints with CH-Organization-Id and omits it elsewhere", async () => {+ onChb(jsonResponse(200, { id: "bundle_1" }));+ await client().getBundle({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ });+ expect(headersOf(lastChbCall().init)["CH-Organization-Id"]).toBe(+ CH_ORG_ID,+ );++ onChb(+ jsonResponse(200, {+ url: "https://pay.example.com/c/1",+ organizationId: CH_ORG_ID,+ }),+ );+ await client().createCheckoutSession({+ email: "[email protected]",+ planCode: "pro",+ returnUrl: "https://cloud.langfuse.com/back",+ });+ // Checkout creates the CH organization, so there is none to scope to yet.+ expect(+ headersOf(lastChbCall().init)["CH-Organization-Id"],+ ).toBeUndefined();+ });++ it("sets content-type only when there is a body", async () => {+ onChb(jsonResponse(202, {}));+ await client().setScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ change: {+ type: "downgrade",+ when: "billing_cycle_end",+ planCode: "core",+ },+ });+ const withBody = lastChbCall();+ expect(headersOf(withBody.init)["content-type"]).toBe("application/json");+ expect(JSON.parse(withBody.init.body as string)).toEqual({+ type: "downgrade",+ when: "billing_cycle_end",+ planCode: "core",+ });++ onChb(jsonResponse(202, {}));+ await client().clearScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ });+ const withoutBody = lastChbCall();+ expect(withoutBody.init.method).toBe("DELETE");+ expect(withoutBody.init.body).toBeUndefined();+ expect(headersOf(withoutBody.init)["content-type"]).toBeUndefined();+ });++ it("forwards an idempotency key as a header, and omits it when absent", async () => {+ onChb(jsonResponse(202, {}));+ await client().setScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ change: { type: "cancel", when: "billing_cycle_end" },+ idempotencyKey: "chb.bundle.scheduled.set:bundleId=bundle_1:op=abc",+ });+ expect(headersOf(lastChbCall().init)["Idempotency-Key"]).toBe(+ "chb.bundle.scheduled.set:bundleId=bundle_1:op=abc",+ );++ onChb(jsonResponse(202, {}));+ await client().setScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ change: { type: "cancel", when: "billing_cycle_end" },+ });+ expect(headersOf(lastChbCall().init)["Idempotency-Key"]).toBeUndefined();+ });+ });++ describe("error mapping", () => {+ it("maps 409 to ChbPaymentRequiredError", async () => {+ onChb(jsonResponse(409, { error: "no_payment_method" }));++ const error = await client()+ .setScheduledChange({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ change: { type: "upgrade", when: "immediate", planCode: "team" },+ })+ .catch((e) => e);++ // Callers branch on the subclass, so both the class and the 409 status+ // are part of the contract.+ expect(error).toBeInstanceOf(ChbPaymentRequiredError);+ expect(error).toBeInstanceOf(ChbApiError);+ expect(error.status).toBe(409);+ expect(error.body).toEqual({ error: "no_payment_method" });+ // A 409 is an expected UX branch, not an incident.+ expect(mocks.logger.error).not.toHaveBeenCalled();+ });++ it("maps any other non-2xx to ChbApiError and logs it", async () => {+ onChb(jsonResponse(503, { error: "unavailable" }));++ const error = await client()+ .getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "bundle_1" })+ .catch((e) => e);++ expect(error).toBeInstanceOf(ChbApiError);+ expect(error).not.toBeInstanceOf(ChbPaymentRequiredError);+ expect(error.status).toBe(503);+ expect(mocks.logger.error).toHaveBeenCalledTimes(1);+ });++ it("does not fail on a non-2xx with an unparsable body", async () => {+ onChb({+ status: 502,+ ok: false,+ json: async () => {+ throw new Error("not json");+ },+ });++ const error = await client()+ .getBundle({ chOrganizationId: CH_ORG_ID, bundleId: "bundle_1" })+ .catch((e) => e);++ expect(error).toBeInstanceOf(ChbApiError);+ expect(error.status).toBe(502);+ expect(error.body).toBeUndefined();+ });+ });++ describe("response parsing", () => {+ it("ignores unknown fields so additive CHB changes cannot break us", async () => {+ onChb(+ jsonResponse(200, {+ id: "bundle_1",+ plan: { planCode: "team", tierName: "Team", extra: true },+ period: { startDate: "2026-08-01T00:00:00Z" },+ payment: { status: "active", provider: { customerId: "cus_1" } },+ unknownTopLevel: { nested: 1 },+ }),+ );++ const bundle = await client().getBundle({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ });++ expect(bundle.id).toBe("bundle_1");+ expect(bundle.plan?.planCode).toBe("team");+ expect(bundle.payment?.provider?.customerId).toBe("cus_1");+ // Nothing required beyond `id`, so a sparse bundle still parses.+ expect(bundle.scheduled).toBeUndefined();+ });++ it("defaults the invoice list to empty when CHB omits the key", async () => {+ onChb(jsonResponse(200, {}));++ await expect(+ client().listInvoices({+ chOrganizationId: CH_ORG_ID,+ bundleId: "bundle_1",+ }),+ ).resolves.toEqual([]);+ });++ it("rejects a checkout session without a uuid organization id", async () => {+ // The id is persisted into cloudConfig, where the stored schema demands a+ // uuid β rejecting here keeps a bad id from ever reaching the database.+ onChb(+ jsonResponse(200, {+ url: "https://pay.example.com/c/1",+ organizationId: "not-a-uuid",+ }),+ );++ await expect(+ client().createCheckoutSession({+ email: "[email protected]",+ planCode: "pro",+ returnUrl: "https://cloud.langfuse.com/back",+ }),+ ).rejects.toThrow();+ });+ });++ describe("buildChbApiClientFromEnv", () => {+ const setAll = () => {+ mocks.env.CLICKHOUSE_BILLING_BASE_URL = "https://chb.example.com";+ mocks.env.CLICKHOUSE_BILLING_AUTH0_DOMAIN = AUTH0_DOMAIN;+ mocks.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_ID = "client-id";+ mocks.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET = "client-secret";+ };++ it.each([+ "CLICKHOUSE_BILLING_BASE_URL",+ "CLICKHOUSE_BILLING_AUTH0_DOMAIN",+ "CLICKHOUSE_BILLING_AUTH0_CLIENT_ID",+ "CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET",+ ] as const)("returns null when %s is missing", (missing) => {+ setAll();+ mocks.env[missing] = undefined;+ // Fail closed: a partly configured deployment must not call CHB at all.+ expect(buildChbApiClientFromEnv()).toBeNull();+ });++ it("builds a client once every credential is present", () => {+ setAll();+ expect(buildChbApiClientFromEnv()).toBeInstanceOf(ChbApiClient);+ });+ });++ describe("getChbApiClient", () => {+ const setAll = () => {+ mocks.env.CLICKHOUSE_BILLING_BASE_URL = "https://chb.example.com";+ mocks.env.CLICKHOUSE_BILLING_AUTH0_DOMAIN = AUTH0_DOMAIN;+ mocks.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_ID = "client-id";+ mocks.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET = "client-secret";+ };++ beforeEach(() => resetChbApiClientForTests());+ afterEach(() => resetChbApiClientForTests());++ /**+ * The dispatch layer resolves a billing service per tRPC request. If that+ * handed back a fresh client each time, every billing call would mint a new+ * Auth0 token β the client's token cache and single-flight only do anything+ * when one instance is shared.+ */+ it("hands every caller the same client", () => {+ setAll();+ const first = getChbApiClient();+ expect(first).toBeInstanceOf(ChbApiClient);+ expect(getChbApiClient()).toBe(first);+ expect(getChbApiClient()).toBe(first);+ });++ it("mints one token across calls made through the shared client", async () => {+ setAll();+ onChb(jsonResponse(200, { url: "https://chb.example.com/portal" }));+ onChb(jsonResponse(200, { url: "https://chb.example.com/portal" }));++ // Two separate resolutions, as two billing procedures in one page load.+ await getChbApiClient()!.createPortalSession({+ chOrganizationId: CH_ORG_ID,+ returnUrl: "https://cloud.langfuse.com/return",+ });+ await getChbApiClient()!.createPortalSession({+ chOrganizationId: CH_ORG_ID,+ returnUrl: "https://cloud.langfuse.com/return",+ });++ expect(chbCalls()).toHaveLength(2);+ expect(tokenCalls()).toHaveLength(1);+ });++ it("caches the unconfigured verdict instead of re-reading env", () => {+ setAll();+ mocks.env.CLICKHOUSE_BILLING_BASE_URL = undefined;+ expect(getChbApiClient()).toBeNull();++ // Env cannot change under a running process; a later call must not+ // suddenly start talking to CHB.+ setAll();+ expect(getChbApiClient()).toBeNull();+ });+ });+});diff --git a/web/src/__tests__/server/unit/chbBillingService.servertest.ts b/web/src/__tests__/server/unit/chbBillingService.servertest.tsnew file mode 100644index 0000000000..66f2240b4a--- /dev/null+++ b/web/src/__tests__/server/unit/chbBillingService.servertest.ts@@ -0,0 +1,692 @@+import type { CloudConfigSchema } from "@langfuse/shared";+import type * as SharedServer from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ env: { NEXTAUTH_URL: "https://cloud.langfuse.com" },+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ auditLog: vi.fn(),+}));++vi.mock("@/src/env.mjs", () => ({ env: mocks.env }));++vi.mock("@/src/features/audit-logs/auditLog", () => ({+ auditLog: mocks.auditLog,+}));++// Only the logger is stubbed: getBillingCycleStart/End are the real cached-cycle+// fallback this service shares with the Stripe path.+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual = await importOriginal<typeof SharedServer>();+ return { ...actual, logger: mocks.logger };+});++import {+ type ChbApiClient,+ ChbPaymentRequiredError,+} from "@/src/ee/features/billing/server/chb/chbApiClient";+import { ChbBillingService } from "@/src/ee/features/billing/server/chb/chbBillingService";+import { mapChbPlanCodeToStripeProductId } from "@/src/ee/features/billing/utils/chbCatalogue";+import { type OrgAuthedContext } from "@/src/server/api/trpc";++const ORG_ID = "org-1";+const CH_ORG_ID = "6dd6ab1d-9e8d-4c1a-8b4f-9a3d1e2c4b5a";+const BUNDLE_ID = "bundle_1";++// Resolved through the bridge rather than hardcoded: the catalogue swaps in+// test-mode product ids, and this suite is about the mapping, not the literals.+const productIdFor = (planCode: string) => {+ const productId = mapChbPlanCodeToStripeProductId(planCode);+ if (!productId)+ throw new Error(`no stripe product for plan code ${planCode}`);+ return productId;+};++const findUnique = vi.fn();+const update = vi.fn();+// Checkout claims the CH organization id with a guarded UPDATE rather than a+// read-then-write, so the claim is a raw statement returning a row count.+const executeRaw = vi.fn();++const clientMock = {+ createCheckoutSession: vi.fn(),+ getBundle: vi.fn(),+ setScheduledChange: vi.fn(),+ clearScheduledChange: vi.fn(),+ listInvoices: vi.fn(),+ createPortalSession: vi.fn(),+};++const ctx = {+ prisma: { organization: { findUnique, update }, $executeRaw: executeRaw },+ session: {+ orgId: ORG_ID,+ orgRole: "OWNER",+ user: { id: "user-1", email: "[email protected]" },+ },+} as unknown as OrgAuthedContext;++const service = () =>+ new ChbBillingService(clientMock as unknown as ChbApiClient, ctx);++/** An org row shaped enough for parseDbOrg and the billing-cycle helpers. */+const stubOrg = (cloudConfig: CloudConfigSchema | null) => ({+ id: ORG_ID,+ name: "Org",+ createdAt: new Date("2026-01-15T00:00:00Z"),+ updatedAt: new Date("2026-01-15T00:00:00Z"),+ cloudConfig,+ cloudBillingCycleAnchor: new Date("2026-01-15T00:00:00Z"),+ cloudCurrentCycleUsage: 4_200,+});++const withOrg = (cloudConfig: CloudConfigSchema | null) => {+ findUnique.mockResolvedValue(stubOrg(cloudConfig));+};++const chbConfig = (+ overrides: Partial<NonNullable<CloudConfigSchema["clickhouse"]>> = {},+): CloudConfigSchema => ({+ clickhouse: {+ organizationId: CH_ORG_ID,+ bundleId: BUNDLE_ID,+ planCode: "pro",+ ...overrides,+ },+});++const trpcCode = async (promise: Promise<unknown>) => {+ const error = await promise.catch((e) => e);+ expect(error).toBeInstanceOf(TRPCError);+ return (error as TRPCError).code;+};++describe("chbBillingService", () => {+ beforeEach(() => {+ // resetAllMocks, not clearAllMocks: the rejection implementations below+ // would otherwise leak into every following test.+ vi.resetAllMocks();+ update.mockResolvedValue({});+ // Default: the claim succeeds. Tests that exercise the race override it.+ executeRaw.mockResolvedValue(1);+ });++ describe("getSubscriptionInfo", () => {+ it("falls back to the cached billing cycle when the org has no bundle", async () => {+ withOrg({ clickhouse: { organizationId: CH_ORG_ID } });++ const info = await service().getSubscriptionInfo(ORG_ID);++ expect(clientMock.getBundle).not.toHaveBeenCalled();+ expect(info.cancellation).toBeNull();+ expect(info.scheduledChange).toBeNull();+ expect(info.hasValidPaymentMethod).toBe(false);+ // Anchored on the 15th, so both bounds land on a 15th.+ expect(info.billingPeriod?.start.getUTCDate()).toBe(15);+ expect(info.billingPeriod?.end.getUTCDate()).toBe(15);+ expect(info.billingPeriod!.end.getTime()).toBeGreaterThan(+ info.billingPeriod!.start.getTime(),+ );+ });++ it("reports a healthy bundle's period and payment status", async () => {+ withOrg(chbConfig());+ clientMock.getBundle.mockResolvedValue({+ id: BUNDLE_ID,+ period: {+ startDate: "2026-08-01T00:00:00Z",+ endDate: "2026-09-01T00:00:00Z",+ },+ payment: { status: "active" },+ });++ const info = await service().getSubscriptionInfo(ORG_ID);++ expect(clientMock.getBundle).toHaveBeenCalledWith({+ chOrganizationId: CH_ORG_ID,+ bundleId: BUNDLE_ID,+ });+ expect(info.billingPeriod).toEqual({+ start: new Date("2026-08-01T00:00:00Z"),+ end: new Date("2026-09-01T00:00:00Z"),+ });+ expect(info.hasValidPaymentMethod).toBe(true);+ expect(info.cancellation).toBeNull();+ expect(info.scheduledChange).toBeNull();+ });++ it("treats any non-active payment status as no valid payment method", async () => {+ withOrg(chbConfig());+ clientMock.getBundle.mockResolvedValue({+ id: BUNDLE_ID,+ payment: { status: "failed" },+ });++ const info = await service().getSubscriptionInfo(ORG_ID);+ expect(info.hasValidPaymentMethod).toBe(false);+ // Unresolvable period β null rather than an invalid Date pair.+ expect(info.billingPeriod).toBeNull();+ });++ it("maps a pending cancellation onto the cancellation field", async () => {+ withOrg(chbConfig());+ clientMock.getBundle.mockResolvedValue({+ id: BUNDLE_ID,+ period: { endDate: "2026-09-01T00:00:00Z" },+ scheduled: { type: "cancel", when: "billing_cycle_end" },+ });++ const info = await service().getSubscriptionInfo(ORG_ID);++ // Unix seconds, like the Stripe path the UI already renders.+ expect(info.cancellation).toEqual({+ cancelAt: Date.parse("2026-09-01T00:00:00Z") / 1000,+ });+ expect(info.scheduledChange).toBeNull();+ });++ it("maps a pending plan switch onto scheduledChange with a bridged product id", async () => {+ withOrg(chbConfig());+ clientMock.getBundle.mockResolvedValue({+ id: BUNDLE_ID,+ period: { endDate: "2026-09-01T00:00:00Z" },+ scheduled: {+ type: "downgrade",+ when: "billing_cycle_end",+ planCode: "core",+ startDate: "2026-09-05T00:00:00Z",+ },+ });++ const info = await service().getSubscriptionInfo(ORG_ID);++ expect(info.cancellation).toBeNull();+ expect(info.scheduledChange).toEqual({+ scheduleId: `chb:${BUNDLE_ID}`,+ // An explicit startDate wins over the period end.+ switchAt: Date.parse("2026-09-05T00:00:00Z") / 1000,+ newProductId: productIdFor("core"),+ message: null,+ });+ });++ it("renders no pending state when the change has no resolvable date", async () => {+ withOrg(chbConfig());+ clientMock.getBundle.mockResolvedValue({+ id: BUNDLE_ID,+ scheduled: { type: "cancel", when: "immediate" },+ });++ const info = await service().getSubscriptionInfo(ORG_ID);+ expect(info.cancellation).toBeNull();+ expect(info.scheduledChange).toBeNull();+ });++ it("renders no pending state for an immediate change on an active period", async () => {+ withOrg(chbConfig());+ clientMock.getBundle.mockResolvedValue({+ id: BUNDLE_ID,+ // An immediate cancellation echoed back while the period is still+ // populated: the date fallback would date it at the cycle end and+ // render a change that has already applied as pending.+ period: {+ startDate: "2026-08-01T00:00:00Z",+ endDate: "2026-09-01T00:00:00Z",+ },+ scheduled: { type: "cancel", when: "immediate" },+ });++ const info = await service().getSubscriptionInfo(ORG_ID);+ expect(info.cancellation).toBeNull();+ expect(info.scheduledChange).toBeNull();+ });+ });++ describe("createCheckoutSession", () => {+ const session = {+ url: "https://pay.example.com/c/1",+ organizationId: CH_ORG_ID,+ };++ it("claims the CH organization id returned by checkout", async () => {+ withOrg(null);+ clientMock.createCheckoutSession.mockResolvedValue(session);++ const url = await service().createCheckoutSession(+ ORG_ID,+ productIdFor("pro"),+ "op-checkout",+ );++ expect(url).toBe(session.url);+ expect(clientMock.createCheckoutSession).toHaveBeenCalledWith({+ organizationId: undefined,+ email: "[email protected]",+ planCode: "pro",+ returnUrl: `https://cloud.langfuse.com/organization/${ORG_ID}/settings/billing`,+ idempotencyKey: `chb.checkout.create:orgId=${ORG_ID}:planCode=pro:op=op-checkout`,+ });+ // Claimed with the guarded statement, never a blind read-then-write.+ expect(executeRaw).toHaveBeenCalledTimes(1);+ expect(update).not.toHaveBeenCalled();+ expect(mocks.auditLog).toHaveBeenCalledTimes(1);+ });++ it("keys the idempotency key on the plan so a plan switch is not replayed", async () => {+ // The dialog keeps one opId across plan re-clicks, so the plan code is+ // what separates "core, then team" into two operations.+ clientMock.createCheckoutSession.mockResolvedValue(session);++ withOrg(null);+ await service().createCheckoutSession(+ ORG_ID,+ productIdFor("core"),+ "op-1",+ );+ withOrg(null);+ await service().createCheckoutSession(+ ORG_ID,+ productIdFor("team"),+ "op-1",+ );++ const keys = clientMock.createCheckoutSession.mock.calls.map(+ ([params]) => params.idempotencyKey,+ );+ expect(new Set(keys).size).toBe(2);+ });++ it("sends no idempotency key without an opId", async () => {+ withOrg(null);+ clientMock.createCheckoutSession.mockResolvedValue(session);++ await service().createCheckoutSession(ORG_ID, productIdFor("pro"));++ // Matches makeIdempotencyKey's contract: no client opId, no claim.+ expect(clientMock.createCheckoutSession).toHaveBeenCalledWith(+ expect.objectContaining({ idempotencyKey: undefined }),+ );+ });++ it("reuses the CH organization from an earlier attempt without rewriting it", async () => {+ withOrg({ clickhouse: { organizationId: CH_ORG_ID } });+ clientMock.createCheckoutSession.mockResolvedValue(session);++ await service().createCheckoutSession(ORG_ID, productIdFor("team"));++ // A retry must recover the same CH org instead of orphaning one.+ expect(clientMock.createCheckoutSession).toHaveBeenCalledWith(+ expect.objectContaining({+ organizationId: CH_ORG_ID,+ planCode: "team",+ }),+ );+ // Already stored, so the retry claims nothing.+ expect(executeRaw).not.toHaveBeenCalled();+ expect(update).not.toHaveBeenCalled();+ });++ it("refuses when a retry comes back with a different CH organization", async () => {+ withOrg({ clickhouse: { organizationId: CH_ORG_ID } });+ clientMock.createCheckoutSession.mockResolvedValue({+ url: session.url,+ organizationId: "11111111-2222-4333-8444-555555555555",+ });++ // Sticky provider routing is broken; clobbering the stored id would point+ // the org at a bundle it never bought.+ expect(+ await trpcCode(+ service().createCheckoutSession(ORG_ID, productIdFor("team")),+ ),+ ).toBe("INTERNAL_SERVER_ERROR");+ expect(executeRaw).not.toHaveBeenCalled();+ });++ it("refuses to persist an id the stored schema rejects", async () => {+ withOrg(null);+ clientMock.createCheckoutSession.mockResolvedValue({+ url: session.url,+ organizationId: "not-a-uuid",+ });++ // Mocking the client bypasses ChbCheckoutSessionSchema, so this covers+ // the service's own write-side gate: a bad id reaching Postgres would+ // make parseDbOrg null the whole cloudConfig on every later read.+ expect(+ await trpcCode(+ service().createCheckoutSession(ORG_ID, productIdFor("pro"), "op-1"),+ ),+ ).toBe("INTERNAL_SERVER_ERROR");+ expect(executeRaw).not.toHaveBeenCalled();+ });++ it("fails closed when a concurrent checkout wins the claim", async () => {+ withOrg(null);+ clientMock.createCheckoutSession.mockResolvedValue(session);+ executeRaw.mockResolvedValue(0);++ // Returning this URL would send the user to a checkout whose webhook+ // resolves to a CH org the Langfuse row no longer points at.+ expect(+ await trpcCode(+ service().createCheckoutSession(ORG_ID, productIdFor("pro"), "op-1"),+ ),+ ).toBe("CONFLICT");+ expect(mocks.auditLog).not.toHaveBeenCalled();+ expect(mocks.logger.error).toHaveBeenCalledWith(+ "chbBillingService.checkout.session.create:claimLost",+ expect.objectContaining({ orphanedChOrganizationId: CH_ORG_ID }),+ );+ });++ it("leaves the org row untouched when CHB checkout fails", async () => {+ withOrg(null);+ clientMock.createCheckoutSession.mockRejectedValue(+ new Error("CHB unavailable"),+ );++ await expect(+ service().createCheckoutSession(ORG_ID, productIdFor("pro"), "op-1"),+ ).rejects.toThrow();+ expect(executeRaw).not.toHaveBeenCalled();+ expect(update).not.toHaveBeenCalled();+ });++ it("refuses an org with a manual plan override", async () => {+ withOrg({ plan: "Team" });++ expect(+ await trpcCode(+ service().createCheckoutSession(ORG_ID, productIdFor("pro")),+ ),+ ).toBe("INTERNAL_SERVER_ERROR");+ expect(clientMock.createCheckoutSession).not.toHaveBeenCalled();+ });++ it.each([+ ["a stripe customer", { customerId: "cus_1" }],+ ["an active stripe subscription", { activeSubscriptionId: "sub_1" }],+ ])("refuses an org that already carries %s", async (_label, stripe) => {+ withOrg({ stripe } as CloudConfigSchema);++ expect(+ await trpcCode(+ service().createCheckoutSession(ORG_ID, productIdFor("pro")),+ ),+ ).toBe("INTERNAL_SERVER_ERROR");+ // An org bills through exactly one provider.+ expect(clientMock.createCheckoutSession).not.toHaveBeenCalled();+ });++ it("refuses a product id with no CHB plan code", async () => {+ withOrg(null);++ expect(+ await trpcCode(service().createCheckoutSession(ORG_ID, "prod_unknown")),+ ).toBe("INTERNAL_SERVER_ERROR");+ expect(clientMock.createCheckoutSession).not.toHaveBeenCalled();+ });+ });++ describe("changePlan", () => {+ it("applies an upgrade immediately", async () => {+ withOrg(chbConfig({ planCode: "core" }));++ await service().changePlan(ORG_ID, productIdFor("team"), "op-1");++ expect(clientMock.setScheduledChange).toHaveBeenCalledWith({+ chOrganizationId: CH_ORG_ID,+ bundleId: BUNDLE_ID,+ change: { type: "upgrade", when: "immediate", planCode: "team" },+ idempotencyKey:+ "chb.bundle.scheduled.set:bundleId=bundle_1:to=team:op=op-1",+ });+ });++ it("defers a downgrade to the end of the billing cycle", async () => {+ withOrg(chbConfig({ planCode: "team" }));++ await service().changePlan(ORG_ID, productIdFor("core"), "op-2");++ expect(clientMock.setScheduledChange).toHaveBeenCalledWith(+ expect.objectContaining({+ change: {+ type: "downgrade",+ when: "billing_cycle_end",+ planCode: "core",+ },+ }),+ );+ });++ it("treats an org with no stored plan code as upgrading", async () => {+ withOrg(chbConfig({ planCode: null }));++ await service().changePlan(ORG_ID, productIdFor("core"));++ // Nothing to compare against, so apply now rather than stranding the org+ // on its current tier until the cycle ends.+ expect(clientMock.setScheduledChange).toHaveBeenCalledWith(+ expect.objectContaining({+ change: { type: "upgrade", when: "immediate", planCode: "core" },+ // No opId β no key, matching makeIdempotencyKey's contract.+ idempotencyKey: undefined,+ }),+ );+ });++ it("maps a missing payment method onto PRECONDITION_FAILED", async () => {+ withOrg(chbConfig());+ clientMock.setScheduledChange.mockRejectedValue(+ new ChbPaymentRequiredError({ error: "no_payment_method" }),+ );++ expect(+ await trpcCode(service().changePlan(ORG_ID, productIdFor("team"))),+ ).toBe("PRECONDITION_FAILED");+ expect(mocks.auditLog).not.toHaveBeenCalled();+ });++ it("lets any other client error through unchanged", async () => {+ withOrg(chbConfig());+ const boom = new Error("socket hang up");+ clientMock.setScheduledChange.mockRejectedValue(boom);++ await expect(+ service().changePlan(ORG_ID, productIdFor("team")),+ ).rejects.toBe(boom);+ });++ it.each([+ ["a manual plan override", { plan: "Team" } as CloudConfigSchema],+ ["no CHB state at all", {} as CloudConfigSchema],+ ["no bundle", { clickhouse: { organizationId: CH_ORG_ID } }],+ ])("refuses an org with %s", async (_label, cloudConfig) => {+ withOrg(cloudConfig);++ expect(+ await trpcCode(service().changePlan(ORG_ID, productIdFor("team"))),+ ).toBe("INTERNAL_SERVER_ERROR");+ expect(clientMock.setScheduledChange).not.toHaveBeenCalled();+ });+ });++ describe("cancel, reactivate and clear", () => {+ it("cancels at the end of the billing cycle", async () => {+ withOrg(chbConfig());++ await expect(service().cancel(ORG_ID, "op-3")).resolves.toEqual({+ status: "success",+ });+ expect(clientMock.setScheduledChange).toHaveBeenCalledWith(+ expect.objectContaining({+ change: { type: "cancel", when: "billing_cycle_end" },+ idempotencyKey:+ "chb.bundle.scheduled.set:bundleId=bundle_1:to=cancel-billing_cycle_end:op=op-3",+ }),+ );+ });++ it.each([+ ["reactivate", (s: ChbBillingService) => s.reactivate(ORG_ID, "op-4")],+ [+ "clearPlanSwitchSchedule",+ (s: ChbBillingService) => s.clearPlanSwitchSchedule(ORG_ID, "op-4"),+ ],+ ])("%s clears the pending scheduled change", async (_label, call) => {+ withOrg(chbConfig());++ await expect(call(service())).resolves.toEqual({ status: "success" });+ expect(clientMock.clearScheduledChange).toHaveBeenCalledWith({+ chOrganizationId: CH_ORG_ID,+ bundleId: BUNDLE_ID,+ idempotencyKey: "chb.bundle.scheduled.clear:bundleId=bundle_1:op=op-4",+ });+ });++ it("cancels immediately for destructive flows", async () => {+ withOrg(chbConfig());++ await expect(+ service().cancelImmediatelyAndInvoice(ORG_ID, "op-5"),+ ).resolves.toEqual({ status: "success" });+ expect(clientMock.setScheduledChange).toHaveBeenCalledWith(+ expect.objectContaining({+ change: { type: "cancel", when: "immediate" },+ }),+ );+ });++ it("no-ops the immediate cancellation for an org without a bundle", async () => {+ withOrg(null);++ // Org deletion must keep working for hobby orgs.+ await expect(+ service().cancelImmediatelyAndInvoice(ORG_ID),+ ).resolves.toEqual({ status: "noop" });+ expect(clientMock.setScheduledChange).not.toHaveBeenCalled();+ });+ });++ describe("getInvoices", () => {+ const pagination = { limit: 10 };++ it("returns nothing for an org without a bundle", async () => {+ withOrg(null);++ await expect(service().getInvoices(ORG_ID, pagination)).resolves.toEqual({+ invoices: [],+ hasMore: false,+ cursors: {},+ });+ expect(clientMock.listInvoices).not.toHaveBeenCalled();+ });++ it("maps CHB invoices onto the invoice-table row shape", async () => {+ withOrg(chbConfig());+ clientMock.listInvoices.mockResolvedValue([+ {+ id: "inv_1",+ number: "LF-1",+ status: "paid",+ currency: "usd",+ createdAt: "2026-08-01T00:00:00Z",+ totalCents: 19_900,+ downloadUrl: "https://chb.example.com/inv_1.pdf",+ },+ ]);++ const result = await service().getInvoices(ORG_ID, pagination);++ expect(result.hasMore).toBe(false);+ expect(result.invoices).toEqual([+ {+ id: "inv_1",+ number: "LF-1",+ status: "paid",+ currency: "USD",+ created: Date.parse("2026-08-01T00:00:00Z"),+ hostedInvoiceUrl: "https://chb.example.com/inv_1.pdf",+ invoicePdfUrl: "https://chb.example.com/inv_1.pdf",+ breakdown: {+ subscriptionCents: 0,+ usageCents: 0,+ discountCents: 0,+ taxCents: 0,+ totalCents: 19_900,+ },+ },+ ]);+ });++ it("never emits NaN for an unparsable or missing timestamp", async () => {+ withOrg(chbConfig());+ clientMock.listInvoices.mockResolvedValue([+ { id: "inv_1", createdAt: "not a date" },+ { id: "inv_2" },+ ]);++ const result = await service().getInvoices(ORG_ID, pagination);++ // NaN would reach the table as an Invalid Date.+ expect(result.invoices.map((invoice) => invoice.created)).toEqual([0, 0]);+ expect(result.invoices.map((invoice) => invoice.currency)).toEqual([+ "USD",+ "USD",+ ]);+ });+ });++ describe("remaining surface", () => {+ it("builds a portal session against the org's CH id", async () => {+ withOrg(chbConfig());+ clientMock.createPortalSession.mockResolvedValue(+ "https://portal.example.com/1",+ );++ await expect(service().getCustomerPortalUrl(ORG_ID)).resolves.toBe(+ "https://portal.example.com/1",+ );+ expect(clientMock.createPortalSession).toHaveBeenCalledWith({+ chOrganizationId: CH_ORG_ID,+ returnUrl: `https://cloud.langfuse.com/organization/${ORG_ID}/settings/billing`,+ });+ });++ it("refuses a portal session for an org without CHB state", async () => {+ withOrg(null);++ expect(await trpcCode(service().getCustomerPortalUrl(ORG_ID))).toBe(+ "INTERNAL_SERVER_ERROR",+ );+ });++ it("reports usage from the cached cycle counter", async () => {+ withOrg(chbConfig());++ const usage = await service().getUsage(ORG_ID);++ expect(usage.usageCount).toBe(4_200);+ expect(usage.usageType).toBe("units");+ expect(usage.billingPeriod.start.getUTCDate()).toBe(15);+ });++ it("rejects promotion codes, which CHB has no API for", async () => {+ withOrg(chbConfig());++ expect(+ await trpcCode(service().applyPromotionCode(ORG_ID, "SAVE20")),+ ).toBe("NOT_IMPLEMENTED");+ });++ it("fails when the organization row is gone", async () => {+ findUnique.mockResolvedValue(null);++ expect(await trpcCode(service().getSubscriptionInfo(ORG_ID))).toBe(+ "INTERNAL_SERVER_ERROR",+ );+ });+ });+});diff --git a/web/src/__tests__/server/unit/chbCatalogue.servertest.ts b/web/src/__tests__/server/unit/chbCatalogue.servertest.tsnew file mode 100644index 0000000000..c6e045f850--- /dev/null+++ b/web/src/__tests__/server/unit/chbCatalogue.servertest.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import {+ isChbUpgrade,+ mapChbPlanCodeToStripeProductId,+ mapStripeProductIdToChbPlanCode,+} from "@/src/ee/features/billing/utils/chbCatalogue";+import { stripeProducts } from "@/src/ee/features/billing/utils/stripeCatalogue";++describe("chbCatalogue", () => {+ it("bridges every Stripe product to a CHB plan code and back", () => {+ // The bridge exists because the plan-selection mutations still take a+ // stripeProductId; a product that cannot round-trip would strand a CHB org+ // on a plan it cannot change.+ for (const product of stripeProducts) {+ const planCode = mapStripeProductIdToChbPlanCode(product.stripeProductId);+ expect(planCode).not.toBeNull();+ expect(mapChbPlanCodeToStripeProductId(planCode!)).toBe(+ product.stripeProductId,+ );+ }+ });++ it.each([+ ["an unknown Stripe product id", "prod_unknown"],+ ["an empty product id", ""],+ ])("returns null when bridging %s", (_label, productId) => {+ expect(mapStripeProductIdToChbPlanCode(productId)).toBeNull();+ });++ it.each([+ ["an unknown plan code", "platinum"],+ ["an empty plan code", ""],+ ])("returns null when bridging %s to a product id", (_label, planCode) => {+ expect(mapChbPlanCodeToStripeProductId(planCode)).toBeNull();+ });++ it("classifies upgrades and downgrades by the shared Stripe order keys", () => {+ expect(isChbUpgrade("core", "pro")).toBe(true);+ expect(isChbUpgrade("pro", "team")).toBe(true);+ expect(isChbUpgrade("team", "core")).toBe(false);+ expect(isChbUpgrade("enterprise", "enterprise")).toBe(false);+ });++ it("does not treat a drifted plan code as an upgrade", () => {+ // A code CHB ships before we deploy support for it resolves to order key 0.+ // It must not read as an upgrade from a real tier, which would let a+ // downgrade apply immediately instead of at cycle end.+ expect(isChbUpgrade("team", "platinum")).toBe(false);+ expect(isChbUpgrade("platinum", "team")).toBe(true);+ });+});diff --git a/web/src/ee/features/billing/server/chb/chbAccessToken.ts b/web/src/ee/features/billing/server/chb/chbAccessToken.tsnew file mode 100644index 0000000000..c62521bfff--- /dev/null+++ b/web/src/ee/features/billing/server/chb/chbAccessToken.ts@@ -0,0 +1,123 @@+import { z } from "zod";++import { logger } from "@langfuse/shared/src/server";++/**+ * Auth0 client-credentials (M2M) token source for the ClickHouse Billing (CHB)+ * REST API.+ */++export class ChbAuthError extends Error {+ constructor(+ message: string,+ public readonly status?: number,+ ) {+ super(message);+ this.name = "ChbAuthError";+ }+}++const TokenResponseSchema = z.object({+ access_token: z.string().min(1),+ // Seconds.+ expires_in: z.number().positive(),+});++/**+ * Renew this long before the token actually expires, so a request that is+ * already in flight cannot arrive at CHB with a token that expired in transit.+ */+const EXPIRY_MARGIN_SECONDS = 300;++const TOKEN_REQUEST_TIMEOUT_MS = 10_000;++export type ChbAccessTokenConfig = {+ /** Auth0 tenant hostname, without scheme (the token url is derived). */+ auth0Domain: string;+ clientId: string;+ clientSecret: string;+ audience: string;+};++export class ChbAccessTokenProvider {+ private cached: { token: string; expiresAtMs: number } | null = null;+ /** Single-flight: a burst of billing requests must not stampede Auth0. */+ private inFlight: Promise<string> | null = null;++ constructor(private readonly config: ChbAccessTokenConfig) {}++ /**+ * Drop the cached token so the next call mints a fresh one. Called when CHB+ * rejects a token we still believed was valid.+ */+ invalidate(): void {+ this.cached = null;+ }++ async getToken(): Promise<string> {+ const cached = this.cached;+ if (cached && cached.expiresAtMs > Date.now()) return cached.token;+ if (this.inFlight) return this.inFlight;++ this.inFlight = this.mintToken().finally(() => {+ this.inFlight = null;+ });+ return this.inFlight;+ }++ private async mintToken(): Promise<string> {+ const response = await fetch(+ `https://${this.config.auth0Domain}/oauth/token`,+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ // The Auth0 client is configured for `client_secret_post`, so the+ // credentials travel in the body rather than a Basic header.+ body: JSON.stringify({+ grant_type: "client_credentials",+ client_id: this.config.clientId,+ client_secret: this.config.clientSecret,+ audience: this.config.audience,+ }),+ // An unexpected redirect must not carry the client secret onward.+ redirect: "error",+ signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS),+ },+ );++ if (!response.ok) {+ // Deliberately not logging the body: Auth0 error payloads echo request+ // parameters back.+ logger.error("[CHB Auth] Client-credentials grant failed", {+ status: response.status,+ audience: this.config.audience,+ });+ throw new ChbAuthError(+ `CHB client-credentials grant failed with status ${response.status}`,+ response.status,+ );+ }++ const parsed = TokenResponseSchema.safeParse(+ await response.json().catch(() => undefined),+ );+ if (!parsed.success) {+ throw new ChbAuthError("CHB token endpoint returned an unusable payload");+ }++ // Renew a margin ahead of expiry, but never wait longer than half the+ // token's life: capping the margin at half the lifetime keeps the buffer+ // proportional for a short-lived token, where subtracting the full margin+ // would re-grant on nearly every call.+ const marginSeconds = Math.min(+ EXPIRY_MARGIN_SECONDS,+ Math.floor(parsed.data.expires_in / 2),+ );+ const lifetimeSeconds = parsed.data.expires_in - marginSeconds;+ this.cached = {+ token: parsed.data.access_token,+ expiresAtMs: Date.now() + lifetimeSeconds * 1000,+ };+ return parsed.data.access_token;+ }+}diff --git a/web/src/ee/features/billing/server/chb/chbApiClient.ts b/web/src/ee/features/billing/server/chb/chbApiClient.tsnew file mode 100644index 0000000000..bb64e03adc--- /dev/null+++ b/web/src/ee/features/billing/server/chb/chbApiClient.ts@@ -0,0 +1,365 @@+import { z } from "zod";++import { env } from "@/src/env.mjs";+import { logger } from "@langfuse/shared/src/server";++import {+ ChbAccessTokenProvider,+ type ChbAccessTokenConfig,+} from "./chbAccessToken";++/**+ * Thin fetch wrapper for the ClickHouse Billing (CHB) REST API.+ */++export class ChbApiError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly body?: unknown,+ ) {+ super(message);+ this.name = "ChbApiError";+ }+}++/**+ * CHB returns 409 Conflict on bundle mutations when the organization has no+ * active payment method. Callers translate this into the same "needs checkout"+ * UX path the billing dialog already handles.+ */+export class ChbPaymentRequiredError extends ChbApiError {+ constructor(body?: unknown) {+ super(+ "CHB rejected the mutation: no active payment method on the organization",+ 409,+ body,+ );+ this.name = "ChbPaymentRequiredError";+ }+}++export const ChbScheduledChangeSchema = z.object({+ type: z.string(), // "upgrade" | "downgrade" | "cancel"+ when: z.string(), // "immediate" | "billing_cycle_end" | ISO date+ planCode: z.string().nullish(),+ startDate: z.string().nullish(),+});+export type ChbScheduledChange = z.infer<typeof ChbScheduledChangeSchema>;++export const ChbBundleSchema = z.object({+ id: z.string(),+ plan: z+ .object({+ planCode: z.string().nullish(),+ })+ .nullish(),+ period: z+ .object({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ })+ .nullish(),+ payment: z+ .object({+ status: z.string().nullish(),+ nextPaymentDate: z.string().nullish(),+ provider: z+ .object({+ customerId: z.string().nullish(),+ })+ .nullish(),+ })+ .nullish(),+ scheduled: ChbScheduledChangeSchema.nullish(),+});+export type ChbBundle = z.infer<typeof ChbBundleSchema>;++export const ChbCheckoutSessionSchema = z.object({+ url: z.string(),+ // ClickHouse Organization ID β persisted on the Langfuse org right away so a+ // checkout retry recovers the same CH org instead of orphaning one.+ organizationId: z.uuid(),+});+export type ChbCheckoutSession = z.infer<typeof ChbCheckoutSessionSchema>;++export const ChbInvoiceSchema = z.object({+ id: z.string().nullish(),+ number: z.string().nullish(),+ status: z.string().nullish(),+ currency: z.string().nullish(),+ createdAt: z.string().nullish(),+ totalCents: z.number().nullish(),+ // Still an open question with CHB: a hosted download URL and draft/upcoming+ // rows are requested but not confirmed in the invoice payload yet.+ downloadUrl: z.string().nullish(),+});+export type ChbInvoice = z.infer<typeof ChbInvoiceSchema>;++const ChbInvoiceListSchema = z.object({+ invoices: z.array(ChbInvoiceSchema).default([]),+});++export const ChbPortalSessionSchema = z.object({+ url: z.string(),+});++const REQUEST_TIMEOUT_MS = 15_000;++type ChbRequestOptions = {+ method: "GET" | "POST" | "PUT" | "DELETE";+ path: string;+ /** CH-Organization-Id header β required for org-scoped endpoints */+ chOrganizationId?: string;+ body?: unknown;+ idempotencyKey?: string;+ searchParams?: Record<string, string>;+};++export class ChbApiClient {+ private readonly tokenProvider: ChbAccessTokenProvider;++ constructor(+ private readonly config: {+ baseUrl: string;+ auth: ChbAccessTokenConfig;+ },+ ) {+ this.tokenProvider = new ChbAccessTokenProvider(config.auth);+ }++ private requestUrl(opts: ChbRequestOptions): URL {+ // Relative join against a trailing slash, so a base url carrying a path+ // prefix keeps it instead of having it replaced.+ const url = new URL(+ opts.path.replace(/^\//, ""),+ `${this.config.baseUrl.replace(/\/$/, "")}/`,+ );+ for (const [key, value] of Object.entries(opts.searchParams ?? {})) {+ url.searchParams.set(key, value);+ }+ return url;+ }++ private async send(url: URL, opts: ChbRequestOptions): Promise<Response> {+ return await fetch(url, {+ method: opts.method,+ headers: {+ authorization: `Bearer ${await this.tokenProvider.getToken()}`,+ ...(opts.chOrganizationId+ ? { "CH-Organization-Id": opts.chOrganizationId }+ : {}),+ ...(opts.body !== undefined+ ? { "content-type": "application/json" }+ : {}),+ ...(opts.idempotencyKey+ ? { "Idempotency-Key": opts.idempotencyKey }+ : {}),+ },+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,+ // The base URL is operator-configured; an unexpected redirect is an+ // error, not something to follow with a bearer token attached.+ redirect: "error",+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ }++ private async request(opts: ChbRequestOptions): Promise<unknown> {+ const url = this.requestUrl(opts);++ let response = await this.send(url, opts);+ if (response.status === 401) {+ // CHB rejected a token we still considered fresh β revoked, or the Auth0+ // signing key rotated. A 401 means CHB did no work, and the retry carries+ // the same idempotency key, so replaying once with a new token is safe.+ logger.warn("[CHB API] Token rejected, retrying with a fresh one", {+ method: opts.method,+ path: opts.path,+ });+ this.tokenProvider.invalidate();+ response = await this.send(url, opts);+ }++ const responseBody = await response+ .json()+ .catch(() => undefined as unknown);++ if (response.status === 409) {+ throw new ChbPaymentRequiredError(responseBody);+ }+ if (!response.ok) {+ logger.error("[CHB API] Request failed", {+ method: opts.method,+ path: opts.path,+ status: response.status,+ body: responseBody,+ });+ throw new ChbApiError(+ `CHB API ${opts.method} ${opts.path} failed with status ${response.status}`,+ response.status,+ responseBody,+ );+ }++ return responseBody;+ }++ async createCheckoutSession(params: {+ organizationId?: string;+ email: string;+ planCode: string;+ returnUrl: string;+ idempotencyKey?: string;+ }): Promise<ChbCheckoutSession> {+ const body = await this.request({+ method: "POST",+ path: "checkout-sessions",+ body: {+ ...(params.organizationId+ ? { organizationId: params.organizationId }+ : {}),+ email: params.email,+ planCode: params.planCode,+ returnUrl: params.returnUrl,+ ...(params.idempotencyKey+ ? { idempotencyKey: params.idempotencyKey }+ : {}),+ },+ idempotencyKey: params.idempotencyKey,+ });+ return ChbCheckoutSessionSchema.parse(body);+ }++ async getBundle(params: {+ chOrganizationId: string;+ bundleId: string;+ }): Promise<ChbBundle> {+ const body = await this.request({+ method: "GET",+ path: `bundles/${encodeURIComponent(params.bundleId)}`,+ chOrganizationId: params.chOrganizationId,+ searchParams: { fields: "plan,period,payment,scheduled" },+ });+ return ChbBundleSchema.parse(body);+ }++ /** Schedule an upgrade / downgrade / cancellation on a bundle (202). */+ async setScheduledChange(params: {+ chOrganizationId: string;+ bundleId: string;+ change: {+ type: "upgrade" | "downgrade" | "cancel";+ when: "immediate" | "billing_cycle_end";+ planCode?: string;+ };+ idempotencyKey?: string;+ }): Promise<void> {+ await this.request({+ method: "PUT",+ path: `bundles/${encodeURIComponent(params.bundleId)}/scheduled`,+ chOrganizationId: params.chOrganizationId,+ body: params.change,+ idempotencyKey: params.idempotencyKey,+ });+ }++ /** Clear a pending scheduled change β reactivate / undo plan switch (202). */+ async clearScheduledChange(params: {+ chOrganizationId: string;+ bundleId: string;+ idempotencyKey?: string;+ }): Promise<void> {+ await this.request({+ method: "DELETE",+ path: `bundles/${encodeURIComponent(params.bundleId)}/scheduled`,+ chOrganizationId: params.chOrganizationId,+ idempotencyKey: params.idempotencyKey,+ });+ }++ async listInvoices(params: {+ chOrganizationId: string;+ bundleId: string;+ }): Promise<ChbInvoice[]> {+ const body = await this.request({+ method: "GET",+ path: "invoices",+ chOrganizationId: params.chOrganizationId,+ searchParams: { bundleId: params.bundleId },+ });+ return ChbInvoiceListSchema.parse(body).invoices;+ }++ async createPortalSession(params: {+ chOrganizationId: string;+ returnUrl: string;+ }): Promise<string> {+ const body = await this.request({+ method: "POST",+ path: "portal-sessions",+ chOrganizationId: params.chOrganizationId,+ body: { returnUrl: params.returnUrl },+ });+ return ChbPortalSessionSchema.parse(body).url;+ }+}++/**+ * Build a client from env, or null when the CHB REST surface is not fully+ * configured. Callers treat null as "CHB unavailable" and fail closed β a+ * partially configured deployment must not reach CHB unauthenticated.+ *+ * Exported for the env-validation tests only; call `getChbApiClient` instead,+ * which shares one client (and therefore one token cache) process-wide.+ */+export const buildChbApiClientFromEnv = (): ChbApiClient | null => {+ if (+ !env.CLICKHOUSE_BILLING_BASE_URL ||+ !env.CLICKHOUSE_BILLING_AUTH0_DOMAIN ||+ !env.CLICKHOUSE_BILLING_AUTH0_CLIENT_ID ||+ !env.CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET+ ) {+ return null;+ }+ return new ChbApiClient({+ baseUrl: env.CLICKHOUSE_BILLING_BASE_URL,+ auth: {+ auth0Domain: env.CLICKHOUSE_BILLING_AUTH0_DOMAIN,+ clientId: env.CLICKHOUSE_BILLING_AUTH0_CLIENT_ID,+ clientSecret: env.CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET,+ audience: env.CLICKHOUSE_BILLING_AUTH0_AUDIENCE,+ },+ });+};++class ChbApiClientSingleton {+ private static instance: ChbApiClient | null;+ private static built = false;++ public static getInstance(): ChbApiClient | null {+ if (!ChbApiClientSingleton.built) {+ // Cached even when null: an unconfigured deployment must not re-check+ // env on every billing request either.+ ChbApiClientSingleton.instance = buildChbApiClientFromEnv();+ ChbApiClientSingleton.built = true;+ }+ return ChbApiClientSingleton.instance;+ }++ /** Test-only: drop the cached client so the next call rebuilds from env. */+ public static reset(): void {+ ChbApiClientSingleton.built = false;+ ChbApiClientSingleton.instance = null;+ }+}++/**+ * The CHB client for this process, or null when CHB is not fully configured.+ * Callers treat null as "CHB unavailable" and fail closed.+ */+export const getChbApiClient = (): ChbApiClient | null =>+ ChbApiClientSingleton.getInstance();++/** Test-only: reset the singleton between cases. */+export const resetChbApiClientForTests = (): void =>+ ChbApiClientSingleton.reset();diff --git a/web/src/ee/features/billing/server/chb/chbBillingService.ts b/web/src/ee/features/billing/server/chb/chbBillingService.tsnew file mode 100644index 0000000000..5446b574c6--- /dev/null+++ b/web/src/ee/features/billing/server/chb/chbBillingService.ts@@ -0,0 +1,711 @@+import { TRPCError } from "@trpc/server";++import { env } from "@/src/env.mjs";+import { type OrgAuthedContext } from "@/src/server/api/trpc";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { CloudConfigSchema, parseDbOrg } from "@langfuse/shared";+import {+ getBillingCycleEnd,+ getBillingCycleStart,+ logger,+} from "@langfuse/shared/src/server";++import { type BillingSubscriptionInfo } from "../stripe/stripeBillingService";+import {+ type ChbApiClient,+ type ChbBundle,+ ChbPaymentRequiredError,+} from "./chbApiClient";+import {+ isChbUpgrade,+ mapChbPlanCodeToStripeProductId,+ mapStripeProductIdToChbPlanCode,+} from "../../utils/chbCatalogue";+import {+ IdempotencyKind,+ makeIdempotencyKey,+} from "../../utils/stripeIdempotencyKey";++/**+ * ClickHouse Billing implementation of the router-facing billing surface.+ *+ * Exposes the same method names and return shapes as the Stripe+ * `BillingService` (incl. `BillingSubscriptionInfo`), so the ten+ * `cloudBillingRouter` procedures dispatch to either provider without any+ * tRPC contract change.+ *+ * The two plan-selection mutations take+ * `stripeProductId`, so this service maps stripeProductId β Plan β PlanCode+ * through chbCatalogue. Plan-code-first inputs retire the bridge post-GA.+ */+export class ChbBillingService {+ constructor(+ private readonly client: ChbApiClient,+ private readonly ctx: OrgAuthedContext,+ ) {}++ private async getParsedOrg(orgId: string) {+ const org = await this.ctx.prisma.organization.findUnique({+ where: { id: orgId },+ });+ if (!org) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Organization not found",+ });+ }+ return { org, parsedOrg: parseDbOrg(org) } as const;+ }++ private requireChbState(parsedOrg: {+ id: string;+ cloudConfig: CloudConfigSchema | null;+ }) {+ const chb = parsedOrg.cloudConfig?.clickhouse;+ if (!chb?.organizationId) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Organization has no ClickHouse Billing state",+ });+ }+ return chb;+ }++ private returnUrl(orgId: string) {+ return `${env.NEXTAUTH_URL}/organization/${orgId}/settings/billing`;+ }++ private toUnixSeconds(value: string | null | undefined): number | null {+ if (!value) return null;+ const ms = Date.parse(value);+ return Number.isNaN(ms) ? null : Math.floor(ms / 1000);+ }++ /**+ * Map a bundle's pending scheduled change onto the Stripe-shaped+ * cancellation / scheduledChange fields the billing UI renders.+ */+ private mapScheduled(bundle: ChbBundle): {+ cancellation: BillingSubscriptionInfo["cancellation"];+ scheduledChange: BillingSubscriptionInfo["scheduledChange"];+ } {+ const scheduled = bundle.scheduled;+ if (!scheduled) return { cancellation: null, scheduledChange: null };++ // An "immediate" change has already been applied, so there is no pending+ // state to render. Checked explicitly rather than relying on the date+ // fallback below: an immediate change echoed back on a bundle that still+ // carries an active period would otherwise resolve to the period end and+ // render as "switches at end of cycle".+ if (scheduled.when === "immediate") {+ return { cancellation: null, scheduledChange: null };+ }++ // Date resolution: explicit startDate wins, else the period end.+ const switchAt =+ this.toUnixSeconds(scheduled.startDate) ??+ this.toUnixSeconds(bundle.period?.endDate);+ if (!switchAt) return { cancellation: null, scheduledChange: null };++ if (scheduled.type === "cancel") {+ return {+ cancellation: { cancelAt: switchAt },+ scheduledChange: null,+ };+ }++ return {+ cancellation: null,+ scheduledChange: {+ // CHB has no schedule object of its own; synthesize a stable id for+ // the UI (only mutations by orgId exist, the id is display-only).+ scheduleId: `chb:${bundle.id}`,+ switchAt,+ newProductId: scheduled.planCode+ ? (mapChbPlanCodeToStripeProductId(scheduled.planCode) ?? undefined)+ : undefined,+ message: null,+ },+ };+ }++ async getSubscriptionInfo(orgId: string): Promise<BillingSubscriptionInfo> {+ const { org, parsedOrg } = await this.getParsedOrg(orgId);+ const chb = parsedOrg.cloudConfig?.clickhouse;++ if (!chb?.bundleId) {+ // No bundle yet (hobby / pre-checkout) β same cached-cycle fallback the+ // Stripe path uses for orgs without a subscription.+ const now = new Date();+ return {+ cancellation: null,+ scheduledChange: null,+ billingPeriod: {+ start: getBillingCycleStart(org, now),+ end: getBillingCycleEnd(org, now),+ },+ hasValidPaymentMethod: false,+ };+ }++ const bundle = await this.client.getBundle({+ chOrganizationId: chb.organizationId,+ bundleId: chb.bundleId,+ });++ const periodStart = bundle.period?.startDate+ ? new Date(bundle.period.startDate)+ : null;+ const periodEnd = bundle.period?.endDate+ ? new Date(bundle.period.endDate)+ : null;++ return {+ ...this.mapScheduled(bundle),+ billingPeriod:+ periodStart && periodEnd+ ? { start: periodStart, end: periodEnd }+ : null,+ // No promotion-code API on the CHB path yet+ discounts: [],+ hasValidPaymentMethod: bundle.payment?.status === "active",+ };+ }++ /**+ * Claim `cloudConfig.clickhouse.organizationId` for this org, atomically.+ *+ * A read-then-write would let two concurrent first-time checkouts each create+ * a CH organization and then race to persist one. The loser's CH org is not+ * just orphaned: the loser is holding a checkout URL whose completion webhook+ * resolves the Langfuse org by a JSONB lookup on this very field, so a payment+ * completed against it would land on an organization we can no longer see.+ *+ * The WHERE guard makes the claim single-winner β only a row whose+ * organizationId is still absent can be written. The merge rebuilds just the+ * `clickhouse` sub-object from the row's own current value rather than from+ * the caller's earlier read, so a webhook concurrently writing `planCode` or+ * `paymentStatus` is not clobbered by a stale snapshot.+ *+ * Returns the number of rows claimed; 0 means another caller won the race.+ *+ * Both `COALESCE`s pass through `NULLIF(β¦, 'null'::jsonb)`: a JSON-null is not+ * a SQL NULL, so `COALESCE` alone does not catch it. The guard counts a stored+ * `{"clickhouse": null}` as unclaimed β correctly, it holds no CHB state β so+ * the merge has to accept that value too, and `||` against a JSON-null scalar+ * concatenates into `[null, {...}]` instead of merging. Keep the two clauses in+ * step: a `clickhouse` that is not an object fails CloudConfigSchema, and+ * parseDbOrg nulls the whole cloudConfig rather than just that field, so the+ * damage is silent and not local to the CHB state.+ */+ private async claimChOrganizationId(+ orgId: string,+ chOrganizationId: string,+ ): Promise<number> {+ return await this.ctx.prisma.$executeRaw`+ UPDATE organizations+ SET cloud_config = jsonb_set(+ COALESCE(NULLIF(cloud_config, 'null'::jsonb), '{}'::jsonb),+ '{clickhouse}',+ COALESCE(+ NULLIF(cloud_config -> 'clickhouse', 'null'::jsonb),+ '{}'::jsonb+ )+ || jsonb_build_object('organizationId', ${chOrganizationId}::text),+ true+ )+ WHERE id = ${orgId}+ AND COALESCE(+ cloud_config -> 'clickhouse' -> 'organizationId',+ 'null'::jsonb+ ) = 'null'::jsonb+ `;+ }++ async createCheckoutSession(+ orgId: string,+ stripeProductId: string,+ opId?: string,+ ) {+ const { parsedOrg } = await this.getParsedOrg(orgId);++ // Interlocks: CHB checkout must never run for an org that is manually+ // planned or carries any Stripe billing state β an org bills through+ // exactly one provider, and both resolvers key off these fields.+ if (parsedOrg.cloudConfig?.plan) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "Cannot initialize checkout for orgs that have a manual plan override",+ });+ }+ if (+ parsedOrg.cloudConfig?.stripe?.customerId ||+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId+ ) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "Cannot initialize ClickHouse Billing checkout for a Stripe-billed organization",+ });+ }++ const planCode = mapStripeProductIdToChbPlanCode(stripeProductId);+ if (!planCode) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Invalid stripe product id",+ });+ }++ const email = this.ctx.session.user.email;+ if (!email) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Acting user has no email address for checkout",+ });+ }++ // Scoped to orgId + planCode rather than the opId alone: the dialog keeps+ // one opId across plan re-clicks, so without planCode a user switching+ // from core to team would replay the first plan's session.+ const idempotencyKey = makeIdempotencyKey({+ kind: IdempotencyKind.enum["chb.checkout.create"],+ fields: { orgId, planCode },+ opId,+ });++ const existingChOrgId = parsedOrg.cloudConfig?.clickhouse?.organizationId;++ logger.info("chbBillingService.checkout.session.create", {+ orgId,+ planCode,+ chOrganizationId: existingChOrgId,+ idempotencyKey,+ opId,+ userId: this.ctx.session.user.id,+ });++ const session = await this.client.createCheckoutSession({+ // Reuse the CH organization from an earlier checkout attempt so a retry+ // recovers the same org instead of orphaning one+ organizationId: existingChOrgId,+ email,+ planCode,+ returnUrl: this.returnUrl(orgId),+ idempotencyKey,+ });++ // Validated through the stored schema before it reaches Postgres: a bad id+ // would make parseDbOrg null the *entire* cloudConfig on every later read,+ // taking the org's rate-limit and lookback overrides with it. (Not its plan+ // override or stripe.customerId β both are checkout interlocks above, so an+ // org carrying either never reaches this line.)+ const validatedChb = CloudConfigSchema.shape.clickhouse.safeParse({+ ...parsedOrg.cloudConfig?.clickhouse,+ organizationId: session.organizationId,+ });+ if (!validatedChb.success || !validatedChb.data) {+ // The client's own ChbCheckoutSessionSchema already rejects a non-uuid+ // id, so this guards the stored schema drifting from the wire schema+ // rather than a malformed CHB response: whatever is about to be written+ // has to satisfy the schema every later read parses it back through.+ // safeParse, not parse, because a raw ZodError escaping the service would+ // surface as an opaque 500 instead of this named one.+ logger.error("chbBillingService.checkout.session.create:invalidChOrgId", {+ orgId,+ returnedChOrganizationId: session.organizationId,+ error: validatedChb.success ? undefined : validatedChb.error,+ });+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "ClickHouse Billing returned an unusable organization id for this checkout",+ });+ }+ const chOrganizationId = validatedChb.data.organizationId;++ if (existingChOrgId) {+ // Retry against an org that already has a CH organization. CHB must hand+ // back the one we asked it to reuse; a different id means sticky provider+ // routing is broken, so refuse rather than clobber the stored id or send+ // the user to a checkout whose webhook resolves elsewhere.+ if (chOrganizationId !== existingChOrgId) {+ logger.error(+ "chbBillingService.checkout.session.create:orgIdMismatch",+ {+ orgId,+ requestedChOrganizationId: existingChOrgId,+ returnedChOrganizationId: chOrganizationId,+ },+ );+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "ClickHouse Billing returned a different organization for this checkout",+ });+ }+ return session.url;+ }++ // First checkout for this org: the CH organization id is the one thing+ // checkout persists outside the webhook, and it must be written exactly+ // once. Only reached after CHB succeeded, so a failed call leaves the org+ // row untouched.+ const claimed = await this.claimChOrganizationId(orgId, chOrganizationId);++ if (claimed === 0) {+ // A concurrent checkout claimed the org first. Its id is now the stored+ // one, which makes the CH org we just created an orphan β log it so it is+ // traceable, and fail instead of returning a URL that would misroute a+ // payment. The user's next attempt takes the reuse path and succeeds.+ logger.error("chbBillingService.checkout.session.create:claimLost", {+ orgId,+ orphanedChOrganizationId: chOrganizationId,+ });+ throw new TRPCError({+ code: "CONFLICT",+ message:+ "Another checkout for this organization is already in progress. Please try again.",+ });+ }++ auditLog({+ session: this.ctx.session,+ orgId: parsedOrg.id,+ resourceType: "organization",+ resourceId: parsedOrg.id,+ action: "BillingService.createCheckoutSession",+ before: parsedOrg.cloudConfig,+ after: {+ ...parsedOrg.cloudConfig,+ clickhouse: {+ ...parsedOrg.cloudConfig?.clickhouse,+ organizationId: chOrganizationId,+ },+ },+ });++ return session.url;+ }++ async changePlan(orgId: string, newProductId: string, opId?: string) {+ const { parsedOrg } = await this.getParsedOrg(orgId);++ if (parsedOrg.cloudConfig?.plan) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Cannot change plan for orgs that have a manually set plan",+ });+ }++ const chb = this.requireChbState(parsedOrg);+ if (!chb.bundleId) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Organization does not have an active subscription",+ });+ }++ const newPlanCode = mapStripeProductIdToChbPlanCode(newProductId);+ if (!newPlanCode) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Invalid stripe product id for new product",+ });+ }++ const currentPlanCode = chb.planCode;+ const upgrading = currentPlanCode+ ? isChbUpgrade(currentPlanCode, newPlanCode)+ : true;++ const idempotencyKey = makeIdempotencyKey({+ kind: IdempotencyKind.enum["chb.bundle.scheduled.set"],+ fields: { bundleId: chb.bundleId, to: newPlanCode },+ opId,+ });++ logger.info("chbBillingService.bundle.scheduled.set", {+ orgId,+ bundleId: chb.bundleId,+ fromPlanCode: currentPlanCode,+ toPlanCode: newPlanCode,+ isUpgrade: upgrading,+ idempotencyKey,+ opId,+ userId: this.ctx.session.user.id,+ });++ try {+ await this.client.setScheduledChange({+ chOrganizationId: chb.organizationId,+ bundleId: chb.bundleId,+ change: {+ type: upgrading ? "upgrade" : "downgrade",+ // Same semantics as the Stripe path: upgrades apply immediately,+ // downgrades at the end of the current billing cycle.+ when: upgrading ? "immediate" : "billing_cycle_end",+ planCode: newPlanCode,+ },+ idempotencyKey,+ });+ } catch (error) {+ if (error instanceof ChbPaymentRequiredError) {+ // No active payment method β same "needs checkout" UX path the dialog+ // already handles for new subscriptions.+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message:+ "No active payment method on the organization. Please complete checkout first.",+ cause: error,+ });+ }+ throw error;+ }++ auditLog({+ session: this.ctx.session,+ orgId: parsedOrg.id,+ resourceType: "organization",+ resourceId: parsedOrg.id,+ action: "BillingService.changePlan",+ before: parsedOrg.cloudConfig,+ after: "webhook",+ });+ }++ async cancel(orgId: string, opId?: string) {+ await this.setCancellation(orgId, "billing_cycle_end", opId);+ return { status: "success" } as const;+ }++ async reactivate(orgId: string, opId?: string) {+ // Reactivation = clearing the pending scheduled cancellation+ await this.clearScheduled(orgId, "BillingService.reactivate", opId);+ return { status: "success" } as const;+ }++ async clearPlanSwitchSchedule(orgId: string, opId?: string) {+ await this.clearScheduled(+ orgId,+ "BillingService.clearPlanSwitchSchedule",+ opId,+ );+ return { status: "success" } as const;+ }++ /**+ * Immediate cancellation for destructive flows (org deletion). Per spec,+ * CHB closes the bill and invoices on the cancellation date; billing data+ * only, the CH organization survives. No-op without a bundle so org+ * deletion keeps working for hobby orgs.+ */+ async cancelImmediatelyAndInvoice(orgId: string, opId?: string) {+ const { parsedOrg } = await this.getParsedOrg(orgId);+ const chb = parsedOrg.cloudConfig?.clickhouse;+ if (!chb?.bundleId) {+ logger.info("chbBillingService.cancel.now:noop.noActiveBundle", {+ orgId,+ });+ return { status: "noop" } as const;+ }++ await this.client.setScheduledChange({+ chOrganizationId: chb.organizationId,+ bundleId: chb.bundleId,+ change: { type: "cancel", when: "immediate" },+ idempotencyKey: makeIdempotencyKey({+ kind: IdempotencyKind.enum["chb.bundle.scheduled.set"],+ fields: { bundleId: chb.bundleId, to: "cancel-immediate" },+ opId,+ }),+ });++ auditLog({+ session: this.ctx.session,+ orgId: parsedOrg.id,+ resourceType: "organization",+ resourceId: parsedOrg.id,+ action: "BillingService.cancelImmediatelyAndInvoice",+ before: parsedOrg.cloudConfig,+ after: "webhook",+ });++ return { status: "success" } as const;+ }++ async getCustomerPortalUrl(orgId: string) {+ const { parsedOrg } = await this.getParsedOrg(orgId);+ const chb = this.requireChbState(parsedOrg);++ return await this.client.createPortalSession({+ chOrganizationId: chb.organizationId,+ returnUrl: this.returnUrl(orgId),+ });+ }++ async getInvoices(+ orgId: string,+ _pagination: {+ limit: number;+ startingAfter?: string;+ endingBefore?: string;+ },+ ) {+ const { parsedOrg } = await this.getParsedOrg(orgId);+ const chb = parsedOrg.cloudConfig?.clickhouse;+ if (!chb?.bundleId) {+ return { invoices: [], hasMore: false, cursors: {} };+ }++ const invoices = await this.client.listInvoices({+ chOrganizationId: chb.organizationId,+ bundleId: chb.bundleId,+ });++ return {+ // Mapped into the existing invoice-table row shape. Breakdown parity+ // (subscription vs usage split, draft/upcoming row) is still open with+ // CHB, so this is total-only until they confirm the payload.+ invoices: invoices.map((invoice) => ({+ id: invoice.id,+ number: invoice.number,+ status: invoice.status,+ currency: invoice.currency?.toUpperCase() ?? "USD",+ // Milliseconds, like the Stripe path. Guarded: an unparsable CHB+ // timestamp must not reach the table as NaN.+ created: (this.toUnixSeconds(invoice.createdAt) ?? 0) * 1000,+ hostedInvoiceUrl: invoice.downloadUrl ?? null,+ invoicePdfUrl: invoice.downloadUrl ?? null,+ breakdown: {+ subscriptionCents: 0,+ usageCents: 0,+ discountCents: 0,+ taxCents: 0,+ totalCents: invoice.totalCents ?? 0,+ },+ })),+ // CHB invoice pagination is not part of the v1 contract; return the+ // full list.+ hasMore: false,+ cursors: {},+ };+ }++ /**+ * v1 usage source of truth for CHB orgs is the existing non-Stripe+ * fallback: billing cycle from the org's anchor + the cached cycle usage+ * the hourly job maintains. Spend-in-USD can later come from+ * `GET /bundles/{id}?fields=period`.+ */+ async getUsage(orgId: string) {+ const { org } = await this.getParsedOrg(orgId);++ const now = new Date();+ return {+ usageCount: org.cloudCurrentCycleUsage ?? 0,+ usageType: "units",+ billingPeriod: {+ start: getBillingCycleStart(org, now),+ end: getBillingCycleEnd(org, now),+ },+ };+ }++ async applyPromotionCode(+ _orgId: string,+ _code: string,+ _opId?: string,+ ): Promise<{ ok: true }> {+ // No CHB promotion-code API yet; the button is hidden for CHB orgs.+ throw new TRPCError({+ code: "NOT_IMPLEMENTED",+ message:+ "Promotion codes are not available for ClickHouse-billed organizations",+ });+ }++ private async setCancellation(+ orgId: string,+ when: "immediate" | "billing_cycle_end",+ opId?: string,+ ) {+ const { parsedOrg } = await this.getParsedOrg(orgId);+ const chb = this.requireChbState(parsedOrg);+ if (!chb.bundleId) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "No active subscription to cancel",+ });+ }++ logger.info("chbBillingService.bundle.scheduled.cancel", {+ orgId,+ bundleId: chb.bundleId,+ when,+ opId,+ userId: this.ctx.session.user.id,+ });++ await this.client.setScheduledChange({+ chOrganizationId: chb.organizationId,+ bundleId: chb.bundleId,+ change: { type: "cancel", when },+ idempotencyKey: makeIdempotencyKey({+ kind: IdempotencyKind.enum["chb.bundle.scheduled.set"],+ fields: { bundleId: chb.bundleId, to: `cancel-${when}` },+ opId,+ }),+ });++ auditLog({+ session: this.ctx.session,+ orgId: parsedOrg.id,+ resourceType: "organization",+ resourceId: parsedOrg.id,+ action: "BillingService.cancel",+ before: parsedOrg.cloudConfig,+ after: "webhook",+ });+ }++ private async clearScheduled(orgId: string, action: string, opId?: string) {+ const { parsedOrg } = await this.getParsedOrg(orgId);+ const chb = this.requireChbState(parsedOrg);+ if (!chb.bundleId) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "No active subscription found",+ });+ }++ logger.info("chbBillingService.bundle.scheduled.clear", {+ orgId,+ bundleId: chb.bundleId,+ action,+ opId,+ userId: this.ctx.session.user.id,+ });++ await this.client.clearScheduledChange({+ chOrganizationId: chb.organizationId,+ bundleId: chb.bundleId,+ idempotencyKey: makeIdempotencyKey({+ kind: IdempotencyKind.enum["chb.bundle.scheduled.clear"],+ fields: { bundleId: chb.bundleId },+ opId,+ }),+ });++ auditLog({+ session: this.ctx.session,+ orgId: parsedOrg.id,+ resourceType: "organization",+ resourceId: parsedOrg.id,+ action,+ before: parsedOrg.cloudConfig,+ after: "webhook",+ });+ }+}diff --git a/web/src/ee/features/billing/utils/chbCatalogue.ts b/web/src/ee/features/billing/utils/chbCatalogue.tsnew file mode 100644index 0000000000..045a314501--- /dev/null+++ b/web/src/ee/features/billing/utils/chbCatalogue.ts@@ -0,0 +1,62 @@+import {+ type ChbPlanCode,+ chbPlanCodeToPlan,+ chbPlanCodes,+ type Plan,+} from "@langfuse/shared";++import { stripeProducts } from "./stripeCatalogue";++/**+ * Bridges between CHB plan codes and Stripe product ids.+ *+ * The code -> plan mapping itself lives in shared (`chbPlanCodeToPlan`), because+ * `cloudConfigSchema` validates stored codes against it. What cannot live there+ * is the Stripe product id: the plan-selection tRPC mutations and several+ * billing components still speak `stripeProductId`, so a CHB org's plan has to+ * be translated in both directions until plan-code-first inputs ship. Ordering+ * is read off `stripeProducts` for the same reason β one order table for both+ * providers, so an upgrade cannot be classified differently depending on who+ * bills the org.+ *+ * This module is imported client-side, so it must not pull in the server logger:+ * lookups return null and let the call site decide.+ */++const planToChbPlanCode = Object.fromEntries(+ chbPlanCodes.map((planCode) => [chbPlanCodeToPlan[planCode], planCode]),+) as Partial<Record<Plan, ChbPlanCode>>;++const planForChbPlanCode = (planCode: string): Plan | undefined =>+ chbPlanCodeToPlan[planCode as ChbPlanCode];++const orderKeyForPlan = (plan: Plan | undefined): number =>+ (plan &&+ stripeProducts.find((product) => product.mappedPlan === plan)?.orderKey) ??+ 0;++export const mapStripeProductIdToChbPlanCode = (+ stripeProductId: string,+): ChbPlanCode | null => {+ const mappedPlan = stripeProducts.find(+ (product) => product.stripeProductId === stripeProductId,+ )?.mappedPlan;+ return (mappedPlan && planToChbPlanCode[mappedPlan]) ?? null;+};++export const mapChbPlanCodeToStripeProductId = (+ planCode: string,+): string | null => {+ const mappedPlan = planForChbPlanCode(planCode);+ return mappedPlan+ ? (stripeProducts.find((product) => product.mappedPlan === mappedPlan)+ ?.stripeProductId ?? null)+ : null;+};++export const isChbUpgrade = (+ currentPlanCode: string,+ newPlanCode: string,+): boolean =>+ orderKeyForPlan(planForChbPlanCode(currentPlanCode)) <+ orderKeyForPlan(planForChbPlanCode(newPlanCode));diff --git a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts b/web/src/ee/features/billing/utils/stripeIdempotencyKey.tsindex f6e62c2128..aa4980f567 100644--- a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts+++ b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts@@ -31,6 +31,14 @@ export const IdempotencyKind = z.enum(["subscription.migrate.flexible","subscription.schedule.clear","subscription.update.discounts.add",+ // ClickHouse Billing (CHB) operations β same machinery, keyed on the+ // client-generated opId the router already accepts. The checkout mutation+ // takes an opId too: BillingSwitchPlanDialog generates one per dialog+ // lifetime, which is exactly the double-submit window, and drops it on+ // remount so a fresh visit gets a fresh session rather than an expired one.+ "chb.checkout.create",+ "chb.bundle.scheduled.set",+ "chb.bundle.scheduled.clear",]);export type IdempotencyKind = z.infer<typeof IdempotencyKind>;diff --git a/web/src/env.mjs b/web/src/env.mjsindex 99cef94f47..4c178926d6 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -430,6 +430,20 @@ export const env = createEnv({"must be an EventBridge bus ARN (arn:aws:events:<region>:<account-id>:event-bus/<name>)",).optional(),+ // CHB REST API base url (checkout sessions, bundles, invoices). Unset, or+ // any missing Auth0 credential below, makes the CHB billing service refuse+ // to construct, so no half-configured calls go out.+ CLICKHOUSE_BILLING_BASE_URL: z.url().optional(),+ // Auth0 client credentials for CHB's REST API: it verifies the bearer+ // token's issuer, audience and signature against this tenant's JWKS, so a+ // static shared secret is rejected. Not used for the event bus, which+ // authenticates via IAM.+ CLICKHOUSE_BILLING_AUTH0_DOMAIN: z.string().optional(),+ CLICKHOUSE_BILLING_AUTH0_CLIENT_ID: z.string().optional(),+ CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET: z.string().optional(),+ // CHB's resource-server identifier. Defaulted because it is the same value+ // in every CHB tenant, and overridable in case that stops being true.+ CLICKHOUSE_BILLING_AUTH0_AUDIENCE: z.string().default("billing-api"),SENTRY_AUTH_TOKEN: z.string().optional(),SENTRY_CSP_REPORT_URI: z.string().optional(),LANGFUSE_RATE_LIMITS_ENABLED: z.enum(["true", "false"]).default("true"),@@ -987,6 +1001,15 @@ export const env = createEnv({process.env.CLICKHOUSE_BILLING_METRICS_API_KEY,CLICKHOUSE_BILLING_EVENT_BUS_ARN:process.env.CLICKHOUSE_BILLING_EVENT_BUS_ARN,+ CLICKHOUSE_BILLING_BASE_URL: process.env.CLICKHOUSE_BILLING_BASE_URL,+ CLICKHOUSE_BILLING_AUTH0_DOMAIN:+ process.env.CLICKHOUSE_BILLING_AUTH0_DOMAIN,+ CLICKHOUSE_BILLING_AUTH0_CLIENT_ID:+ process.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_ID,+ CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET:+ process.env.CLICKHOUSE_BILLING_AUTH0_CLIENT_SECRET,+ CLICKHOUSE_BILLING_AUTH0_AUDIENCE:+ process.env.CLICKHOUSE_BILLING_AUTH0_AUDIENCE,SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,SENTRY_CSP_REPORT_URI: process.env.SENTRY_CSP_REPORT_URI,LANGFUSE_RATE_LIMITS_ENABLED: process.env.LANGFUSE_RATE_LIMITS_ENABLED,