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
perf(auth): cache plan lookups for 5 minutes, including companies with no plan row
Sidwebworks4387ea132fbb
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.mdindex 5592ccdbca..41bb548b61 100644--- a/.claude/rules/authentication-system.md+++ b/.claude/rules/authentication-system.md@@ -421,7 +421,8 @@ writer is the 30s TTL. Then:perms must be present and include the active company. `{}` is NOT full access here —an empty scope set fails the check. 403 on failure.- Cloud edition: Starter-plan companies are blocked from API access (Business+ only),- except `STRIPE_BYPASS_COMPANY_IDS`.+ except `STRIPE_BYPASS_COMPANY_IDS`. The plan comes from the cached `getCompanyPlanId`+ (see `billing-system.md`), so a plan change made outside the Stripe sync can take up to 5 minutes to bite.- Returns a `getCarbonAPIKeyClient(apiKey)` client (RLS resolves company via header).Key hashing: `hashApiKey` = `createHash("sha256")` hex (same in Node ERP and Deno edgediff --git a/.claude/rules/billing-system.md b/.claude/rules/billing-system.mdindex aa9cf8892c..73ad440356 100644--- a/.claude/rules/billing-system.md+++ b/.claude/rules/billing-system.md@@ -118,7 +118,14 @@ users (every invite defaults to the seeded `Admin` employee type) but not authorroles. Enforcement (`requirePermissions`, RLS, `get_claims`) is unaffected andstays in every edition.-Server checks (`plan.server.ts`) read `companyPlan.planId` (`.eq("id", companyId)`):+Server checks (`plan.server.ts`) read `companyPlan.planId` through `getCompanyPlanId`+(`@carbon/auth/company.server`), the one cached reader the API-key plan gate in+`requirePermissions` also uses: service role, Redis for 5 minutes, memoized per read request.+A company with no plan row is cached too (as `""`), and so is the `isCarbonOwnedCompany`+fallback such a company falls through to. `syncStripeDataToKV` clears the plan key when+it writes a row; a failed read is never cached. Any other change (a plan row edited by+hand, the `customer.subscription.deleted` webhook, a group owner change) shows up within+5 minutes, or at once after `DEL companyPlan:<companyId>` in Redis.- `companyHasPlan(client, companyId, spec)` → boolean.- `requirePlan({ request, client, companyId, redirectTo, message?, ...spec })` → throws adiff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex 25f4666811..579f4d4de2 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -42,7 +42,7 @@ pnpm --filter @carbon/auth test| `./auth.server` | `requirePermissions`, API key auth (30s Redis-cached `getApiKeyRecord` + `bustApiKeyCache`, from `services/api-key.server.ts`), `hashApiKey`, `hashOAuthSecret` || `./mfa.server` | TOTP MFA: `enrollTotpFactor`, `verifyTotpChallenge`, `unenrollTotpFactor`, `userHasVerifiedTotpFactor` (Redis-cached), `adminDeleteTotpFactors` || `./session.server` | `createCookieSessionStorage`, `requireAuthSession` (incl. MFA re-check), `destroyAuthSession`, session refresh, pending-MFA session + `completeMfaChallenge` |-| `./company.server` | Company switching, `updateCompanySession` |+| `./company.server` | Company switching, `updateCompanySession`; the cached plan lookups `getCompanyPlanId` and `isCarbonOwnedCompany` (Redis 5 min, a missing plan row cached as `""`) || `./users.server` | `getUserClaims`, deactivation flows, cache invalidation || `./passkey.server` | WebAuthn/passkey registration and authentication || `./console-pin.server` | MES console pin-in cookie (signed, bound to company + terminal session user): `setConsolePinIn`, `clearConsolePinIn`, `resolveConsolePinIn` (re-validated against the DB, memoized per read), `ConsolePinIn`; `requirePermissions` uses it to derive `userId` in console mode |diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.tsindex daca51860f..e857b45eef 100644--- a/packages/auth/src/services/auth.server.ts+++ b/packages/auth/src/services/auth.server.ts@@ -36,7 +36,7 @@ import { path } from "../utils/path";import { error } from "../utils/result";import { type ApiKeyRecord, getApiKeyRecord } from "./api-key.server";import { logAuthEvent } from "./auth-events.server";-import { isCarbonOwnedCompany } from "./company.server";+import { getCompanyPlanId, isCarbonOwnedCompany } from "./company.server";import { resolveConsolePinIn } from "./console-pin.server";import {destroyAuthSession,@@ -313,14 +313,8 @@ export async function requirePermissions(: false;if (!isBypass) {- const { data: planData } = await serviceRole- .from("companyPlan")- .select("planId")- .eq("id", companyId)- .single();-if (- planData?.planId === Plan.Starter &&+ (await getCompanyPlanId(companyId)) === Plan.Starter &&!(await isCarbonOwnedCompany(companyId))) {throw new Response(diff --git a/packages/auth/src/services/company-plan-cache.test.ts b/packages/auth/src/services/company-plan-cache.test.tsnew file mode 100644index 0000000000..323b480ac8--- /dev/null+++ b/packages/auth/src/services/company-plan-cache.test.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// Import-safety only: the module reads env and builds clients at import time.+vi.mock("@carbon/auth", () => ({+ CarbonEdition: "cloud",+ DOMAIN: "localhost"+}));+vi.mock("@carbon/kv", () => ({ redis: {} }));+vi.mock("../lib/supabase/client.server", () => ({+ getCarbonServiceRole: vi.fn()+}));++import { planIdFromCache } from "./company.server";++describe("planIdFromCache", () => {+ it("returns a cached plan id", () => {+ expect(planIdFromCache("PARTNER-300")).toBe("PARTNER-300");+ });++ // Companies with no plan row were re-read from the database on every request.+ it("treats an empty string as a cached missing row, not a miss", () => {+ expect(planIdFromCache("")).toBeNull();+ });++ it("treats an unset key, or Redis being down, as a miss", () => {+ expect(planIdFromCache(null)).toBeUndefined();+ });+});diff --git a/packages/auth/src/services/company.server.ts b/packages/auth/src/services/company.server.tsindex 0acf409098..7d2e8404ce 100644--- a/packages/auth/src/services/company.server.ts+++ b/packages/auth/src/services/company.server.ts@@ -3,11 +3,16 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { CarbonEdition, DOMAIN } from "@carbon/auth";-import { Edition, isInternalEmail } from "@carbon/utils";+import { redis } from "@carbon/kv";+import { getLogger } from "@carbon/logger";+import { oncePerRead } from "@carbon/logger/middleware.server";+import { companyPlanCacheKey, Edition, isInternalEmail } from "@carbon/utils";import * as cookie from "cookie";import { getCarbonServiceRole } from "../lib/supabase/client.server";import { getCookieDomain } from "../utils/cookie";+const logger = getLogger("auth", "company");+const cookieName = "companyId";const isTestEdition = CarbonEdition === Edition.Test;const cookieDomain = isTestEdition ? undefined : getCookieDomain(DOMAIN);@@ -40,32 +45,110 @@ export function setCompanyId(companyId: string | null) {});}+// Both plan lookups below run on almost every request, so they are cached in+// Redis and memoized per read request. The Stripe sync clears the plan key when+// it writes a row; the TTL covers every other writer.+const PLAN_CACHE_TTL_SECONDS = 5 * 60;+const carbonOwnedCacheKey = (companyId: string) => `carbonOwned:${companyId}`;++/**+ * The company's `companyPlan.planId`, or null when it has no plan row.+ *+ * Read via service role: `companyPlan`'s SELECT policy needs an authenticated+ * `auth.uid()`, which the anon `carbon-key` API-key client does not have, so a+ * read through the caller's client returns no row for a paying company.+ *+ * A failed read returns null without being cached. Callers treat null as the+ * lowest plan, so a transient failure must not stick for the whole TTL.+ */+export function getCompanyPlanId(companyId: string): Promise<string | null> {+ return oncePerRead(`companyPlan:${companyId}`, () =>+ loadCompanyPlanId(companyId)+ );+}++/**+ * Decodes the cached value: `undefined` is a miss, `null` a cached "no plan row"+ * (stored as ""). Redis being down resolves null, so it reads as a miss.+ */+export function planIdFromCache(+ cached: string | null+): string | null | undefined {+ if (typeof cached !== "string") return undefined;+ return cached || null;+}++async function loadCompanyPlanId(companyId: string): Promise<string | null> {+ const cacheKey = companyPlanCacheKey(companyId);+ const cached = planIdFromCache(await redis.get(cacheKey));+ if (cached !== undefined) return cached;++ const { data, error } = await getCarbonServiceRole()+ .from("companyPlan")+ .select("planId")+ .eq("id", companyId)+ .maybeSingle();++ if (error) {+ logger.error("Failed to read company plan", { companyId, error });+ return null;+ }++ const planId = data?.planId ?? null;+ await redis.set(cacheKey, planId ?? "", "EX", PLAN_CACHE_TTL_SECONDS);+ return planId;+}+/*** True when the company's group owner has a Carbon-internal email. These* companies get top-tier plan access without billing — the runtime analogue of* the `STRIPE_BYPASS_COMPANY_IDS` list, keyed on owner identity instead of a- * hardcoded id. Use only as a fallback after the normal plan check, since it- * hits the database.+ * hardcoded id. Use only as a fallback after the normal plan check.*/-export async function isCarbonOwnedCompany(- companyId: string-): Promise<boolean> {+export function isCarbonOwnedCompany(companyId: string): Promise<boolean> {+ return oncePerRead(`carbonOwned:${companyId}`, () =>+ loadIsCarbonOwnedCompany(companyId)+ );+}++async function loadIsCarbonOwnedCompany(companyId: string): Promise<boolean> {+ const cacheKey = carbonOwnedCacheKey(companyId);+ const cached = await redis.get(cacheKey);+ if (cached === "1" || cached === "0") return cached === "1";+const client = getCarbonServiceRole();- const { data: company } = await client+ const company = await client.from("company").select("companyGroup(ownerId)").eq("id", companyId)- .single();-- const ownerId = company?.companyGroup?.ownerId;- if (!ownerId) return false;+ .maybeSingle();+ if (company.error) {+ logger.error("Failed to read company owner", {+ companyId,+ error: company.error+ });+ return false;+ }- const { data: owner } = await client- .from("user")- .select("email")- .eq("id", ownerId)- .single();+ let owned = false;+ const ownerId = company.data?.companyGroup?.ownerId;+ if (ownerId) {+ const owner = await client+ .from("user")+ .select("email")+ .eq("id", ownerId)+ .maybeSingle();+ if (owner.error) {+ logger.error("Failed to read company owner email", {+ companyId,+ error: owner.error+ });+ return false;+ }+ owned = isInternalEmail(owner.data?.email);+ }- return isInternalEmail(owner?.email);+ await redis.set(cacheKey, owned ? "1" : "0", "EX", PLAN_CACHE_TTL_SECONDS);+ return owned;}diff --git a/packages/ee/src/plan.server.test.ts b/packages/ee/src/plan.server.test.tsindex ff0d25ef58..96b1e6b5dd 100644--- a/packages/ee/src/plan.server.test.ts+++ b/packages/ee/src/plan.server.test.ts@@ -5,38 +5,19 @@import { Plan } from "@carbon/utils";import { beforeEach, describe, expect, it, vi } from "vitest";-const serviceRoleMaybeSingle = vi.hoisted(() => vi.fn());-const serviceRoleFrom = vi.hoisted(() =>- vi.fn(() => ({- select: () => ({ eq: () => ({ maybeSingle: serviceRoleMaybeSingle }) })- }))-);+const getCompanyPlanId = vi.hoisted(() => vi.fn());const isCarbonOwnedCompany = vi.hoisted(() => vi.fn());-const redisGet = vi.hoisted(() => vi.fn());-const redisSet = vi.hoisted(() => vi.fn());vi.mock("@carbon/auth", () => ({CarbonEdition: "cloud",error: vi.fn(),STRIPE_BYPASS_COMPANY_IDS: ""}));-vi.mock("@carbon/auth/client.server", () => ({- getCarbonServiceRole: () => ({ from: serviceRoleFrom })+vi.mock("@carbon/auth/company.server", () => ({+ getCompanyPlanId,+ isCarbonOwnedCompany}));-vi.mock("@carbon/auth/company.server", () => ({ isCarbonOwnedCompany }));vi.mock("@carbon/auth/session.server", () => ({ flash: vi.fn() }));-vi.mock("@carbon/kv", () => ({ redis: { get: redisGet, set: redisSet } }));-vi.mock("@carbon/logger/middleware.server", () => ({- oncePerRead: (_key: string, compute: () => unknown) => compute()-}));-vi.mock("@carbon/logger", () => ({- getLogger: () => ({- error: vi.fn(),- warn: vi.fn(),- info: vi.fn(),- debug: vi.fn()- })-}));import { companyHasFeature } from "./plan.server";@@ -55,21 +36,17 @@ function rlsBlockedClient() {return { from };}-describe("plan gate reads companyPlan via service role", () => {+describe("plan gate reads companyPlan through the shared service-role reader", () => {beforeEach(() => {vi.clearAllMocks();isCarbonOwnedCompany.mockResolvedValue(false);- redisGet.mockResolvedValue(null);});it("grants a PARTNER-* company MCP even when the caller's client cannot see the plan row", async () => {// 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.- serviceRoleMaybeSingle.mockResolvedValue({- data: { planId: "PARTNER-33" },- error: null- });+ getCompanyPlanId.mockResolvedValue("PARTNER-33");const client = rlsBlockedClient();const allowed = await companyHasFeature(client as never, "company-1", {@@ -77,15 +54,11 @@ describe("plan gate reads companyPlan via service role", () => {});expect(allowed).toBe(true);- expect(serviceRoleFrom).toHaveBeenCalledWith("companyPlan");expect(client.from).not.toHaveBeenCalled();});it("still blocks a Starter company", async () => {- serviceRoleMaybeSingle.mockResolvedValue({- data: { planId: Plan.Starter },- error: null- });+ getCompanyPlanId.mockResolvedValue(Plan.Starter);const allowed = await companyHasFeature(rlsBlockedClient() as never,@@ -98,35 +71,3 @@ describe("plan gate reads companyPlan via service role", () => {expect(allowed).toBe(false);});});--describe("plan gate cache", () => {- beforeEach(() => {- vi.clearAllMocks();- isCarbonOwnedCompany.mockResolvedValue(false);- redisGet.mockResolvedValue(null);- });-- it("answers from Redis without reading companyPlan", async () => {- redisGet.mockResolvedValue("PARTNER-33");-- const allowed = await companyHasFeature(- rlsBlockedClient() as never,- "company-1",- { feature: "MCP" }- );-- expect(allowed).toBe(true);- expect(redisGet).toHaveBeenCalledWith("companyPlan:company-1");- expect(serviceRoleFrom).not.toHaveBeenCalled();- });-- it("does not cache a missing plan row", async () => {- serviceRoleMaybeSingle.mockResolvedValue({ data: null, error: null });-- await companyHasFeature(rlsBlockedClient() as never, "company-3", {- feature: "MCP"- });-- expect(redisSet).not.toHaveBeenCalled();- });-});diff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.tsindex 4f41eecd05..9ab2d1464c 100644--- a/packages/ee/src/plan.server.ts+++ b/packages/ee/src/plan.server.ts@@ -3,19 +3,13 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { CarbonEdition, error, STRIPE_BYPASS_COMPANY_IDS } from "@carbon/auth";-import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { isCarbonOwnedCompany } from "@carbon/auth/company.server";+import {+ getCompanyPlanId,+ isCarbonOwnedCompany+} from "@carbon/auth/company.server";import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";-import { redis } from "@carbon/kv";-import { getLogger } from "@carbon/logger";-import { oncePerRead } from "@carbon/logger/middleware.server";-import {- companyPlanCacheKey,- Edition,- normalizePlanId,- Plan-} from "@carbon/utils";+import { Edition, normalizePlanId, Plan } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { redirect } from "react-router";import {@@ -25,8 +19,6 @@ import {resolveRequirement} from "./plan";-const logger = getLogger("ee", "plan");-function isBypassCompany(companyId: string): boolean {if (!STRIPE_BYPASS_COMPANY_IDS) return false;return STRIPE_BYPASS_COMPANY_IDS.split(",")@@ -34,60 +26,19 @@ function isBypassCompany(companyId: string): boolean {.includes(companyId);}-// The plan read MUST bypass RLS. `companyPlan`'s SELECT policy requires-// `auth.role() = 'authenticated'` AND an `auth.uid()` membership row — true for a-// web session's user client, but NOT for the anon `carbon-key` API-key client the-// 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`.-//-// `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+// The plan read is `getCompanyPlanId` (`@carbon/auth`): service role, cached, and+// shared with the API-key plan gate in `requirePermissions`. A failed read// 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.+// on a transient blip.//-// Cached in Redis and cleared by the Stripe sync; the TTL covers writes that-// don't clear it. A missing row is never cached.-const PLAN_CACHE_TTL_SECONDS = 60;--function readCompanyPlan(companyId: string): Promise<string | null> {- return oncePerRead(`companyPlan:${companyId}`, () =>- loadCompanyPlan(companyId)- );-}--async function loadCompanyPlan(companyId: string): Promise<string | null> {- const cacheKey = companyPlanCacheKey(companyId);- const cached = await redis.get(cacheKey);- if (cached) return cached;-- const { data, error: planError } = await getCarbonServiceRole()- .from("companyPlan")- .select("planId")- .eq("id", companyId)- .maybeSingle();-- if (planError) {- logger.error("getCompanyPlan failed", { companyId, error: planError });- }-- if (data?.planId) {- await redis.set(cacheKey, data.planId, "EX", PLAN_CACHE_TTL_SECONDS);- }-- return data?.planId ?? null;-}--// The `_client` param is kept for call-site compatibility; the read goes through-// the service role regardless (see `readCompanyPlan`).+// The `_client` param is kept for call-site compatibility; the read never goes+// through the caller's client, whose RLS scope can hide the plan row.async function getCompanyPlan(_client: SupabaseClient<Database>,companyId: string): Promise<Plan> {- return normalizePlanId(await readCompanyPlan(companyId));+ return normalizePlanId(await getCompanyPlanId(companyId));}/**@@ -113,7 +64,7 @@ export async function getPlan(// 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);+ const planId = await getCompanyPlanId(companyId);if (planId) return planId;// No durable plan row (never subscribed). Carbon-owned companies still get