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
feat(flags): rules name users by email, not by user id
Sidwebworksa0b64a87cbef
diff --git a/.ai/specs/2026-10-28-feature-flags.md b/.ai/specs/2026-10-28-feature-flags.mdindex 95114ddb18..c864b18290 100644--- a/.ai/specs/2026-10-28-feature-flags.md+++ b/.ai/specs/2026-10-28-feature-flags.md@@ -111,7 +111,8 @@ A rule can test any of them.| Field | Value | Set by ||-------|-------|--------|-| `targetingKey` | `userId`, else `companyId`. A `userIds` rule tests it. | The call site |+| `targetingKey` | `email`, else `companyId` | The call site |+| `email` | The user's email in lower case, when the call site passes one. An `emails` rule tests it. | The call site || `companyId` | The session's company | The call site (required) || `tenancy` | `"single"` or `"multi"`, from `SINGLE_TENANT` (`TENANT_TYPE`) | The provider || `edition` | `"cloud"`, `"enterprise"`, `"community"` or `"test"`, from `CarbonEdition` | The provider |@@ -176,7 +177,7 @@ exports, never through `process.env` (`packages/env/AGENTS.md`).| `CarbonFlagsProvider` | An OpenFeature provider. It loads the document and evaluates with `FlagdCore`. || `initFlags({ store, waitUntil })` | Sets the provider. Each app calls it once in `app/entry.server.tsx`. || `FlagsStore` (type) | The interface of the shared cache. `@carbon/kv` implements it with Redis. |-| `flags.bool(key, ctx)` | The only API that call sites use. `ctx` is `{ companyId, userId? }`, and `companyId` is required. The provider adds `tenancy` and `edition`. |+| `flags.bool(key, ctx)` | The only API that call sites use. `ctx` is `{ companyId, email? }`, and `companyId` is required. The provider adds `tenancy` and `edition`. || `evaluateBrowserFlags(ctx)` | Returns the value of every registry flag with `browser: true`, for the layout loaders. || `parseHeaders(raw)` | The `CARBON_FLAGS_HEADERS` parser. |@@ -305,7 +306,7 @@ rule (a 111 KB document):A flag with `browser: true` in the registry can reach React components.1. The ERP authenticated layout loader (`apps/erp/app/routes/x+/_layout.tsx`)- calls `evaluateBrowserFlags` with the session's `companyId` and `userId`.+ calls `evaluateBrowserFlags` with the session's `companyId` and `email`.The MES layout sends no flags until an MES component reads one; untilthen `useFeatureFlags()` in the MES answers the registry defaults.2. The loader returns the values as `flags: Record<string, FlagValue>`.@@ -360,17 +361,18 @@ Each source has:| Part | What it holds ||------|---------------|| Flag table | `key`, `description`, `variants` (JSON), `defaultVariant`, `archivedAt`, audit columns |-| Rule table | `flagKey`, `order`, `variant`, and the conditions: `companyIds`, `userIds`, `percent`, `tenancy` (`single`, `multi` or empty), `editions`, `instanceIds` (empty = every instance) |+| Rule table | `flagKey`, `order`, `variant`, and the conditions: `companyIds`, `emails`, `percent`, `tenancy` (`single`, `multi` or empty), `editions`, `instanceIds` (empty = every instance) || Instance token table | `instanceId`, `tokenHash` (SHA-256), `createdAt`, `revokedAt`, `lastFetchAt`, `lastCommit` (the most recent `X-Carbon-Commit` seen; during a rolling deploy it can show the old or the new build until every process runs the new one) || Change log | One row per save: who, when, the flag before and after || Admin form | Staff edit variants, default, rules and archive state || Endpoint | Section 2. It hashes the bearer token, finds the instance, compiles the rules into one `if` chain per flag and validates the result. It sets `lastFetchAt`. |A rule matches when all its non-empty conditions match. The endpoint-compiles a rule with 2 or more conditions into one `and`. A `userIds`-condition compiles to `{ "in": [{ "var": "targetingKey" }, [ … ]] }`.+compiles a rule with 2 or more conditions into one `and`. An `emails`+condition compiles to `{ "in": [{ "var": "email" }, [ … ]] }`, with each email+in lower case.-Use `userIds` with `companyIds` in one rule. Then the rule means "these+Use `emails` with `companyIds` in one rule. Then the rule means "thesepeople, in this company". A user rule without a company follows the userinto every company the user belongs to. A percentage always buckets bycompany, never by user, so one company never splits.@@ -495,7 +497,7 @@ companies to the staff. So with no source, behavior stays as it is today.1. The flag is one switch for every `internalOnly` integration, as the userlist is today. A user also needs access to the Onshape app in Onshape, so- each rule names the users (`userIds`) and their company (`companyIds`).+ each rule names the users (`emails`) and their company (`companyIds`).2. `isIntegrationComingSoon` (`packages/ee/src/plan.ts`) does not change. Itstill takes `hasEarlyAccess: boolean`.3. Its 2 callers pass the new value: `isIntegrationInstallWithheld`@@ -506,7 +508,7 @@ Before the deploy that removes the variable, do these steps:1. Find each company of each user in the list.2. For each company, add a rule with that company in `companyIds` and its- listed users in `userIds`.+ listed users' emails in `emails`.**Later flags.** These features are hidden in code until a dependency ships.Each one becomes a flag when its rollout starts:@@ -541,7 +543,7 @@ Each one becomes a flag when its rollout starts:| Instance auth | One flags token per instance, stored as a SHA-256 hash | Answer to Q2. Rotation and revocation touch nothing else. || Authoring | Admin form in each source, with a change log | Answer to Q3. || Who controls a flag per company | Carbon staff only, with a `companyIds` rule | Answer to Q13. Customers never see flags. |-| User targeting | A `userIds` condition, used with `companyIds` | Answer to Q16. A grant to a person stays inside the company that the rule names. |+| User targeting | An `emails` condition, used with `companyIds` | Answer to Q16. A grant to a person stays inside the company that the rule names. || Tenancy and edition | Fields in the evaluation context that a rule can test | Answer to Q14. Company rules work the same on single-tenant and multi-tenant instances. || Browser flags | Evaluated in the authenticated layout loader, read with `useFeatureFlags().feature(key)` | Answer to Q4. Rules never reach the browser. One hook in `@carbon/react` for both apps. || Readers | ERP and MES only | Answer to Q7. |@@ -593,8 +595,8 @@ and `flags_token` (text, secret). Both are nullable.| `apps/mes/package.json` | Add `@carbon/env` (dev dependency, like the other `@carbon/*` packages), for the `flags.server` import in the entry. || `apps/erp/app/routes/x+/settings+/companies.tsx`, `companies.$id.tsx`, `companies.delete.$id.tsx` | Redirect only when the user has no Carbon email and `multi-company-management` is off (section 10). || `apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx` | Show the Companies entry when `isInternal` or `useFeatureFlags().feature("multi-company-management")` is true. |-| `packages/ee/src/plan.server.ts` | `hasIntegrationEarlyAccess({ companyId, userId })` reads `integration-early-access`. Delete `isListedUserId` if nothing else uses it. |-| `apps/erp/app/modules/settings/settings.service.ts`, `apps/erp/app/routes/x+/settings+/integrations.tsx` | Pass `{ companyId, userId }` to `hasIntegrationEarlyAccess` and await it. |+| `packages/ee/src/plan.server.ts` | `hasIntegrationEarlyAccess({ companyId, userId, email })` reads `integration-early-access` with the email and the env list with the id. Delete `isListedUserId` if nothing else uses it. |+| `apps/erp/app/modules/settings/settings.service.ts`, `apps/erp/app/routes/x+/settings+/integrations.tsx` | Pass `{ companyId, userId, email }` to `hasIntegrationEarlyAccess` and await it. || `packages/ee/src/plan.test.ts` | Keep the `isIntegrationComingSoon` cases. They test a boolean, so they do not change. || `packages/env/src/schema.ts`, `packages/env/src/index.ts` | Keep `INTEGRATION_EARLY_ACCESS_USER_IDS`, described as a fallback until a flags source is live. || `.claude/rules/onshape-panel.md`, `.claude/rules/environment-configuration.md`, `packages/ee/AGENTS.md` | Replace `INTEGRATION_EARLY_ACCESS_USER_IDS` with the `integration-early-access` flag. |@@ -651,7 +653,7 @@ None in the ERP or the MES. The admin form is in each source (section 6).- [ ] With 5 providers on one store, the source receives at most 1 request per 60 s.- [ ] A document that one provider writes to the store reaches a second provider on its next sync.- [ ] With the store unavailable, a provider fetches the source directly and still evaluates flags.-- [ ] A rule with `companyIds = [cmp_A]` and `userIds = [usr_X]` is on for `usr_X` in `cmp_A`. It is off for `usr_X` in `cmp_B` and for `usr_Y` in `cmp_A`.+- [ ] A rule with `companyIds = [cmp_A]` and `emails = [[email protected]]` is on for `[email protected]` in `cmp_A`. It is off for `[email protected]` in `cmp_B` and for `[email protected]` in `cmp_A`.- [ ] A `data:` endpoint loads once and the provider never fetches again.- [ ] A BYOC deploy with the console down fails before rollout, and the old release keeps serving.- [ ] `ci/src/deploy.ts` on a `workspaces` row with `flags_endpoint` set passes a `data:` `CARBON_FLAGS_ENDPOINT` to `sst deploy`. A row without it passes none.@@ -715,3 +717,4 @@ None in the ERP or the MES. The admin form is in each source (section 6).- 2026-10-29: PR review. Subsidiary create and update follow `multi-company-management` like the Companies pages. Header names are case-insensitive. The Redis scope includes the flagd-core version, so a process that rejects the copy on its own key repairs it. `ci/src/deploy.ts` validates with flagd-core strict mode and the boolean registry, and sends `flags_token` only over https.- 2026-10-29: Self-review. `INTEGRATION_EARLY_ACCESS_USER_IDS` stays as a fallback beside the flag, so merging before a flags source exists takes nobody's early access away. The CI fetch and validator moved to `ci/src/flags.ts` with tests.- 2026-10-29: PR review. `createSubsidiary` requires a parent in the caller's group. `updateSubsidiaryDetails` checks the company and its new parent are in the caller's group, and clears exchange-rate overrides in the same transaction when the base currency changes. The provider refuses an endpoint that is not https: or data:.+- 2026-10-29: Rules name users by email, not by user id. Staff know emails, and a BYOC console cannot see a customer's user ids. `targetingKey` is the email, else the company. The env list fallback still holds user ids.diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 75e7181f09..3b39bad9ea 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -670,7 +670,11 @@ export async function isIntegrationInstallWithheld(!isIntegrationComingSoon(integration, {edition: CarbonEdition,email,- hasEarlyAccess: await hasIntegrationEarlyAccess({ companyId, userId })+ hasEarlyAccess: await hasIntegrationEarlyAccess({+ companyId,+ userId,+ })})) {return false;@@ -3414,12 +3418,13 @@ export async function refuseUnlessCanManageCompanies(.select("email").eq("id", ctx.actor.userId).maybeSingle();- if (isInternalEmail(data?.email ?? "")) return null;+ const email = data?.email ?? "";+ if (isInternalEmail(email)) return null;// The same rule as the Settings → Companies pages: Carbon staff, and the// companies the `multi-company-management` flag turns it on for.const enabled = await flags.bool("multi-company-management", {companyId: ctx.company.id,- userId: ctx.actor.userId});return enabled ? null : refused;}diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 54cd0009d6..8a3b8e86c2 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -141,7 +141,8 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({export async function loader({ request }: LoaderFunctionArgs) {const authSession = await requireAuthSession(request, { verify: true });- const { accessToken, companyId, expiresAt, expiresIn, userId } = authSession;+ const { accessToken, companyId, email, expiresAt, expiresIn, userId } =+ authSession;// Block ERP access when console mode is active on this terminal.// Console terminals should only access the MES app.@@ -348,7 +349,7 @@ export async function loader({ request }: LoaderFunctionArgs) {company,companies: companies.data ?? [],// Feature flags with `browser: true`, read with `useFeatureFlags().feature(key)`.- flags: await evaluateBrowserFlags({ companyId, userId }),+ flags: await evaluateBrowserFlags({ companyId, email }),companySettings: companySettings.data ?? null,customFields: customFields.data ?? [],defaults: defaults.data,diff --git a/apps/erp/app/routes/x+/settings+/companies.$id.tsx b/apps/erp/app/routes/x+/settings+/companies.$id.tsxindex 2c78191104..ffff83a320 100644--- a/apps/erp/app/routes/x+/settings+/companies.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.$id.tsx@@ -17,18 +17,15 @@ import { CompanyForm } from "~/modules/settings/ui";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId, email, userId } = await requirePermissions(- request,- {- view: "settings"- }- );+ const { client, companyId, email } = await requirePermissions(request, {+ view: "settings"+ });// Multi-company management: Carbon staff, and the companies the// `multi-company-management` flag turns it on for.if (!isInternalEmail(email) &&- !(await flags.bool("multi-company-management", { companyId, userId }))+ !(await flags.bool("multi-company-management", { companyId, email }))) {throw redirect(path.to.settings);}diff --git a/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx b/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsxindex ed66161598..ccc79c286c 100644--- a/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx@@ -21,18 +21,15 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "settings-companies-delete");export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId, email, userId } = await requirePermissions(- request,- {- view: "settings"- }- );+ const { client, companyId, email } = await requirePermissions(request, {+ view: "settings"+ });// Multi-company management: Carbon staff, and the companies the// `multi-company-management` flag turns it on for.if (!isInternalEmail(email) &&- !(await flags.bool("multi-company-management", { companyId, userId }))+ !(await flags.bool("multi-company-management", { companyId, email }))) {throw redirect(path.to.settings);}@@ -52,7 +49,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}export async function action({ request, params }: ActionFunctionArgs) {- const { companyGroupId, companyId, email, userId } = await requirePermissions(+ const { companyGroupId, companyId, email } = await requirePermissions(request,{delete: "settings"@@ -63,7 +60,7 @@ export async function action({ request, params }: ActionFunctionArgs) {// `multi-company-management` flag turns it on for.if (!isInternalEmail(email) &&- !(await flags.bool("multi-company-management", { companyId, userId }))+ !(await flags.bool("multi-company-management", { companyId, email }))) {throw redirect(path.to.settings);}diff --git a/apps/erp/app/routes/x+/settings+/companies.tsx b/apps/erp/app/routes/x+/settings+/companies.tsxindex ce24ad3321..bff9ef6037 100644--- a/apps/erp/app/routes/x+/settings+/companies.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.tsx@@ -37,7 +37,7 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { companyGroupId, companyId, email, userId } = await requirePermissions(+ const { companyGroupId, companyId, email } = await requirePermissions(request,{view: "settings"@@ -48,7 +48,7 @@ export async function loader({ request }: LoaderFunctionArgs) {// `multi-company-management` flag turns it on for.if (!isInternalEmail(email) &&- !(await flags.bool("multi-company-management", { companyId, userId }))+ !(await flags.bool("multi-company-management", { companyId, email }))) {throw redirect(path.to.settings);}diff --git a/apps/erp/app/routes/x+/settings+/integrations.tsx b/apps/erp/app/routes/x+/settings+/integrations.tsxindex 948e4bfe2e..db12bf3739 100644--- a/apps/erp/app/routes/x+/settings+/integrations.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.tsx@@ -28,9 +28,12 @@ export const config = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- view: "settings"- });+ const { client, companyId, email, userId } = await requirePermissions(+ request,+ {+ view: "settings"+ }+ );const integrations = await getIntegrationsWithHealth(client, companyId);if (integrations.error) {@@ -79,7 +82,11 @@ export async function loader({ request }: LoaderFunctionArgs) {integrations: items,activeRoles,// Decided here so the flag's rules never reach the browser.- hasEarlyAccess: await hasIntegrationEarlyAccess({ companyId, userId })+ hasEarlyAccess: await hasIntegrationEarlyAccess({+ companyId,+ userId,+ })// No OAuth state here. Every OAuth install now starts at// `api+/integrations.$id.connect`, which issues a SIGNED, browser-bound,// single-use state — strictly better than the unsigned correlation value thisdiff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.tsindex 62eae94a22..c4bbd548ca 100644--- a/packages/ee/src/plan.server.ts+++ b/packages/ee/src/plan.server.ts@@ -35,20 +35,25 @@ function isBypassCompany(companyId: string): boolean {/*** Whether this user may install an `internalOnly` integration on Carbon Cloud* without a Carbon email (`isIntegrationComingSoon`): the- * `integration-early-access` flag is on for them in this company, or their id+ * `integration-early-access` flag is on for their email in this company, or their id* is listed in `INTEGRATION_EARLY_ACCESS_USER_IDS`. The flag's rules name the* users and their company, because each user also needs access to the app on* the provider's side (the Onshape app, in Onshape). The env list stays as a* fallback until a flags source is live; remove it once the users it lists* have flag rules.*/-export async function hasIntegrationEarlyAccess(context: {+export async function hasIntegrationEarlyAccess({+ companyId,+ userId,+}: {companyId: string;userId: string;+ email: string;}): Promise<boolean> {return (- isListedUserId(INTEGRATION_EARLY_ACCESS_USER_IDS, context.userId) ||- flags.bool("integration-early-access", context)+ isListedUserId(INTEGRATION_EARLY_ACCESS_USER_IDS, userId) ||+ flags.bool("integration-early-access", { companyId, email }));}diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.mdindex 09102bed2c..9fb8874282 100644--- a/packages/env/AGENTS.md+++ b/packages/env/AGENTS.md@@ -48,7 +48,7 @@ pnpm --filter @carbon/env test- **Feature flags (`@carbon/env/flags` + `@carbon/env/flags.server`):** spec `.ai/specs/2026-10-28-feature-flags.md`.- `./flags` is browser-safe: the registry `FLAGS` (each flag's default and whether it goes to the browser), `flagDefault`, `BrowserFlagKey`. Add a flag there first; a key not in `FLAGS` is a type error. The default is the safe value: it is what an instance does with no flags source.- - `./flags.server`: `initFlags({ store, waitUntil, onWarning })` (called once in each app's `entry.server.tsx`), `flags.bool(key, { companyId, userId? })` (never throws, default from `FLAGS`), `evaluateBrowserFlags` (for the layout loaders), `parseHeaders`, and the `FlagsStore` interface that `@carbon/kv`'s `redisFlagsStore` implements (this package cannot import `@carbon/kv`).+ - `./flags.server`: `initFlags({ store, waitUntil, onWarning })` (called once in each app's `entry.server.tsx`), `flags.bool(key, { companyId, email? })` (never throws, default from `FLAGS`; rules match the email in lower case), `evaluateBrowserFlags` (for the layout loaders), `parseHeaders`, and the `FlagsStore` interface that `@carbon/kv`'s `redisFlagsStore` implements (this package cannot import `@carbon/kv`).- `CARBON_FLAGS_ENDPOINT` (`https:` polls through Redis, `http:` only on localhost; `data:` loads once; any other scheme is refused with a warning) and `CARBON_FLAGS_HEADERS` (OTEL headers format, secret).- Read flags only through `flags.*`, `evaluateBrowserFlags` and `useFeatureFlags()` (`@carbon/react`), never with an OpenFeature client: the wrapper requires `companyId` and takes each default from `FLAGS`. Flags are booleans until one needs another type.diff --git a/packages/env/src/flags.server.test.ts b/packages/env/src/flags.server.test.tsindex 9f6dea30ce..073cdd8a2d 100644--- a/packages/env/src/flags.server.test.ts+++ b/packages/env/src/flags.server.test.ts@@ -474,4 +474,38 @@ describe("flags and evaluateBrowserFlags", () => {"multi-company-management": true});});+ it("match a user rule by email, in lower case", async () => {+ const doc = JSON.stringify({+ flags: {+ "integration-early-access": {+ state: "ENABLED",+ variants: { on: true, off: false },+ defaultVariant: "off",+ targeting: {+ if: [+ {+ and: [+ { "==": [{ var: "companyId" }, "cmp_A"] },+ { in: [{ var: "email" }, ["[email protected]"]] }+ ]+ },+ "on",+ null+ ]+ }+ }+ }+ });+ await OpenFeature.setProviderAndWait(+ new CarbonFlagsProvider({+ endpoint: `data:application/json;base64,${Buffer.from(doc).toString("base64")}`+ })+ );+ const read = (companyId: string, email?: string) =>+ flags.bool("integration-early-access", { companyId, email });+ expect(await read("cmp_A", " [email protected] ")).toBe(true);+ expect(await read("cmp_B", "[email protected]")).toBe(false);+ expect(await read("cmp_A", "[email protected]")).toBe(false);+ expect(await read("cmp_A")).toBe(false);+ });});diff --git a/packages/env/src/flags.server.ts b/packages/env/src/flags.server.tsindex 54ed539708..7a4b20aab3 100644--- a/packages/env/src/flags.server.ts+++ b/packages/env/src/flags.server.ts@@ -543,10 +543,11 @@ export async function initFlags(/*** `companyId` is required: a call without it would match no company rule and- * answer the default without telling anyone. Pass `userId` for a flag whose- * rules name users.+ * answer the default without telling anyone. Pass `email` for a flag whose+ * rules name users: staff write rules by email, since a BYOC console cannot+ * see a customer's user ids. Rules match it in lower case.*/-export type FlagContext = { companyId: string; userId?: string };+export type FlagContext = { companyId: string; email?: string };let client: Client | undefined;const getClient = () => {@@ -554,11 +555,14 @@ const getClient = () => {return client;};-const toContext = ({ companyId, userId }: FlagContext): EvaluationContext => ({- targetingKey: userId ?? companyId,- companyId,- ...(userId ? { userId } : {})-});+const toContext = ({ companyId, email }: FlagContext): EvaluationContext => {+ const normalized = email?.trim().toLowerCase();+ return {+ targetingKey: normalized || companyId,+ companyId,+ ...(normalized ? { email: normalized } : {})+ };+};/*** The only way code reads a flag. The default comes from the registry