Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(billing): source the client plan gate from companyPlan, not the Stripe cache (#1470)

Brad Barbin2b188529a9ff
diff --git a/.claude/rules/billing-system.md b/.claude/rules/billing-system.md
index 63688df307..5e07721538 100644
--- a/.claude/rules/billing-system.md
+++ b/.claude/rules/billing-system.md
@@ -91,8 +91,16 @@ Server checks (`plan.server.ts`) read `companyPlan.planId` (`.eq("id", companyId
- `companyHasPlan(client, companyId, spec)` → boolean.
- `requirePlan({ request, client, companyId, redirectTo, message?, ...spec })` → throws a
`redirect` with a flash error when the gate fails.
-
-**Both short-circuit `true`/return when `CarbonEdition !== Edition.Cloud` or the company is
+- `getPlan(client, companyId)` → the raw plan id string the **client** gate
+ (`usePlan`) consumes, resolved from the SAME durable `companyPlan` mirror the two checks
+ above read (precedence bypass → `companyPlan` → carbon-owned; `null` off Cloud). The `/x`
+ loader calls this for its `plan` field. It exists so the UI gate can never disagree with
+ server enforcement — the loader previously sourced `plan` from `getStripeCustomerByCompanyId().planId`
+ (the Stripe/Redis cache), which could go stale and gate a customer whose real plan was
+ correct (a live Partner shown "Upgrade to Business", API keys hidden, while the API auth
+ path — reading `companyPlan` directly — still accepted the keys).
+
+**All three short-circuit when `CarbonEdition !== Edition.Cloud` or the company is
bypass-listed** — gating only bites on Cloud.
`spec` is a `GateSpec`: either `{ feature: Feature }` or `{ plan: Plan | Plan[] }`.
@@ -100,7 +108,8 @@ bypass-listed** — gating only bites on Cloud.
## Frontend hooks (`packages/react/src/hooks/`)
- `usePlan()` (`usePlan.tsx`) — reads `plan` from the `/x` route data and runs it through
- `normalizePlanId`. The `/x` layout loader sources it from the Stripe customer's `planId`.
+ `normalizePlanId`. The `/x` layout loader sources it from `getPlan` (the durable
+ `companyPlan` mirror), NOT the Stripe customer cache — see Plan gating above.
- `useEdition()` (`useEdition.tsx`) — reads `env.CARBON_EDITION` from root route data.
- `usePlanGate` (client mirror of `FEATURE_PLANS`).
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 40d9f242ce..646e259800 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -17,6 +17,7 @@ import {
updateCompanySession
} from "@carbon/auth/session.server";
import { isAuditLogEnabled } from "@carbon/database/audit";
+import { getPlan } from "@carbon/ee/plan.server";
import {
detectImplementationSignals,
getImplementationCheckStates,
@@ -159,6 +160,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
companies,
employeeCompaniesResult,
stripeCustomer,
+ plan,
customFields,
integrations,
companySettings,
@@ -178,6 +180,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
getCompanies(client, userId),
getEmployeeCompanies(client, userId),
getStripeCustomerByCompanyId(companyId, userId),
+ getPlan(client, companyId),
getCustomFieldsSchemas(client, { companyId }),
getCompanyIntegrations(client, companyId),
getCompanySettings(client, companyId),
@@ -186,8 +189,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
getUserClaims(userId, companyId),
getUserGroups(client, userId),
getUserDefaults(client, userId, companyId),
- // Throws, unlike the {data, error} services around it — unguarded, a
- // transient timeout on this flag 500s every page under /x.
isAuditLogEnabled(client, companyId).catch(() => false),
getModulePreferences(client, userId, companyId),
getPrinterRoutes(client, companyId),
@@ -275,7 +276,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
integrations: integrations.data ?? [],
groups: groups.data,
permissions: claims?.permissions,
- plan: stripeCustomer?.planId,
+ plan,
role: claims?.role,
user: user.data,
modulePreferences: modulePreferences.data ?? [],
diff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.ts
index 35f8527e01..38a0f9f7b5 100644
--- a/packages/ee/src/plan.server.ts
+++ b/packages/ee/src/plan.server.ts
@@ -2,7 +2,7 @@ import { CarbonEdition, error, STRIPE_BYPASS_COMPANY_IDS } from "@carbon/auth";
import { isCarbonOwnedCompany } from "@carbon/auth/company.server";
import { flash } from "@carbon/auth/session.server";
import type { Database } from "@carbon/database";
-import { Edition, normalizePlanId, type Plan } from "@carbon/utils";
+import { Edition, normalizePlanId, Plan } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { redirect } from "react-router";
import {
@@ -32,6 +32,41 @@ async function getCompanyPlan(
return normalizePlanId(data?.planId);
}
+/**
+ * The plan id to feed CLIENT-SIDE gating (`usePlanGate` / `usePlan`). It reads
+ * the SAME durable source the server enforces here — `companyPlan` — plus the
+ * bypass/carbon-owned grants, so the UI can never disagree with enforcement.
+ *
+ * The old `/x` loader sourced this from the Stripe/Redis customer cache
+ * (`getStripeCustomerByCompanyId().planId`), which can go stale and gate a
+ * customer whose real plan is correct — e.g. a live Partner shown an "Upgrade to
+ * Business" overlay with their API keys hidden, while their keys still worked
+ * because the API auth path reads `companyPlan` directly.
+ *
+ * Precedence mirrors `companyHasPlan`: bypass → companyPlan → carbon-owned.
+ * Returns `null` off Cloud (the client neutralizes gating there anyway).
+ */
+export async function getPlan(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<string | null> {
+ if (CarbonEdition !== Edition.Cloud) return null;
+ if (isBypassCompany(companyId)) return Plan.Partner;
+
+ const { data } = await client
+ .from("companyPlan")
+ .select("planId")
+ .eq("id", companyId)
+ .single();
+
+ if (data?.planId) return data.planId;
+
+ // No durable plan row (never subscribed). Carbon-owned companies still get
+ // Business-tier access; everyone else resolves to Unknown → gated.
+ if (await isCarbonOwnedCompany(companyId)) return Plan.Business;
+ return null;
+}
+
/** Self-hosted and bypass-listed companies always pass. */
export async function companyHasPlan(
client: SupabaseClient<Database>,