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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(ee): read companyPlan via one service-role maybeSingle helper (#1687)
Brad Barbinfbe72d643317
diff --git a/packages/ee/src/plan.server.test.ts b/packages/ee/src/plan.server.test.tsindex 124318be23..ca5ecc90ea 100644--- a/packages/ee/src/plan.server.test.ts+++ b/packages/ee/src/plan.server.test.ts@@ -1,10 +1,10 @@import { Plan } from "@carbon/utils";import { beforeEach, describe, expect, it, vi } from "vitest";-const serviceRoleSingle = vi.hoisted(() => vi.fn());+const serviceRoleMaybeSingle = vi.hoisted(() => vi.fn());const serviceRoleFrom = vi.hoisted(() =>vi.fn(() => ({- select: () => ({ eq: () => ({ single: serviceRoleSingle }) })+ select: () => ({ eq: () => ({ maybeSingle: serviceRoleMaybeSingle }) })})));const isCarbonOwnedCompany = vi.hoisted(() => vi.fn());@@ -35,11 +35,13 @@ import { companyHasFeature } from "./plan.server";// this client sees no row. If the gate ever reads the plan through the caller's// client again, `from` is called and the assertion fails.function rlsBlockedClient() {- const single = vi.fn(async () => ({- data: null,- error: { code: "PGRST116" }+ // Under `maybeSingle()` a zero-row read is `data: null` with NO error — the+ // "never subscribed"/RLS-invisible case. The gate must never reach this client+ // anyway (it reads via service role), so `from` is asserted uncalled below.+ const maybeSingle = vi.fn(async () => ({ data: null, error: null }));+ const from = vi.fn(() => ({+ select: () => ({ eq: () => ({ maybeSingle }) })}));- const from = vi.fn(() => ({ select: () => ({ eq: () => ({ single }) }) }));return { from };}@@ -53,7 +55,7 @@ describe("plan gate reads companyPlan via service role", () => {// Regression: a paying Partner (planId "PARTNER-33") was 402'd from MCP// because companyHasFeature read companyPlan through the RLS-scoped api-key// client, which returns no row -> Plan.Unknown -> blocked.- serviceRoleSingle.mockResolvedValue({+ serviceRoleMaybeSingle.mockResolvedValue({data: { planId: "PARTNER-33" },error: null});@@ -69,7 +71,7 @@ describe("plan gate reads companyPlan via service role", () => {});it("still blocks a Starter company", async () => {- serviceRoleSingle.mockResolvedValue({+ serviceRoleMaybeSingle.mockResolvedValue({data: { planId: Plan.Starter },error: null});diff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.tsindex d1004f66af..eb264a0409 100644--- a/packages/ee/src/plan.server.ts+++ b/packages/ee/src/plan.server.ts@@ -29,28 +29,35 @@ function isBypassCompany(companyId: string): boolean {// MCP/API paths carry (`auth.uid()` is NULL there). Reading through such a client// returns zero rows, normalizes to `Plan.Unknown`, and wrongly gates a paying// Partner out of MCP. So read via service role, matching the pre-existing-// API-access plan gate in `@carbon/auth`'s `requirePermissions`. The `client`-// param is kept for call-site compatibility.-async function getCompanyPlan(- _client: SupabaseClient<Database>,- companyId: string-): Promise<Plan> {+// API-access plan gate in `@carbon/auth`'s `requirePermissions`.+//+// `maybeSingle()` (not `single()`) so the legitimate "never subscribed" zero-row+// case is `data: null` with no error — only a real read failure logs. A failure+// normalizes to the lowest plan, which turns plan-gated ENFORCEMENT (storage/sales+// rules) off — fail-open. Callers are UI gates and evaluators that should not 500+// on a transient blip, so log rather than throw; the signal is what was missing+// when this silently disabled rules.+async function readCompanyPlan(companyId: string): Promise<string | null> {const { data, error: planError } = await getCarbonServiceRole().from("companyPlan").select("planId").eq("id", companyId)- .single();+ .maybeSingle();- // A read error normalizes to the lowest plan, which turns plan-gated- // ENFORCEMENT (storage/sales rules) off — fail-open. Callers are UI gates- // and evaluators that should not 500 on a transient blip, so log rather- // than throw; the signal is what was missing when this silently disabled- // rules.if (planError) {logger.error("getCompanyPlan failed", { companyId, error: planError });}- return normalizePlanId(data?.planId);+ return data?.planId ?? null;+}++// The `_client` param is kept for call-site compatibility; the read goes through+// the service role regardless (see `readCompanyPlan`).+async function getCompanyPlan(+ _client: SupabaseClient<Database>,+ companyId: string+): Promise<Plan> {+ return normalizePlanId(await readCompanyPlan(companyId));}/**@@ -74,15 +81,10 @@ export async function getPlan(if (CarbonEdition !== Edition.Cloud) return null;if (isBypassCompany(companyId)) return Plan.Partner;- // Service role for the same reason as `getCompanyPlan` — the read must not- // depend on the caller's RLS scope.- const { data } = await getCarbonServiceRole()- .from("companyPlan")- .select("planId")- .eq("id", companyId)- .single();-- if (data?.planId) return data.planId;+ // Reads via service role for the same reason as `getCompanyPlan` — the read+ // must not depend on the caller's RLS scope.+ const planId = await readCompanyPlan(companyId);+ if (planId) return planId;// No durable plan row (never subscribed). Carbon-owned companies still get// Business-tier access; everyone else resolves to Unknown → gated.