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.

feat(flags): feature flags for Carbon instances, loaded from a URL like OTEL (#2073)

Sidf3c007ab5faf
diff --git a/.ai/plans/2026-10-28-feature-flags.md b/.ai/plans/2026-10-28-feature-flags.md
new file mode 100644
index 0000000000..2f35ec8049
--- /dev/null
+++ b/.ai/plans/2026-10-28-feature-flags.md
@@ -0,0 +1,327 @@
+# Feature flags — implementation plan
+
+**Spec:** .ai/specs/2026-10-28-feature-flags.md
+**Research:** .ai/research/2026-10-28-feature-flags.md
+**Closest sibling:** the OTEL exporter config (`packages/logger/src/tracing.server.ts`); for the hook, `apps/erp/app/hooks/useFlags.tsx`
+**Branch:** `feat/feature-flags` (worktree `../carbon-feature-flags`)
+
+## Progress
+- [x] Task 1: Create the branch worktree
+- [x] Task 2: Add the OpenFeature dependencies and exports
+- [x] Task 3: Add the two environment variables
+- [x] Task 4: Add the flag registry
+- [x] Task 5: Build the provider and its tests
+- [x] Task 6: Build the Redis flags store and its test
+- [x] Task 7: Start the provider in the ERP and MES entries
+- [x] Task 8: Send browser flags and extend `useFlags`
+- [x] Task 9: Put Settings → Companies behind `multi-company-management`
+- [x] Task 10: Put integration early access behind `integration-early-access`
+- [x] Task 11: Add the `flags-through-env` check
+- [x] Task 12: Pass the variables in deploy config and `ci/src/deploy.ts`
+- [x] Task 13: Update the docs and AGENTS files
+- [x] Task 14: Run every gate and verify in the browser
+
+## Changes during the build
+- Task 6: the Redis store has no unit test. `test-mocks-own-module` refuses `vi.mock("./client")`, and `.claude/rules/testing.md` treats glue as covered by typecheck.
+- Task 8: `no-duplicated-app-file` refuses a `useFlags.tsx` in both apps. The hook is `useFeatureFlags()` in `@carbon/react`. The ERP `useFlags` returns its `feature`; the MES has no hook of its own.
+- Task 12: `ci/src/deploy.ts` caps the document at 32 KiB, because an ECS task definition is at most 64 KiB. `ci` has no tsconfig, so esbuild only checks that the file parses.
+- Task 14: no dev stack runs for this worktree, so no browser test ran. The MES production build loads, and its flags provider starts from a `data:` endpoint.
+
+## Dependencies
+Task 1 first. Task 2 before Tasks 4–6. Task 3 before Task 5. Tasks 5 and 6
+before Task 7. Task 7 before Tasks 8–10. Tasks 11, 12 and 13 are independent
+of Tasks 8–10. Task 14 is last.
+
+---
+
+## Task 1: Create the branch worktree
+
+**Depends on:** none
+**Files:**
+- Create: `../carbon-feature-flags` (git worktree)
+
+**Steps:**
+1. Run `git worktree add ../carbon-feature-flags -b feat/feature-flags main` from the main checkout.
+2. Copy the spec, research and plan files into the same paths in the worktree.
+3. Run `pnpm install` in the worktree.
+
+**Verify:**
+```bash
+git -C ../carbon-feature-flags branch --show-current
+# Expected: feat/feature-flags
+```
+
+**Out of scope:** the main checkout. Commit nothing there.
+
+## Task 2: Add the OpenFeature dependencies and exports
+
+**Depends on:** 1
+**Files:**
+- Modify: `pnpm-workspace.yaml` — add to `catalog:`: `"@openfeature/core": 1.12.0`, `"@openfeature/server-sdk": 1.23.0`, `"@openfeature/flagd-core": 5.0.0`.
+- Modify: `packages/env/package.json` — add the 3 packages as `"catalog:"` dependencies. Add the exports `"./flags": "./src/flags.ts"` and `"./flags.server": "./src/flags.server.ts"`.
+- Copy from (precedent): the `"./push.server"` export in the same file.
+
+**Steps:**
+1. Edit the two files.
+2. Run a bare `pnpm install`. Never use `--filter`, because it prunes the lockfile.
+3. Check `git diff --stat pnpm-lock.yaml`. It must show added lines only for the 3 packages and their dependencies.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/env exec node -e "require.resolve('@openfeature/flagd-core')" && echo ok
+# Expected: ok
+```
+
+**Out of scope:** any other package's dependencies.
+
+## Task 3: Add the two environment variables
+
+**Depends on:** 1
+**Files:**
+- Modify: `packages/env/src/schema.ts` — add after `SYSTEM_STATUS_URL`:
+ - `CARBON_FLAGS_ENDPOINT`: `{ group: "core", description: "URL of the feature flags document: https:, data: or file:", type: url }`
+ - `CARBON_FLAGS_HEADERS`: `{ group: "core", description: "Headers for CARBON_FLAGS_ENDPOINT, as k=v pairs separated by commas (OTEL format)", secret: true }`
+- Modify: `packages/env/src/index.ts` — add `export const CARBON_FLAGS_ENDPOINT = getEnv("CARBON_FLAGS_ENDPOINT");` and the same for `CARBON_FLAGS_HEADERS`, after `SYSTEM_STATUS_URL`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/env test
+# Expected: all tests pass
+```
+
+**Out of scope:** `getBrowserEnv()`. Neither variable goes to the browser.
+
+## Task 4: Add the flag registry
+
+**Depends on:** 2
+**Files:**
+- Create: `packages/env/src/flags.ts`
+
+**Steps:**
+1. Write the SPDX header with `pnpm --filter @carbon/checks license-headers` after the file exists.
+2. Export `FLAGS` with the 2 v1 entries (spec section 10), `as const`.
+3. Export the types `FlagKey`, `FlagValue<K>` (boolean, string or number from `type`), `BrowserFlagKey` (keys with `browser: true`) and `BrowserFlags` (`Partial<Record<BrowserFlagKey, …>>`).
+4. Export `flagDefault(key)`, which returns `FLAGS[key].default`.
+5. Import nothing from `.server` files and nothing from `node:*`. This file reaches the browser.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/env --concurrency=1
+# Expected: Tasks: 1 successful
+```
+
+## Task 5: Build the provider and its tests
+
+**Depends on:** 2, 3, 4
+**Files:**
+- Create: `packages/env/src/flags.server.ts`
+- Create: `packages/env/src/flags.server.test.ts`
+- Copy from (precedent): the tested scratch provider `nodeflags/provider.ts` in the session scratchpad. Rewrite it for the three layers below.
+
+**Steps:**
+1. Export `parseHeaders(raw)`. Skip a pair with no `=` or a bad `%` sequence, log it, and never throw.
+2. Export the type `FlagsStore`:
+ ```ts
+ export type StoredFlags = { body: string; etag: string; fetchedAt: number };
+ export type FlagsStore = {
+ readMeta(scope: string): Promise<Pick<StoredFlags, "etag" | "fetchedAt"> | null>;
+ readBody(scope: string): Promise<string | null>;
+ write(scope: string, value: Partial<StoredFlags> & { fetchedAt: number }): Promise<void>;
+ tryLease(scope: string): Promise<{ status: "acquired"; release: () => Promise<void> } | { status: "held" } | { status: "unavailable" }>;
+ };
+ ```
+3. Export `CarbonFlagsProvider`, an OpenFeature `Provider` (`runsOn = "server"`). Implement the behavior list in spec section 3, steps 1–11, exactly.
+4. Compute `scope` as the first 16 hex characters of `sha256(endpoint + "\n" + headers)`.
+5. Use these constants: sync 10 s, source 60 s, jitter ± 20%, fetch timeout 5 s, boot wait 2 s, lease 10 s, body cap 1 MB.
+6. Add `tenancy` (`SINGLE_TENANT ? "single" : "multi"`) and `edition` (`CarbonEdition`) to every evaluation context.
+7. Export `initFlags({ store, waitUntil })`. It reads `CARBON_FLAGS_ENDPOINT` and `CARBON_FLAGS_HEADERS` from `./index`, builds the provider and calls `OpenFeature.setProviderAndWait`. A second call does nothing.
+8. Export `flags.bool`, `flags.string`, `flags.number`. Each takes `(key, { companyId, userId? })`, takes the default from `FLAGS`, and never throws.
+9. Export `evaluateBrowserFlags({ companyId, userId })`. It returns `BrowserFlags` for every key with `browser: true`.
+10. Export `flagStatus()`, which returns `{ confirmedAt, lastError }`.
+11. Write one test per acceptance criterion of the provider in the spec. Use a local `node:http` server and an in-memory `FlagsStore`. Cover these cases:
+ - unset endpoint
+ - company targeting, user targeting, `tenancy` and `edition`
+ - ETag and `304`
+ - the header parse
+ - the 1 MB cap
+ - boot that waits at most 2 s with an empty store and does not wait with a filled store
+ - 5 providers on one store, with at most 1 source request
+ - a store write that reaches a second provider
+ - an unavailable store
+ - a `data:` endpoint that never fetches again
+ - one archived-flag warning per key
+12. Run the license-header fixer.
+
+If `vi.useFakeTimers` blocks the local server, STOP and report — do not improvise.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/env test -- flags.server
+# Expected: every flags.server test passes
+```
+
+**Out of scope:** Redis. This package must not import `@carbon/kv`.
+
+## Task 6: Build the Redis flags store and its test
+
+**Depends on:** 5
+**Files:**
+- Create: `packages/kv/src/flags-store.ts`
+- Create: `packages/kv/src/flags-store.test.ts`
+- Modify: `packages/kv/src/index.ts` — export `redisFlagsStore`.
+- Copy from (precedent): `packages/kv/src/lease.ts` and `lease.test.ts`.
+
+**Steps:**
+1. Import the type `FlagsStore` from `@carbon/env/flags.server`.
+2. Implement it on the hash `flags:<scope>`: `readMeta` is `HMGET etag fetchedAt`, `readBody` is `HGET body`, and `write` is one `HSET`.
+3. Implement `tryLease` with `acquireLease("flags:<scope>:refresh", 10_000)` and `releaseLease`.
+4. Test it with `ioredis-mock`, the way `lease.test.ts` does.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/kv test -- flags-store
+# Expected: every flags-store test passes
+```
+
+## Task 7: Start the provider in the ERP and MES entries
+
+**Depends on:** 5, 6
+**Files:**
+- Modify: `apps/erp/app/entry.server.tsx`, `apps/mes/app/entry.server.tsx`
+
+**Steps:**
+1. Import `initFlags` from `@carbon/env/flags.server` and `redisFlagsStore` from `@carbon/kv`.
+2. At module level, after the tracing setup, call `void initFlags({ store: redisFlagsStore, waitUntil })`. `waitUntil` is already imported from `@vercel/functions`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --concurrency=1 && pnpm exec turbo run typecheck --filter=mes --concurrency=1
+# Expected: both successful
+```
+
+## Task 8: Send browser flags and extend `useFlags`
+
+**Depends on:** 7
+**Files:**
+- Modify: `apps/erp/app/routes/x+/_layout.tsx`, `apps/mes/app/routes/x+/_layout.tsx` — add `flags: await evaluateBrowserFlags({ companyId, userId })` to the `data({ … })` return.
+- Modify: `apps/erp/app/hooks/useFlags.tsx` — add `feature(key: BrowserFlagKey)`. It reads `flags` with `useRouteData(path.to.authenticatedRoot)` and falls back to `flagDefault(key)`.
+- Create: `apps/mes/app/hooks/useFlags.tsx` — the same `feature(key)`. Read the MES layout data the way `apps/mes/app/hooks/useUser.tsx` does.
+- Copy from (precedent): `apps/erp/app/hooks/useFlags.tsx`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --concurrency=1 && pnpm exec turbo run typecheck --filter=mes --concurrency=1
+# Expected: both successful
+```
+
+**Out of scope:** `shouldRevalidate`. Do not change it.
+
+## Task 9: Put Settings → Companies behind `multi-company-management`
+
+**Depends on:** 8
+**Files:**
+- Modify: `apps/erp/app/routes/x+/settings+/companies.tsx`, `companies.$id.tsx`, `companies.delete.$id.tsx`
+- Modify: `apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx`
+
+**Steps:**
+1. In each loader and action, replace `if (!isInternalEmail(email))` with `if (!isInternalEmail(email) && !(await flags.bool("multi-company-management", { companyId, userId })))`.
+2. Get `companyId` and `userId` from the `requirePermissions` result that each route already has.
+3. In `useSettingsSubmodules`, hide `path.to.companies` only when `!isInternal && !feature("multi-company-management")`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --concurrency=1
+# Expected: successful
+```
+
+## Task 10: Put integration early access behind `integration-early-access`
+
+**Depends on:** 7
+**Files:**
+- Modify: `packages/ee/src/plan.server.ts` — `hasIntegrationEarlyAccess({ companyId, userId })` returns `flags.bool("integration-early-access", { companyId, userId })`. Delete `isListedUserId` if nothing else calls it.
+- Modify: `apps/erp/app/modules/settings/settings.service.ts` (`isIntegrationInstallWithheld`) and `apps/erp/app/routes/x+/settings+/integrations.tsx` — pass `{ companyId, userId }` and `await` the result.
+- Modify: `packages/env/src/schema.ts`, `packages/env/src/index.ts` — remove `INTEGRATION_EARLY_ACCESS_USER_IDS`.
+
+**Steps:**
+1. Run `grep -rn "INTEGRATION_EARLY_ACCESS_USER_IDS\|hasIntegrationEarlyAccess\|isListedUserId" apps packages` first. Change every hit.
+2. Keep `isIntegrationComingSoon` and `plan.test.ts` unchanged.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee test && pnpm exec turbo run typecheck --filter=@carbon/ee --concurrency=1
+# Expected: tests pass, typecheck successful
+```
+
+## Task 11: Add the `flags-through-env` check
+
+**Depends on:** 1
+**Files:**
+- Create: `packages/checks/src/conformance/flags-through-env.ts`, `flags-through-env.test.ts`
+- Modify: `packages/checks/src/index.ts`, `packages/checks/src/run.ts` — register the check.
+- Copy from (precedent): `packages/checks/src/conformance/no-integration-id-branching.ts` and its test.
+
+**Steps:**
+1. Flag any import of `@openfeature/` in a TypeScript file outside `packages/env/`.
+2. Name the fix in the message: "Read flags with `flags.*` from `@carbon/env/flags.server`."
+
+**Verify:**
+```bash
+pnpm --filter @carbon/checks test -- flags-through-env
+# Expected: the test passes
+```
+
+## Task 12: Pass the variables in deploy config and `ci/src/deploy.ts`
+
+**Depends on:** 3
+**Files:**
+- Modify: `.env.example` — 2 commented lines after `SYSTEM_STATUS_URL`.
+- Modify: `contrib/deploying/simple-docker-caddy/docker-compose.prod.yml` — `CARBON_FLAGS_ENDPOINT: ${CARBON_FLAGS_ENDPOINT:-}` and the same for the headers, in both services.
+- Modify: `sst.config.ts` — forward `CARBON_FLAGS_ENDPOINT` in both environment blocks, next to `SYSTEM_STATUS_URL`.
+- Modify: `ci/src/deploy.ts` — add `flags_endpoint` and `flags_token` (both `string | null`) to `Workspace`.
+
+**Steps:**
+1. In `ci/src/deploy.ts`, before the `$$` env object, fetch `flags_endpoint` with `Authorization: Bearer <flags_token>` when `flags_endpoint` is set.
+2. Use a 10 s timeout and a 1 MB cap. On any failure, throw, so this workspace's deploy fails.
+3. Pass `CARBON_FLAGS_ENDPOINT: "data:application/json;base64," + base64(body)` in the env object.
+
+If the `workspaces` table has no `flags_endpoint` column, add the field to the type anyway. STOP and report that the CI database needs the 2 columns — do not create them.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=ci --concurrency=1
+# Expected: successful
+```
+
+## Task 13: Update the docs and AGENTS files
+
+**Depends on:** 10
+**Files:**
+- Modify: `.claude/rules/environment-configuration.md` — a "Feature flags" paragraph after "Maintenance and status". Remove `INTEGRATION_EARLY_ACCESS_USER_IDS`.
+- Modify: `packages/env/AGENTS.md` — the flags exports, the registry and the lifecycle.
+- Modify: `packages/kv/AGENTS.md` if it exists — `redisFlagsStore`.
+- Modify: `.claude/rules/onshape-panel.md`, `packages/ee/AGENTS.md` — replace `INTEGRATION_EARLY_ACCESS_USER_IDS` with the `integration-early-access` flag.
+
+**Verify:**
+```bash
+grep -rn "INTEGRATION_EARLY_ACCESS_USER_IDS" apps packages .claude --include=*.ts --include=*.tsx --include=*.md
+# Expected: no output
+```
+
+## Task 14: Run every gate and verify in the browser
+
+**Depends on:** all
+**Steps:**
+1. Run `pnpm --filter @carbon/checks license-headers`.
+2. Run the typechecks one at a time: `@carbon/env`, `@carbon/kv`, `@carbon/ee`, `@carbon/checks`, `erp`, `mes`, `ci`.
+3. Run the tests: `@carbon/env`, `@carbon/kv`, `@carbon/ee`, `@carbon/checks`.
+4. Run `pnpm run lint`.
+5. Run `pnpm --filter @carbon/checks start` and confirm the new check reports no violation.
+6. If a dev stack runs, use `/test` with no `CARBON_FLAGS_ENDPOINT`. A user with a Carbon email opens Settings → Companies. Then set a `data:` endpoint that turns `multi-company-management` on for the company, and confirm the page for a user without a Carbon email.
+
+**Verify:**
+```bash
+pnpm run lint
+# Expected: no errors
+```
+
+**Out of scope:** the console, the CSA dashboard and the byoc repo.
diff --git a/.ai/research/2026-10-28-feature-flags.md b/.ai/research/2026-10-28-feature-flags.md
new file mode 100644
index 0000000000..d1bed68ed5
--- /dev/null
+++ b/.ai/research/2026-10-28-feature-flags.md
@@ -0,0 +1,69 @@
+# Research — feature flags for Carbon instances
+
+Date: 2026-10-28. Spec: `.ai/specs/2026-10-28-feature-flags.md`.
+
+## Question
+
+A Carbon instance gets its feature flags from a URL that the operator sets,
+like the OTEL exporter. The instance can be Carbon Cloud or BYOC. Which
+open-source format and library fit this?
+
+## Options surveyed
+
+| Option | Kind | License | Fit |
+|--------|------|---------|-----|
+| OpenFeature SDKs (`@openfeature/server-sdk` 1.23.0, Go `go-sdk` 1.20.0) | Vendor-neutral evaluation API | Apache-2.0 | Good. A custom provider puts any backend behind one API. |
+| flagd file format + `@openfeature/flagd-core` 5.0.0 (JS) / `flagd/core` 0.19.1 (Go) | Flag JSON schema and an in-process evaluation library | Apache-2.0 | Good. Both languages evaluate the same JSON. No daemon is necessary. |
+| flagd daemon | A server that serves the flagd format | Apache-2.0 | Not necessary. We use the format and the library, not the daemon. |
+| Flags SDK (`flags`, Vercel) | Flags declared in code with a `decide()` function | MIT | Weak. It targets Next.js and SvelteKit. Carbon uses React Router. |
+| GrowthBook SDK | Local evaluation of a features JSON | MIT | Possible. It has its own format with no Go-and-JS shared standard. |
+| Unleash, Flagsmith, Flipt, FeatBit, GO Feature Flag | Self-hosted flag platforms | Open source | Too much for v1. Each one is a server to run. All have OpenFeature providers, so a later move is a provider swap. |
+
+## What we verified
+
+1. `FlagdCore.setConfigurations(json)` and `resolveBooleanEvaluation(key, default, context)`
+ exist in `@openfeature/flagd-core` 5.0.0.
+2. In Go, `evaluator.NewJSON(logger, store)`, `SetState(sync.DataSync{FlagData, Source})`
+ and `ResolveBooleanValue(ctx, reqID, key, context)` exist in `flagd/core` 0.19.1.
+3. A scratch Go client and a scratch Node provider load the same flagd JSON.
+ Both give the same answers. A targeted company gets `true`, another company
+ gets `false`, and a missing flag gets the code default.
+4. A scratch Go server compiles flag rules into flagd JSON per instance. It
+ validates the output with the flagd evaluator before it sends it. Tests
+ cover 401, 200, 304 and the removal of rules that other instances own.
+5. The OTEL exporter in Carbon reads `OTEL_EXPORTER_OTLP_ENDPOINT` and
+ `OTEL_EXPORTER_OTLP_HEADERS` from `process.env`
+ (`packages/logger/src/tracing.server.ts`). The header format is
+ `key=value` pairs, separated by commas, with percent-encoded values.
+
+## Pitfalls found in review
+
+| Pitfall | Mitigation |
+|---------|------------|
+| A cold serverless instance starts on code defaults while warm instances keep the loaded flags | Keep the last good document in Redis. Load it before the first fetch. |
+| Go `url.QueryUnescape` changes `+` to a space | Use `url.PathUnescape`. Test a value with `+`, `%2C` and `=` in both languages. |
+| `decodeURIComponent` throws on a bad `%` sequence | Skip the bad pair and log it. Flags never stop the app from starting. |
+| Vercel pauses the process after the response | Run the background refresh through `waitUntil`. Set the next refresh time only after the fetch ends. |
+| A call site without `companyId` gets the default and no error | Export a typed wrapper that requires `companyId`. |
+| A large response body fills memory | Refuse a body over 1 MB. |
+| A failing endpoint shows only in the logs | Expose the age of the loaded flags and the last error. |
+| The first fetch blocks startup | Wait at most 2 seconds, then continue in the background. |
+| Deleting a flag on the server sends every instance back to the code default | Delete the flag only after the code no longer reads it. |
+| Instances that one deploy started poll at the same time | Add ±20% jitter to the 60-second interval. |
+
+## Sources
+
+- https://openfeature.dev
+- https://flagd.dev/reference/flag-definitions/
+- npm: `@openfeature/server-sdk`, `@openfeature/flagd-core`
+- Go modules: `github.com/open-feature/go-sdk`, `github.com/open-feature/flagd/core`
+
+## Later decisions (spec Q7–Q9)
+
+After this research, the design changed in two places:
+
+1. Only the ERP and the MES read flags. The Go client stays a reference.
+2. The sources (the console and the CSA dashboard) are Node apps. Each one
+ writes its own endpoint. They use the `Flag` type and the validator from
+ `@openfeature/flagd-core`. `setConfigurations` throws on a bad
+ `defaultVariant` or a bad `state` (checked with 5.0.0).
diff --git a/.ai/specs/2026-10-28-feature-flags.md b/.ai/specs/2026-10-28-feature-flags.md
new file mode 100644
index 0000000000..95114ddb18
--- /dev/null
+++ b/.ai/specs/2026-10-28-feature-flags.md
@@ -0,0 +1,717 @@
+# Feature flags for Carbon instances
+
+> Status: draft
+> Author: Sid
+> Date: 2026-10-28
+> Research: `.ai/research/2026-10-28-feature-flags.md`
+
+## TLDR
+
+Each Carbon instance reads its feature flags from one URL. The operator sets
+the URL and the request headers with two environment variables, the same way
+the OTEL exporter is set up. The URL returns a flagd JSON document, the
+OpenFeature standard format. The ERP and the MES evaluate the flags in
+process with `@openfeature/flagd-core`. There is no flagd daemon. Carbon staff
+can turn a flag on for named users, for one company, by percentage, by
+tenancy (single or multi) or by edition. On Carbon Cloud, one process at a
+time fetches the URL, at most once a minute, and every process reads the
+shared copy in Redis. A BYOC
+instance and a Carbon-managed AWS workspace get their flags once, at deploy
+time, so a console outage never changes a running instance. The console and
+the CSA dashboard are two independent sources. Each one keeps its own flag
+data and serves the same contract. Flags control rollouts only. The license
+key and `requireEntitlement` still decide which paid features a company has.
+
+## Overview diagram
+
+```mermaid
+sequenceDiagram
+ participant Staff as Carbon staff
+ participant Src as Console or CSA dashboard
+ participant Cloud as Cloud ERP and MES
+ participant Deploy as BYOC or AWS deploy step
+ participant Fixed as BYOC or AWS ERP and MES
+ Staff->>Src: Edit flag rules per company
+ loop Every 60 s, with jitter
+ Cloud->>Src: GET flags with If-None-Match
+ Src-->>Cloud: 200 flagd JSON or 304
+ end
+ Cloud->>Cloud: Evaluate per company in process
+ Deploy->>Src: GET flags with instance token
+ Src-->>Deploy: 200 flagd JSON
+ Deploy->>Fixed: Set endpoint to a data URL
+ Fixed->>Fixed: Load once at boot, never poll
+```
+
+## Problem Statement
+
+Carbon has no feature flag system. The only flag-like mechanism is
+`INTEGRATION_EARLY_ACCESS_USER_IDS` (`packages/env/src/schema.ts`). It is a
+list of user ids in an environment variable, and it gates one thing: the
+install of a Coming soon integration.
+
+So today:
+
+1. A feature cannot go to one company first and then to all companies without
+ a deploy.
+2. A risky change has no switch that turns it off without a deploy.
+3. A BYOC instance cannot get a feature that Carbon Cloud has, except through a
+ code default.
+4. Each new staged rollout invents its own environment variable.
+
+## Proposed Solution
+
+### 1. Configuration — two environment variables
+
+```bash
+CARBON_FLAGS_ENDPOINT="https://console.carbon.ms/api/flags"
+CARBON_FLAGS_HEADERS="Authorization=Bearer%20<token>,X-Carbon-Instance=<id>"
+```
+
+`CARBON_FLAGS_HEADERS` uses the format of `OTEL_EXPORTER_OTLP_HEADERS`. It is a
+list of `key=value` pairs, separated by commas, with percent-encoded keys and
+values. The parser skips a malformed pair and logs it. It never throws.
+
+| `CARBON_FLAGS_ENDPOINT` value | Used by | Behavior |
+|-------------------------------|---------|----------|
+| `https://…` (console or CSA dashboard) | Carbon Cloud | Load at boot, then poll |
+| `data:application/json;base64,…` | BYOC, Carbon-managed AWS workspaces | Load once at boot. No poll. |
+| Unset | Community self-host, local dev | Code defaults only |
+
+Both variables are server-only. They never go into `getBrowserEnv()`.
+`CARBON_FLAGS_HEADERS` is `secret: true`, because it holds the token.
+
+### 2. The endpoint contract
+
+The console and the CSA dashboard each implement this contract. A stock flagd
+daemon can also read the endpoint, because flagd's own HTTP sync sends the same
+headers (`Authorization`, extra headers, `If-None-Match`).
+
+**Request:** `GET <CARBON_FLAGS_ENDPOINT>` with the configured headers. The
+request also sends `If-None-Match` when the instance has an ETag, and
+`X-Carbon-Commit` with the build's git commit when the instance knows it.
+
+| Header | Set by | Use in the source |
+|--------|--------|-------------------|
+| `Authorization` | `CARBON_FLAGS_HEADERS` | The instance token. It is the only identity. |
+| `X-Carbon-Commit` | `CARBON_COMMIT_SHA` (alias `VERCEL_GIT_COMMIT_SHA`; `sst.config.ts` forwards `IMAGE_TAG`), and `ci/src/deploy.ts` at deploy time | Record the most recent build seen for each instance, next to `lastFetchAt`. Only the process that holds the lease fetches, so during a rolling deploy the value can alternate between the old and the new build. The value is the first 12 characters of the commit on every platform. |
+| `If-None-Match` | The provider | Answer `304` when the document has not changed. |
+
+The headers carry no company id, user id or other tenant data.
+
+| Response | Meaning | Instance action |
+|----------|---------|-----------------|
+| `200` + `ETag` + flagd JSON | New flags | Validate, load, keep the ETag |
+| `304` | No change | Keep the loaded flags |
+| `401` / `403` | Unknown or revoked token | Keep the last good document. Record the error. |
+| `5xx`, timeout, body over 1 MB | Server problem | Keep the last good document. Record the error. |
+
+**Evaluation context.** The instance evaluates every flag with these fields.
+A rule can test any of them.
+
+| Field | Value | Set by |
+|-------|-------|--------|
+| `targetingKey` | `userId`, else `companyId`. A `userIds` 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 |
+
+**Body:** a flagd flag definition document
+(`https://flagd.dev/schema/v0/flags.json`):
+
+```json
+{
+ "$schema": "https://flagd.dev/schema/v0/flags.json",
+ "flags": {
+ "new-mrp-engine": {
+ "state": "ENABLED",
+ "variants": { "on": true, "off": false },
+ "defaultVariant": "off",
+ "targeting": {
+ "if": [
+ { "in": [{ "var": "companyId" }, ["cmp_123", "cmp_456"]] }, "on",
+ { "==": [{ "var": "tenancy" }, "single"] }, "on",
+ {
+ "==": [
+ { "fractional": [
+ { "cat": [{ "var": "$flagd.flagKey" }, { "var": "companyId" }] },
+ ["hit", 10], ["_rest", 90]
+ ] },
+ "hit"
+ ]
+ }, "on",
+ null
+ ]
+ },
+ "metadata": { "archived": false }
+ }
+ }
+}
+```
+
+This example turns the flag on for 2 named companies, for every
+single-tenant instance, and for 10% of the other companies.
+
+Rules for the body:
+
+1. The source sends only the rules for the instance that the token names. A
+ BYOC instance never gets another customer's company ids.
+2. A percentage rollout buckets on the flag key plus `companyId`. So every
+ user of one company gets the same answer.
+3. A `null` at the end of the `if` chain returns `defaultVariant`.
+4. An archived flag carries `"metadata": { "archived": true }`. It keeps its
+ current answer.
+5. The source validates the document with `new FlagdCore().setConfigurations(body)`
+ before it sends it. The source never sends a document that fails validation.
+
+### 3. The instance side — `@carbon/env/flags.server`
+
+A new subpath export of `@carbon/env`. It follows the existing
+`./push.server` subpath. The `.server` suffix keeps it out of the browser
+bundle. The provider reads the two variables through the `@carbon/env`
+exports, never through `process.env` (`packages/env/AGENTS.md`).
+
+| Export | Job |
+|--------|-----|
+| `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`. |
+| `evaluateBrowserFlags(ctx)` | Returns the value of every registry flag with `browser: true`, for the layout loaders. |
+| `parseHeaders(raw)` | The `CARBON_FLAGS_HEADERS` parser. |
+
+`initFlags` goes in `app/entry.server.tsx`, not in `server/app.ts`.
+`entry.server.tsx` already imports `waitUntil` and sets up tracing, and it runs
+in dev and in production. `server/app.ts` is the Vercel wrapper only.
+
+A second, client-safe file, `@carbon/env/flags`, holds the flag registry:
+
+```ts
+export const FLAGS = {
+ "new-mrp-engine": { type: "boolean", default: false, browser: false },
+} as const;
+```
+
+The registry is the one place a flag's code default lives. `flags.bool(key, ctx)`
+reads the default from it, so two call sites cannot use two different
+defaults. A key that is not in the registry is a type error.
+
+**How defaults work.** A flag has 2 defaults:
+
+| Default | Lives in | Answers when |
+|---------|----------|--------------|
+| Registry default | `FLAGS[key].default` in this repo | The instance has no answer from a source |
+| Source default | `defaultVariant` of the flag in the source | The source knows the flag, but no rule matches |
+
+The provider picks the value in this order. `@openfeature/flagd-core` 5.0.0
+returns the reasons in the table (checked in a scratch test).
+
+| Case | Value | flagd reason |
+|------|-------|--------------|
+| A rule matches | The rule's variant | `TARGETING_MATCH` |
+| No rule matches, or the flag has no rules | The source default | `DEFAULT` or `STATIC` |
+| The flag has `state: "DISABLED"` | The registry default | `DISABLED` |
+| The document has no such flag | The registry default | `FLAG_NOT_FOUND` |
+| No document is loaded, or the endpoint is unset | The registry default | — |
+| The flag's value has the wrong type | The registry default | `TYPE_MISMATCH` |
+
+So `DISABLED` is the switch that gives control back to the code. Use it to
+stop a flag without deleting it.
+
+The browser follows the same rules. `useFeatureFlags().feature(key)` returns the
+loader's value, else the registry default.
+
+During a rollout, the two defaults move in this order:
+
+| Step | Registry default | Source default | Rules |
+|------|------------------|----------------|-------|
+| 1. Ship the code | off | — (no flag yet) | — |
+| 2. Create the flag | off | off | `companyIds` = one company |
+| 3. Widen the rollout | off | off | `percent`, then `tenancy` or `editions` |
+| 4. On for every instance that has a source | off | on | removed |
+| 5. Ship the new default | on | on | — |
+| 6. Archive, then remove the code | — | archived | — |
+
+Between step 4 and step 5, an instance with no source still runs the old
+behavior. That covers community self-host, and a BYOC or AWS workspace that
+has not deployed since step 4.
+
+**Three layers.** A flag value comes from process memory. Process memory comes
+from Redis. Redis comes from the source.
+
+| Layer | Holds | Read |
+|-------|-------|------|
+| Process memory | The parsed document, in `FlagdCore` | On every evaluation, about 5 µs, no I/O |
+| Redis | One hash per instance: `body`, `etag`, `fetchedAt` | Every 10 s ± 20% per process, in the background |
+| Source | The rules | At most once every 60 s per instance, by the process that holds the lease |
+
+The Redis key is `flags:<scope>`. `<scope>` is the first 16 hex characters of
+the SHA-256 of `CARBON_FLAGS_ENDPOINT` plus `CARBON_FLAGS_HEADERS`. So the ERP
+and the MES of one instance share one copy. Two instances that share one
+Redis never mix their documents.
+
+**Provider behavior for an `http(s)` endpoint:**
+
+1. At boot, read the hash from Redis and load `body` when it exists. Do not
+ wait for the source.
+2. If Redis has no `body`, fetch the source. Wait at most 2 seconds. If the
+ fetch takes longer, it continues in the background.
+3. On every evaluation, check the time of the last sync. If it is older than
+ 10 seconds ± 20%, start a background sync. Never run two syncs at once.
+4. Pass each background sync to `waitUntil`, so Vercel keeps the function
+ alive until the sync ends.
+5. A sync reads `etag` and `fetchedAt` from Redis. If `etag` differs from the
+ loaded one, it reads `body`, validates it and loads it.
+6. If `fetchedAt` is older than 60 seconds, or this process cannot load the
+ copy in Redis, the sync takes the lease `flags:<scope>:refresh` (10 s). The process with the lease fetches the
+ source with `If-None-Match`. On a `200`, it validates the body and writes
+ `body`, `etag` and `fetchedAt`. On a `304`, it writes `fetchedAt` only.
+7. If another process holds the lease, the sync does nothing more. If the
+ fetch fails, the process keeps the lease until it expires, so a down
+ source gets at most one request per 10 s from all processes.
+8. If Redis is unavailable, the process fetches the source directly, at most
+ once every 60 seconds ± 20%.
+9. On any error, keep the loaded flags, set `lastError`, and log a warning.
+10. When code evaluates a flag with `metadata.archived = true`, log one warning
+ per key per process.
+11. A missing flag, a wrong type, or no loaded document returns the registry
+ default.
+
+A `data:` endpoint loads once at boot. It never reads or writes
+Redis, because its document never changes.
+
+Sync on read, not on a timer, because Vercel pauses the process between
+requests.
+
+**The store.** `@carbon/kv` depends on `@carbon/env`, so `@carbon/env`
+cannot import `@carbon/kv`. So `@carbon/env/flags.server` defines the
+`FlagsStore` interface, and `@carbon/kv` exports `redisFlagsStore`, which
+implements it with the fail-soft `redis` client and `acquireLease`. The app
+passes it to `initFlags`. A test passes an in-memory store.
+
+**What this costs a request.** Measured with 50 flags, each with a 200-company
+rule (a 111 KB document):
+
+| Step | Cost |
+|------|------|
+| One evaluation through the OpenFeature SDK | about 4.5 µs |
+| The layout loader with 10 browser flags | about 45 µs |
+| Parse and validate the document | about 17 ms, only when the `etag` changes |
+| Background sync | 1 `HMGET` every 10 s per process, off the request path |
+| Cold start | 2 reads in parallel (`HMGET` and `HGET`), no wait for the source |
+
+### 4. Flags in the frontend
+
+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`.
+ The MES layout sends no flags until an MES component reads one; until
+ then `useFeatureFlags()` in the MES answers the registry defaults.
+2. The loader returns the values as `flags: Record<string, FlagValue>`.
+3. `@carbon/react` exports `useFeatureFlags()`
+ (`packages/react/src/hooks/useFeatureFlags.tsx`). Its `feature(key)` reads
+ `flags` from the `/x` route data and falls back to the registry default.
+ It follows `usePlan`, which reads the same route in both apps.
+4. Both apps call `useFeatureFlags()` directly. The ERP's `useFlags` does
+ not change: it keeps the edition and environment booleans.
+
+The hook lives in `@carbon/react` because the `no-duplicated-app-file`
+check refuses a hook that both apps copy.
+
+Only evaluated values reach the browser. Rules, company lists and the token
+never do.
+
+A layout loader reruns a GET only after `SHELL_MAX_AGE_MS` (its
+`shouldRevalidate`). So a browser flag can take until the next layout
+revalidation to change. Server flags are up to 60 seconds old on Carbon Cloud
+already, so this is acceptable.
+
+**Patterns for call sites:**
+
+| Need | Pattern |
+|------|---------|
+| A flag decides if a page or its data exists | Check `flags.bool` in the route loader, after `requirePermissions`. Throw `notFound()` when the flag is off. |
+| A flag swaps a UI | One ternary at the highest component that changes: `feature("x") ? <BuilderV2 /> : <Builder />`. Do not pass the flag down as a boolean prop. |
+| The new UI is large | Load the new variant with `lazy(() => import(…))` inside `Suspense`, as `InspectionView` does for its drawing pane. A company without the flag never downloads it. |
+| A flag hides an unreleased paid feature | Check the flag first. When the flag is on, the plan gate applies as before: `usePlanGate` shows the upgrade overlay. |
+
+Do not add a `<FeatureGate>` wrapper component. Do not fetch flags from the
+browser.
+
+### 5. Who reads flags
+
+Only the ERP and the MES read flags in v1. Inngest jobs (`@carbon/jobs`) and
+the Rust assembler do not. So a background job, for example an MRP run, must
+not depend on a flag.
+
+### 6. The sources — console and CSA dashboard
+
+The console (`console.carbon.ms`) and the CSA dashboard are both Node apps,
+outside this repo. Each one is an independent source. An instance points at
+one source only. Each source has its own data and its own implementation of
+section 2. They share no Carbon package.
+
+Only Carbon staff control flags, in the source's admin form. A company never
+sees or changes a flag.
+
+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) |
+| 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" }, [ … ]] }`.
+
+Use `userIds` with `companyIds` in one rule. Then the rule means "these
+people, in this company". A user rule without a company follows the user
+into every company the user belongs to. A percentage always buckets by
+company, never by user, so one company never splits.
+
+Each source uses these standard pieces and writes nothing else to handle the
+format:
+
+1. The `Flag` type from `@openfeature/flagd-core` for the output shape.
+2. `FlagdCore.setConfigurations` to validate the output.
+
+**Flag lifecycle:**
+
+1. Ship the code with the registry default.
+2. Turn the flag on for one company, then by percentage, then for all companies.
+3. Change the registry default to the rolled-out value and ship it.
+4. Archive the flag in the source. It keeps its answer, and any code that
+ still reads it logs a warning.
+5. Remove the code and the registry entry.
+6. Delete the flag in the source. The source refuses a hard delete less than
+ 30 days after the archive.
+
+### 7. BYOC and AWS workspaces — flags are fixed at deploy time
+
+Two deploy steps fetch the flags:
+
+| Deployment | Deploy step | Token and source from |
+|------------|-------------|-----------------------|
+| BYOC | The byoc repo's deploy step | The byoc repo's install config |
+| Carbon-managed AWS workspace (SST) | `ci/src/deploy.ts` | The `workspaces` row: new columns `flags_endpoint` and `flags_token` |
+
+Each deploy step does the same thing:
+
+1. Fetch the flags with the instance token:
+ `curl -fsS -H "Authorization: Bearer $TOKEN" "$SOURCE" -o flags.json`.
+2. Write the result into `CARBON_FLAGS_ENDPOINT` as a
+ `data:application/json;base64,…` URL. `ci/src/deploy.ts` refuses a
+ document over 32 KiB, because AWS limits a whole ECS task definition to
+ 64 KiB.
+3. If the fetch fails, fail the deploy before rollout. The old release keeps
+ running.
+
+For an AWS workspace, `ci/src/deploy.ts` adds `CARBON_FLAGS_ENDPOINT` to the
+environment it passes to `sst deploy`. `sst.config.ts` forwards it to the ERP
+and MES services, next to `SYSTEM_STATUS_URL`. A `workspaces` row without
+`flags_endpoint` deploys with no flags source, so its flags are the code
+defaults.
+
+A flag change reaches these instances only with the next deploy. A running
+instance never calls a source. A restart loads the same data URL, so every
+process of one release has the same flags.
+
+### 8. Flags and licensing
+
+Licensing decides if a company may use a feature. A flag decides if a feature
+that the company may use is on for it yet. The two systems stay separate.
+
+1. A call site checks the entitlement first and the flag second:
+
+ ```ts
+ await requireEntitlement(client, companyId, "WORKFLOWS");
+ if (await flags.bool("workflows-v2-builder", { companyId })) { … }
+ ```
+
+2. A flag can only narrow what the license allows. When the source is down, an
+ entitled company gets the registry default. A company without the
+ entitlement is still refused.
+3. A rule can test `edition`, for example "on for Enterprise instances only".
+ That is rollout targeting, not a grant. The feature stays behind
+ `requireEntitlement`.
+4. The flags token and the license are separate credentials. Revoking one
+ never touches the other.
+
+Both systems survive an outage the same way:
+
+| | Licensing (spec 2026-08-19) | Flags |
+|---|---|---|
+| Online | Check-in every 24 h, 30-day term | Poll every 60 s on Carbon Cloud |
+| Offline | Air-gapped license, 1-year term | `data:` endpoint set at deploy |
+| Source down | Keeps the entitlements until expiry | Keeps the last good document |
+| Request path | Never calls out | Evaluates in process |
+
+### 9. Rules that do not change
+
+1. Flags control rollouts only. A flag never grants or removes a paid feature.
+ `FEATURE_PLANS`, `requireEntitlement` and the license key stay the only
+ entitlement checks.
+2. The registry default is the safe value. An instance with no flags source
+ must work.
+3. A flag never gates an irreversible write or a change of stored data shape
+ on its own. During a source outage, two processes of Carbon Cloud can hold
+ different documents for a short time.
+
+### 10. The v1 flags
+
+A sweep of `main` found 2 features that are half-released behind a stand-in
+gate. They are the first entries of the registry:
+
+```ts
+export const FLAGS = {
+ "multi-company-management": { type: "boolean", default: false, browser: true },
+ "integration-early-access": { type: "boolean", default: false, browser: false },
+} as const;
+```
+
+In both, Carbon staff (`isInternalEmail`) keep their access. The flag adds
+companies to the staff. So with no source, behavior stays as it is today.
+
+**`multi-company-management`** — the Settings → Companies pages.
+
+| Today | With the flag |
+|-------|---------------|
+| The loaders of `x+/settings+/companies.tsx`, `companies.$id.tsx` and `companies.delete.$id.tsx` redirect every user without a Carbon email | They redirect when the user has no Carbon email and the flag is off for the company |
+| `internalOnlyRoutes` in `useSettingsSubmodules.tsx` hides the nav entry from users without a Carbon email | The entry shows when `isInternal` is true or `useFeatureFlags().feature("multi-company-management")` is true |
+
+**`integration-early-access`** — install of an integration with
+`internalOnly: true` on Carbon Cloud. Today only `onshape-v2` has it.
+
+| Today | With the flag |
+|-------|---------------|
+| `hasIntegrationEarlyAccess(userId)` (`packages/ee/src/plan.server.ts`) reads the user ids in `INTEGRATION_EARLY_ACCESS_USER_IDS` | `hasIntegrationEarlyAccess({ companyId, userId })` returns `flags.bool("integration-early-access", { companyId, userId })` |
+| Early access belongs to a user, in every company of that user | Early access belongs to the users of a rule, in the companies of that rule |
+
+1. The flag is one switch for every `internalOnly` integration, as the user
+ list is today. A user also needs access to the Onshape app in Onshape, so
+ each rule names the users (`userIds`) and their company (`companyIds`).
+2. `isIntegrationComingSoon` (`packages/ee/src/plan.ts`) does not change. It
+ still takes `hasEarlyAccess: boolean`.
+3. Its 2 callers pass the new value: `isIntegrationInstallWithheld`
+ (`settings.service.ts`) and the `x+/settings+/integrations.tsx` loader.
+4. Keep `INTEGRATION_EARLY_ACCESS_USER_IDS` as a fallback: `hasIntegrationEarlyAccess` answers true when the user is in the list or the flag is on. Remove the list once a flags source is live and its users have rules.
+
+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`.
+
+**Later flags.** These features are hidden in code until a dependency ships.
+Each one becomes a flag when its rollout starts:
+
+| Feature | Today |
+|---------|-------|
+| Construction in progress for fixed assets | `CONSTRUCTION_IN_PROGRESS_ENABLED = false` (`accounting.models.ts`), "hidden until it returns with projects" |
+| Storage rules for work centers | Filtered out in `StorageRulesGroups.tsx` until their entry point and MES modal ship |
+
+### Existing gates that stay as they are
+
+| Gate | Why it is not a flag |
+|------|----------------------|
+| `useFlags` edition booleans (`isCloud`, `isCommunity`, `isEnterprise`) | They describe the deployment, not a rollout. |
+| `isInternalEmail` checks for staff tools (implementation hub editing, backup restore at onboarding) | They decide who may use a staff tool. That is identity, not a rollout. |
+| Console mode and Timecards "Beta" badges (`settings+/people.tsx`) | Company settings that the customer turns on. |
+| `STRIPE_CONNECT_ENABLED`, `CARBON_SLACK_ENABLED` | They say if an integration is configured. |
+| `MAINTENANCE_MODE` | It must work when no flags source answers. |
+| Templates "Coming soon" (`x+/templates+/_index.tsx`) | Document types that the code does not support yet. |
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Flag format | flagd flag definition JSON | The OpenFeature standard. Node and Go libraries evaluate it the same way. A later move to Unleash or Flagsmith is a provider swap. |
+| Evaluation | In process, `@openfeature/flagd-core` 5.0.0 | No daemon to run. Evaluation needs no network call. |
+| Remote evaluation (OFREP) | Rejected | The server evaluates on every request. A BYOC instance could not run on flags fixed at deploy time. |
+| Configuration | `CARBON_FLAGS_ENDPOINT` + `CARBON_FLAGS_HEADERS` | Same shape as the OTEL exporter, so operators already know it. One instance can point at any source. |
+| Source language and home | A route in the console and in the CSA dashboard, both Node | Answer to Q1 and Q8. Each reuses its own database, instance list and admin auth. |
+| Two sources | Independent data, same contract | Answer to Q8. An instance points at one source. |
+| Shared code for the sources | None. Each source uses the flagd-core type and validator. | Answer to Q9. The contract is the shared part. |
+| 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. |
+| 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. |
+| Package home | `@carbon/env/flags.server` + `@carbon/env/flags` | Answer to Q12. The `.server` suffix follows the repo convention for server-only modules. |
+| Provider setup | `initFlags` in `app/entry.server.tsx` | It already holds `waitUntil` and tracing setup, and it runs in dev and in production. |
+| Shared cache | Redis, through a `FlagsStore` that `@carbon/kv` implements | The user asked for Redis. Every process converges on one document. One process per instance calls the source. `@carbon/kv` depends on `@carbon/env`, so the interface lives in `@carbon/env`. |
+| Cloud refresh | Redis sync on read every 10 s ± 20%; source fetch under a lease when Redis is older than 60 s; all through `waitUntil` | Vercel pauses the process between requests. A cold start never waits for the source when Redis has a copy. |
+| BYOC refresh | Deploy time only, as a `data:` URL | Answer to Q6. A console outage never reaches a running customer instance. |
+| AWS workspace refresh | Deploy time only, from the `workspaces` row in `ci/src/deploy.ts` | Answer to Q11. Same as BYOC. A controlled-environment workspace makes no runtime call. |
+| Deploy fetch failure | The deploy fails | Answer to Q6. The old release keeps running. |
+| Flag delete guard | Archive first. `metadata.archived` makes the instance warn. Hard delete waits 30 days. | Answer to Q5 and Q10. CI needs no console token. |
+| Code defaults | One registry, `FLAGS` | Two call sites cannot disagree on a default. |
+| v1 flags | `multi-company-management`, `integration-early-access` | Answer to Q15 and Q16. Staff keep their access. The early-access env list stays as a fallback until a flags source is live, so no current user loses access at merge. |
+| Direct OpenFeature use | No check. `flags.bool` is the only read API `@carbon/env` exports. | A check guarded an import nobody makes. Add one if code starts to import `@openfeature/*` directly. |
+| Flag types | Booleans only | Every v1 flag is a boolean. Add string or number support with the first flag that needs it. |
+| Endpoint schemes | `https:` and `data:` | Nothing produces a `file:` endpoint: the CI deploy and the planned BYOC step both write `data:`. |
+| H1 Multi-tenancy | No new Carbon tables. Targeting keys on `companyId`, and the typed wrapper requires it. | The flag data lives in the sources, not in Carbon's database. |
+| H2 Service shape | N/A | No service functions. `flags.*` returns a value and never throws. |
+| H3 RLS | N/A | No Carbon tables. Each source protects its tables with its own admin auth. |
+| H4 Permission scoping | N/A in Carbon | The sources restrict the admin form to Carbon staff. |
+| H5 Form pattern | N/A in Carbon | The admin form is in the sources. |
+| H6 Module layout | Two subpath exports in `@carbon/env`, no barrel | Follows `./push.server`. |
+| H7 Backward compatibility | Additive | Both variables are optional. Unset means code defaults, which is today's behavior. |
+| New dependencies | `@openfeature/server-sdk`, `@openfeature/flagd-core` in `@carbon/env` | Both Apache-2.0. Sid approved them in this design. |
+
+## Data Model Changes
+
+No change to Carbon's database. The flag, rule, token and change log tables
+live in each source's own database (section 6).
+
+The CI deploy database gets 2 columns on `workspaces`: `flags_endpoint` (text)
+and `flags_token` (text, secret). Both are nullable.
+
+## API / Service Changes
+
+| File | Change |
+|------|--------|
+| `packages/env/src/schema.ts` | Add `CARBON_FLAGS_ENDPOINT` (type `url`) and `CARBON_FLAGS_HEADERS` (`secret: true`). |
+| `packages/env/src/index.ts` | Export both variables and `CARBON_COMMIT_SHA`. |
+| `packages/env/src/flags.ts` | New. The `FLAGS` registry and its types. Client-safe. |
+| `packages/env/src/flags.server.ts` | New. Provider, `initFlags`, `flags.*`, `evaluateBrowserFlags`, `parseHeaders`. |
+| `packages/env/src/flags.server.test.ts` | New. The tests for the acceptance criteria of the provider. |
+| `packages/env/package.json` | Add the `./flags` and `./flags.server` exports and the two dependencies. |
+| `pnpm-workspace.yaml` | Add the two dependencies to the catalog. |
+| `packages/kv/src/flags-store.ts` | New. `redisFlagsStore`, the Redis `FlagsStore`. Export it from `src/index.ts`. It is glue, so it has no unit test (`.claude/rules/testing.md`); the provider tests cover the store contract with an in-memory store. |
+| `apps/erp/app/entry.server.tsx`, `apps/mes/app/entry.server.tsx` | Call `initFlags` with `redisFlagsStore`, `waitUntil` and `onWarning` (the app's logger, scope `flags`). |
+| `apps/erp/app/routes/x+/_layout.tsx` | Return `flags` from `evaluateBrowserFlags`. |
+| `packages/react/src/hooks/useFeatureFlags.tsx` | New. `useFeatureFlags()` for both apps. `@carbon/env` moves from a dev dependency to a dependency of `@carbon/react`. |
+| `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.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. |
+| `.env.example` | Document both variables, next to `SYSTEM_STATUS_URL`. |
+| `contrib/deploying/simple-docker-caddy/docker-compose.prod.yml` | Pass both variables to the ERP and MES services. |
+| `sst.config.ts` | Forward `CARBON_FLAGS_ENDPOINT`, and `IMAGE_TAG` as `CARBON_COMMIT_SHA`, in the ERP and MES environment blocks. |
+| `ci/src/deploy.ts`, `ci/src/flags.ts`, `ci/src/flags.test.ts` | Read `flags_endpoint` and `flags_token`, fetch and validate the flags (`fetchFlagsDocument`, `assertFlagdDocument`), set `CARBON_FLAGS_ENDPOINT` to a `data:` URL. |
+| `.claude/rules/environment-configuration.md` | Add a flags section next to the maintenance and status section. |
+| `packages/env/AGENTS.md` | Document the flags exports and the lifecycle. |
+| byoc repo deploy step | Fetch the flags and set `CARBON_FLAGS_ENDPOINT` to a `data:` URL. |
+| Console and CSA dashboard | Tables, admin form and endpoint (section 6). |
+| Vercel projects (Carbon Cloud) | Set both variables in the ERP and MES projects. |
+
+The provider sends its warnings to `onWarning` with structured properties.
+The apps log them, and the log lines feed two Axiom monitors on Carbon Cloud:
+
+1. "Feature flags kept after a failed sync" with `ageMs` over 10 minutes.
+2. "Code read an archived feature flag".
+
+## Closest Sibling
+
+The OTEL exporter in `@carbon/logger` (`packages/logger/src/tracing.server.ts`).
+It is an optional, server-only integration. Two environment variables
+configure it: an endpoint and a list of headers. Unset means it does nothing.
+This spec copies that shape.
+
+Deviations:
+
+| Deviation | Why |
+|-----------|-----|
+| A `data:` endpoint is valid | BYOC and AWS workspaces fix their flags at deploy time. |
+| The module lives in `@carbon/env`, not `@carbon/logger` | The user's choice. Flags are configuration. |
+
+For browser flags, the sibling is the existing `useFlags` hook
+(`apps/erp/app/hooks/useFlags.tsx`). This spec adds `feature(key)` to it. The
+values come from the authenticated layout loader, because a flag needs the
+session's `companyId`.
+
+## UI Changes
+
+None in the ERP or the MES. The admin form is in each source (section 6).
+
+## Acceptance Criteria
+
+- [ ] With `CARBON_FLAGS_ENDPOINT` unset, the ERP starts and every `flags.bool` call returns the registry default.
+- [ ] With a source that targets `cmp_123`, `flags.bool("new-mrp-engine", { companyId: "cmp_123" })` returns `true` and the same call for `cmp_999` returns `false`.
+- [ ] With a rule `tenancy = single`, the flag is on for every company when `TENANT_TYPE=single`, and off when `TENANT_TYPE` is unset.
+- [ ] With a rule `editions = [enterprise]`, the flag is on when `CARBON_EDITION=enterprise` and off when it is `cloud`.
+- [ ] A second fetch sends `If-None-Match`. A `304` keeps the loaded flags and updates `confirmedAt`.
+- [ ] `CARBON_FLAGS_HEADERS="Authorization=Bearer%20ab+c%2Cd=,X-Bad=%zz"` sends `Authorization: Bearer ab+c,d=`, skips `X-Bad`, and does not throw.
+- [ ] The provider refuses a response body over 1 MB, and the loaded flags stay.
+- [ ] When the source does not answer, the ERP boot waits at most 2 seconds.
+- [ ] When the source is down at cold start, a process loads the document from Redis and does not wait for the source.
+- [ ] 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 `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.
+- [ ] Evaluating a flag with `metadata.archived = true` logs one warning per key per process.
+- [ ] A component that calls `useFeatureFlags().feature("x")` for a browser flag gets the value for the session's company. The page source contains no rules and no company ids other than the session's own.
+- [ ] A user without a Carbon email opens `/x/settings/companies` while `multi-company-management` is off for the company. The loader redirects to Settings. With the flag on for the company, the page loads and the Companies entry shows in Settings.
+- [ ] A user with a Carbon email opens `/x/settings/companies` with the flag off, and the page loads as it does today.
+- [ ] On Carbon Cloud, a user without a Carbon email sees Onshape V2 as "Coming soon" while `integration-early-access` is off for the company. With the flag on, the user can install it.
+- [ ] A user listed in `INTEGRATION_EARLY_ACCESS_USER_IDS` can still install Onshape V2 with no flags source, and `pnpm --filter @carbon/ee test` passes.
+- [ ] Instance B's response from a source contains no rule scoped to instance A.
+- [ ] A source refuses to send a document that `FlagdCore.setConfigurations` rejects.
+- [ ] `pnpm exec turbo run typecheck --filter=@carbon/env`, `--filter=erp` and `--filter=mes` pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Two processes hold different documents for a short time | Low | Every process syncs from Redis every 10 s ± 20%. Rule 9.3: no flag gates an irreversible write alone. |
+| Redis is down | Low | Each process fetches the source directly, once a minute, and keeps its loaded document. |
+| A revoked or wrong token keeps an instance on old flags without anyone noticing | Med | The `onWarning` log line (`ageMs`) and the 10-minute age monitor. The source records `lastFetchAt` per instance. |
+| The console and the CSA dashboard compile rules differently | Med | Both validate with `FlagdCore`. Both run the acceptance criteria for the contract. |
+| A flag turns into a permanent configuration switch | Low | The lifecycle in section 6. The archive warning shows code that still reads an old flag. |
+| A browser flag leaks targeting data | Low | Only evaluated values reach the browser. An acceptance criterion checks the page source. |
+| A flag check leaks into jobs, where no provider runs | Low | The provider is set up only in the ERP and MES entries. In jobs, `flags.*` returns the registry default. |
+| A new subpath export of `@carbon/env` answers 500 in dev | Low | `.ai/lessons.md`: restart every running dev server after the exports change. |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Q1. Where does the flags server live? — **Answer:** A route inside the console. Later answer: the console is a Node app, not Go.
+- [x] Q2. How does an instance prove who it is? — **Answer:** A new flags token per instance. The source stores its SHA-256 hash.
+- [x] Q3. How are flags created and changed in v1? — **Answer:** An admin form in the source, with a change log.
+- [x] Q4. Do React components need flags in v1? — **Answer:** Yes. The layout loader evaluates browser flags. Later answer: the existing `useFlags` hook reads them through `feature(key)`.
+- [x] Q5. How do we stop a flag being deleted while code still reads it? — **Answer:** Archive first. No hard delete until 30 days after the archive.
+- [x] Q6. Which step fetches the flags for BYOC? — **Answer:** The byoc deploy step. It writes a `data:` URL. If the fetch fails, the deploy fails.
+- [x] Q7. Which runtimes read flags in v1? — **Answer:** Only the ERP and the MES.
+- [x] Q8. Do the console and the CSA dashboard each hold their own data? — **Answer:** Yes. Both are Node apps and independent sources.
+- [x] Q9. Where does the shared code for the sources live? — **Answer:** Nowhere. Each source writes its own implementation with the standard flagd-core type and validator.
+- [x] Q10. How does code find out that it reads an archived flag? — **Answer:** The document marks the flag with `metadata.archived`. The instance logs a warning, and an Axiom monitor alerts on it.
+- [x] Q11. How do the AWS workspaces that `ci/src/deploy.ts` deploys get their flags? — **Answer:** At deploy time, from the token and source on their `workspaces` row.
+- [x] Q12. Does the provider live in `@carbon/lib`, next to the system status reader? — **Answer:** No. It stays in `@carbon/env` and has no link to `SYSTEM_STATUS_URL`.
+- [x] Q13. Who switches a flag on for one company? — **Answer:** Carbon staff only, with a rule in the source.
+- [x] Q14. How does single tenant or multi tenant change a flag? — **Answer:** The instance sends `tenancy` and `edition` in the evaluation context, and a rule can test them.
+- [x] Q15. Which flags does v1 ship with? — **Answer:** `multi-company-management` and `integration-early-access`. Construction in progress and work-center storage rules become flags later.
+- [x] Q16. Does integration early access target users or companies? — **Answer:** First answer: companies. Later answer, after Raul's input: both. Each Onshape user also needs access in Onshape, so rules get a `userIds` condition, used with `companyIds`. `INTEGRATION_EARLY_ACCESS_USER_IDS` goes away.
+- [x] Q17. Where does the provider cache the document? — **Answer:** In Redis, as much as possible, to keep things fast. Every process reads the shared copy, and one process at a time calls the source.
+
+## Changelog
+
+- 2026-10-28: Created. All 10 questions answered by Sid before writing.
+- 2026-10-28: Codebase sweep. Added Q11–Q14: AWS workspaces, package home, company control, and tenancy and edition in the context. Moved `initFlags` to `entry.server.tsx`. Replaced the `useFlag` hook with `useFlags().feature(key)`. Added the frontend patterns, the licensing section, the list of gates that stay, the checks rule and the deploy files.
+- 2026-10-28: Added "How defaults work" (section 3). It covers the 2 defaults, the order of evaluation and how both defaults move during a rollout.
+- 2026-10-28: Added section 10, the v1 flags (Q15, Q16): `multi-company-management` and `integration-early-access`, which replaces `INTEGRATION_EARLY_ACCESS_USER_IDS`.
+- 2026-10-28: Added `userIds` rules (Q16 revised) and the Redis-backed store (Q17): three layers, a lease for the source fetch, and the measured cost per request.
+- 2026-10-28: Built on `feat/feature-flags`. Changes from the build: the browser hook moved to `@carbon/react` (`useFeatureFlags`), the Redis store has no unit test, and the AWS `data:` URL has a 32 KiB cap.
+- 2026-10-28: Review fixes. The provider keeps the lease after a failed fetch, fetches for itself when it cannot load the Redis copy, sends structured warnings to `onWarning`, and keeps the boot sync alive with `waitUntil`. The MES layout sends no flags. `ci/src/deploy.ts` checks the document's shape.
+- 2026-10-28: Added the `X-Carbon-Commit` header from `CARBON_COMMIT_SHA` (alias `VERCEL_GIT_COMMIT_SHA`; `IMAGE_TAG` on AWS), so each source records which build every instance runs.
+- 2026-10-29: Review fixes. A process that rejects the Redis copy keeps its fetch in memory. The Redis hash expires after 1 day without a write. `X-Carbon-Commit` is 12 characters everywhere. `flagStatus()` is gone; monitoring reads the `onWarning` log lines. `lastCommit` means the most recent commit seen.
+- 2026-10-29: Simplified. Flags are booleans only (`flags.bool`). No `file:` endpoints. No `flags-through-env` check. Both apps read browser flags with `useFeatureFlags()`, and the ERP's `useFlags` is unchanged.
+- 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:.
diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.md
index 93b8c3cb04..7a39264cae 100644
--- a/.claude/rules/environment-configuration.md
+++ b/.claude/rules/environment-configuration.md
@@ -166,7 +166,7 @@ vars through `ci/src/deploy.ts` → `sst.config.ts` → the ERP service only.
**Analytics / config** — `POSTHOG_API_HOST`, `POSTHOG_PROJECT_PUBLIC_KEY`
(optional, public), `CARBON_EDITION` (`community|cloud|enterprise|test` →
-`CarbonEdition`), `CONTROLLED_ENVIRONMENT` (ITAR flag), `INTEGRATION_EARLY_ACCESS_USER_IDS` (server-only, comma-separated user ids that can install an `internalOnly` integration on Cloud), `DEFAULT_LANGUAGE`
+`CarbonEdition`), `CONTROLLED_ENVIRONMENT` (ITAR flag), `INTEGRATION_EARLY_ACCESS_USER_IDS` (server-only, comma-separated user ids that can install an `internalOnly` integration on Cloud; a fallback beside the `integration-early-access` flag until a flags source is live), `DEFAULT_LANGUAGE`
(default `en`), `GTM_URL`, `GTM_EVENTS_API_SECRET_KEY`.
**Maintenance and status (both optional, server-only)** — `MAINTENANCE_MODE=true`
@@ -187,6 +187,22 @@ shown — Carbon has no version to compare it with. Neither variable is on the
`workspaces` row, so `ci/src/deploy.ts` does not set them; `sst.config.ts`
forwards them from the deploying process's environment.
+**Feature flags (both optional, server-only)** — `CARBON_FLAGS_ENDPOINT` is a
+flagd JSON document (`@carbon/env/flags.server`, spec
+`.ai/specs/2026-10-28-feature-flags.md`); `CARBON_FLAGS_HEADERS` holds its
+request headers in the `OTEL_EXPORTER_OTLP_HEADERS` format (`secret: true`, it
+carries the token). An `https:` endpoint is the Carbon Cloud source: each ERP
+and MES process reads the shared copy in Redis (`redisFlagsStore`, `@carbon/kv`,
+hash `flags:<scope>`) every 10 s and, when that copy is older than 60 s, one
+process fetches the source under a lease. A `data:` endpoint loads
+once: `ci/src/deploy.ts` fetches each AWS workspace's document at deploy time
+(`workspaces.flags_endpoint` / `flags_token`, 32 KiB cap for the task
+definition) and passes it as a `data:` URL, and `sst.config.ts` forwards it.
+Unset means every flag answers its registry default (`packages/env/src/flags.ts`).
+Read flags only with `flags.*` / `evaluateBrowserFlags` and, in React,
+`useFeatureFlags().feature(key)` (`@carbon/react`), never with an
+OpenFeature client.
+
**Tracing (all optional)** — the standard OpenTelemetry variables, read raw by
the OTel SDK (not `@carbon/env`): `OTEL_EXPORTER_OTLP_ENDPOINT` (or
`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) turns server tracing on,
diff --git a/.claude/rules/onshape-panel.md b/.claude/rules/onshape-panel.md
index 3cc96c004d..9cb9f7be87 100644
--- a/.claude/rules/onshape-panel.md
+++ b/.claude/rules/onshape-panel.md
@@ -20,7 +20,7 @@ A Carbon panel in Onshape's element right panel. Users push parts, assemblies an
- `ONSHAPE_INTEGRATION_IDS`, `OnshapeIntegrationId`, `isOnshapeIntegrationId` and `getConflictingOnshapeIntegration` (`lib/connection.ts`) cover the two sync connections only. `OnshapeOAuthIntegrationId` covers all three.
- Status, releases and the three plan routes read the connection with the service role. The `companyIntegration` SELECT policy needs settings view; through a parts-view user's client the row reads as absent and the panel says Onshape is not connected. The Fields route uses the user's client: it requires settings update anyway.
- Only an `onshape-v2` item link means "the panel pushes to this item". A sync connection's item row is BOM-import bookkeeping for the BoM Explorer; the item card and Detach never read or delete it.
-- OAuth: the sync integration and the panel are two Onshape apps and share no variable. `onshape` reads `ONSHAPE_CLIENT_ID`, `ONSHAPE_CLIENT_SECRET`, `ONSHAPE_OAUTH_REDIRECT_URL` (→ `/api/integrations/onshape/oauth`); `onshape-v2` reads `ONSHAPE_V2_CLIENT_ID`, `ONSHAPE_V2_CLIENT_SECRET`, `ONSHAPE_V2_OAUTH_REDIRECT_URL` (→ `/api/integrations/onshape-v2/oauth`). Both ask for `OAuth2Read OAuth2Write`. Each card is `active` only when its own client id is set (`config.tsx`, `config-v2.tsx`); otherwise it reads Not Configured, Install is disabled and an installed connection's Details link goes nowhere; the env schema groups them as `onshape` and `onshapeV2`. `onshape-v2` is also `internalOnly`: on Carbon Cloud only Carbon staff and the users listed in `INTEGRATION_EARLY_ACCESS_USER_IDS` can install it, in any company they belong to, and everyone else sees Coming soon (`isIntegrationComingSoon`, `@carbon/ee/plan`; `hasIntegrationEarlyAccess`, `@carbon/ee/plan.server`). The install route refuses them with `coming-soon` (`isIntegrationInstallWithheld`, `modules/settings/settings.service.ts`); a company that has it installed keeps it. Install routes call `beginOnshapeAuthorization`; callbacks call `completeOnshapeAuthorization` (`modules/settings/settings.service.ts`); `getOnshapeOAuthConfig` picks the client and redirect per id and answers `not-configured` when one of that integration's three variables is missing. A connection's tokens belong to the app that issued them: changing an integration's client id means reconnecting. State is the cookie-bound one from `@carbon/auth/oauth-state.server`.
+- OAuth: the sync integration and the panel are two Onshape apps and share no variable. `onshape` reads `ONSHAPE_CLIENT_ID`, `ONSHAPE_CLIENT_SECRET`, `ONSHAPE_OAUTH_REDIRECT_URL` (→ `/api/integrations/onshape/oauth`); `onshape-v2` reads `ONSHAPE_V2_CLIENT_ID`, `ONSHAPE_V2_CLIENT_SECRET`, `ONSHAPE_V2_OAUTH_REDIRECT_URL` (→ `/api/integrations/onshape-v2/oauth`). Both ask for `OAuth2Read OAuth2Write`. Each card is `active` only when its own client id is set (`config.tsx`, `config-v2.tsx`); otherwise it reads Not Configured, Install is disabled and an installed connection's Details link goes nowhere; the env schema groups them as `onshape` and `onshapeV2`. `onshape-v2` is also `internalOnly`: on Carbon Cloud only Carbon staff (in any company) and the users the `integration-early-access` feature flag is on for (in the companies its rules name), or listed in `INTEGRATION_EARLY_ACCESS_USER_IDS` until a flags source is live, can install it, and everyone else sees Coming soon (`isIntegrationComingSoon`, `@carbon/ee/plan`; `hasIntegrationEarlyAccess`, `@carbon/ee/plan.server`). The install route refuses them with `coming-soon` (`isIntegrationInstallWithheld`, `modules/settings/settings.service.ts`); a company that has it installed keeps it. Install routes call `beginOnshapeAuthorization`; callbacks call `completeOnshapeAuthorization` (`modules/settings/settings.service.ts`); `getOnshapeOAuthConfig` picks the client and redirect per id and answers `not-configured` when one of that integration's three variables is missing. A connection's tokens belong to the app that issued them: changing an integration's client id means reconnecting. State is the cookie-bound one from `@carbon/auth/oauth-state.server`.
- Connect opens a popup (`beginOAuthPopup`, `packages/ee/src/oauth-popup.ts`, opened inside the click). The callback renders `oauthPopupResponse`: it posts the outcome to the opener and closes, or lands on the integrations page with no opener. The drawer's Reconnect action POSTs to the install route and follows `{ redirectUrl }`.
- Uninstall only sets `active = false` and keeps the tokens, so `getOnshapeClient` reads the `onshape-v2` row only while it is active: after an uninstall every panel read answers "not connected". A plan already stored can still be applied until it expires (15 min); APPLY makes no Onshape call.
- `onshapeHealthcheck` (`hooks.server.ts`) builds the client (refreshing an expired token) and reads `/companies`; a revoked grant reads unhealthy.
diff --git a/.env.example b/.env.example
index c5cd041a79..8ad94d57f9 100644
--- a/.env.example
+++ b/.env.example
@@ -13,6 +13,10 @@ SESSION_SECRET="************************"
RATE_LIMIT="5"
# MAINTENANCE_MODE="true" # every request except /health answers 503 with a maintenance screen; needs a restart
# SYSTEM_STATUS_URL="https://example.com/status.json" # optional; { latestVersion?, announcement? } shown as a bar in the app
+# Feature flags — optional; unset means every flag answers its registry default (packages/env/src/flags.ts).
+# CARBON_FLAGS_ENDPOINT="https://console.carbon.ms/api/flags" # https: polls; data: loads once
+# CARBON_FLAGS_HEADERS="Authorization=Bearer%20<token>" # k=v pairs separated by commas, percent-encoded (the OTEL headers format)
+# CARBON_COMMIT_SHA="<git sha>" # optional; sent to the flags source as X-Carbon-Commit (Vercel sets it automatically)
# LOG_LEVEL="debug" # trace|debug|info|warning|error|fatal — optional; default dev=debug, prod=info, browser prod=warning
# Server tracing (OpenTelemetry) — optional; off unless an OTLP endpoint is set. Any OTLP backend works; Axiom shown.
# OTEL_EXPORTER_OTLP_ENDPOINT="https://api.axiom.co"
diff --git a/apps/erp/app/entry.server.tsx b/apps/erp/app/entry.server.tsx
index 75396ddf89..a80fedc8f5 100644
--- a/apps/erp/app/entry.server.tsx
+++ b/apps/erp/app/entry.server.tsx
@@ -9,6 +9,8 @@ import {
setStrictContentSecurityPolicy
} from "@carbon/auth/middleware/security.server";
import { getProcessPool } from "@carbon/database/client";
+import { initFlags } from "@carbon/env/flags.server";
+import { redisFlagsStore } from "@carbon/kv";
import { inngest } from "@carbon/lib/inngest";
import { getLogger } from "@carbon/logger";
import { ensureLoggingConfigured } from "@carbon/logger/config.server";
@@ -45,6 +47,17 @@ export const instrumentations = createTracing({
});
scheduleInngestSelfSync();
+// Feature flags: every process reads the shared copy in Redis and syncs it in
+// the background. Until the first document loads, each flag answers its
+// registry default.
+const flagsLog = getLogger("erp", "flags");
+void initFlags({
+ store: redisFlagsStore,
+ waitUntil: process.env.VERCEL ? waitUntil : undefined,
+ // Structured, so Axiom can alert on stale flags (`ageMs`) and archived reads.
+ onWarning: (message, properties) => flagsLog.warn(message, properties)
+});
+
const log = getLogger("erp");
// Process-level safety net: errors that escape the request lifecycle entirely
diff --git a/apps/erp/app/modules/settings/AGENTS.md b/apps/erp/app/modules/settings/AGENTS.md
index 44b79d182e..f9eb5c6a6c 100644
--- a/apps/erp/app/modules/settings/AGENTS.md
+++ b/apps/erp/app/modules/settings/AGENTS.md
@@ -79,7 +79,7 @@ A settings page has ONE update operation, `update<Page>Settings` (`updateAccount
| `updatePeopleSettings` | `people.tsx` | Console mode through `@carbon/ee/console.server` (the plan lock); returns a generated PIN once, never to a key caller. Not published |
| `updateSecuritySettings` | `security.tsx` | Requiring two-factor through `@carbon/ee/two-factor.server`; emails the company on off → on, never in a controlled environment |
| `updatePlanningSettings` | `planning.tsx` | Every employee named must be the company's; a location hidden by RLS is refused |
-| `updateCompanyDetails` / `createCompany`, `updateSubsidiaryDetails` / `createSubsidiary` | `company.tsx`, `company.new.tsx`, `companies.$id.tsx`, `companies.new.tsx` | A base-currency change deletes the exchange-rate overrides in one transaction; the time-zone cache is dropped; a new company is seeded with its Headquarters and the caller's job; group companies are for internal users only and the parent must be in the caller's group. Only `updateCompanyDetails` is published |
+| `updateCompanyDetails` / `createCompany`, `updateSubsidiaryDetails` / `createSubsidiary` | `company.tsx`, `company.new.tsx`, `companies.$id.tsx`, `companies.new.tsx` | A base-currency change deletes the exchange-rate overrides in one transaction; the time-zone cache is dropped; a new company is seeded with its Headquarters and the caller's job; group companies are open to Carbon staff and to companies with the `multi-company-management` flag (`refuseUnlessCanManageCompanies`); a subsidiary needs a parent in the caller's group, and an update checks the company and its new parent are in that group and clears exchange-rate overrides on a base-currency change. Only `updateCompanyDetails` is published |
| `savePrinterRoute` / `testPrinterRoute` / `removePrinterRoute`, `assignPrinter`, `reprintPrintJob` / `deletePrintJob` / `viewPrintJobContent` | `printing.tsx`, `printing.$id.delete.tsx`, `printing.jobs.tsx` | Deleting a route clears every assignment that named it; each write drops the printer cache. `savePrinterRoute`, `testPrinterRoute`, `reprintPrintJob` and `viewPrintJobContent` are not published: the first three make the server POST to a URL the caller gives |
| `saveDocumentTemplate`, `saveDocumentSection` / `removeDocumentSection` | `x+/templates+/$type.tsx`, `x+/templates+/shared.tsx` | The header layout is saved onto its section first |
| `createApiKey` / `updateApiKey` / `revokeApiKey` | `api-keys.new.tsx`, `api-keys.$id.tsx`, `api-keys.delete.$id.tsx` | Key generation and hashing, the auth-cache busts; the plan lock stays in `@carbon/ee/api-keys.server`. Not published |
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index 7b90760c9b..19cf94875c 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -1032,7 +1032,8 @@ export const createCompany = defineServiceFn({
* Create a company in the caller's company group.
*
* @remarks
- * Open to internal users only, for now. The parent must be a company of the
+ * Open to Carbon staff, and to the companies the `multi-company-management`
+ * flag turns it on for. A parent is required, and it must be a company of the
* caller's own group: seeding joins the new company to its parent's group,
* so a parent from another group would place it inside another tenant. Then
* as for a new company: insert, seed, the Headquarters location and the
@@ -1042,22 +1043,25 @@ export const createSubsidiary = defineServiceFn({
input: subsidiaryValidator,
permission: { create: "settings" },
async run(ctx, subsidiary) {
- const refused = await service.refuseUnlessInternalUser(ctx);
+ const refused = await service.refuseUnlessCanManageCompanies(ctx);
if (refused) return refused;
const { id: _, parentCompanyId, ...company } = subsidiary;
const client = ctx.asSystem.supabase;
- if (parentCompanyId) {
- const parent = await client
- .from("company")
- .select("id")
- .eq("id", parentCompanyId)
- .eq("companyGroupId", ctx.company.groupId)
- .maybeSingle();
- if (parent.error || !parent.data) {
- return ctx.error("notFound", "Parent company not found", parent.error);
- }
+ // Without a parent, seeding would start a new company group: that is
+ // creating a company, not a subsidiary, and has its own permissions.
+ if (!parentCompanyId) {
+ return ctx.error("validation", "A subsidiary needs a parent company");
+ }
+ const parent = await client
+ .from("company")
+ .select("id")
+ .eq("id", parentCompanyId)
+ .eq("companyGroupId", ctx.company.groupId)
+ .maybeSingle();
+ if (parent.error || !parent.data) {
+ return ctx.error("notFound", "Parent company not found", parent.error);
}
const inserted = await service.insertCompany(client, company);
@@ -1090,22 +1094,68 @@ export const createSubsidiary = defineServiceFn({
* Update a company of the caller's company group.
*
* @remarks
- * Open to internal users only, for now. Writes the company's details and its
- * parent, then drops its cached time zone.
+ * Open to Carbon staff, and to the companies the `multi-company-management`
+ * flag turns it on for. The company and its new parent must both be in the
+ * caller's group. Writes the company's details and its parent, then drops its
+ * cached time zone. A base-currency change also clears the company's
+ * exchange-rate overrides in the same transaction, as `updateCompanyDetails`
+ * does: they are denominated in the old base.
*/
export const updateSubsidiaryDetails = defineServiceFn({
input: subsidiaryValidator.safeExtend({ id: z.string() }),
permission: { update: "settings" },
async run(ctx, { id, ...subsidiary }) {
- const refused = await service.refuseUnlessInternalUser(ctx);
+ const refused = await service.refuseUnlessCanManageCompanies(ctx);
if (refused) return refused;
- const result = await service.updateSubsidiary(ctx.asCaller.supabase, id, {
- ...subsidiary,
- updatedBy: ctx.auditUserId
- });
- if (result.error) {
- return ctx.error("internal", "Failed to update subsidiary", result.error);
+ const client = ctx.asSystem.supabase;
+ const current = await client
+ .from("company")
+ .select("baseCurrencyCode")
+ .eq("id", id)
+ .eq("companyGroupId", ctx.company.groupId)
+ .maybeSingle();
+ if (current.error || !current.data) {
+ return ctx.error("notFound", "Company not found", current.error);
+ }
+ if (subsidiary.parentCompanyId) {
+ const parent = await client
+ .from("company")
+ .select("id")
+ .eq("id", subsidiary.parentCompanyId)
+ .eq("companyGroupId", ctx.company.groupId)
+ .maybeSingle();
+ if (parent.error || !parent.data) {
+ return ctx.error("notFound", "Parent company not found", parent.error);
+ }
+ }
+
+ if (
+ subsidiary.baseCurrencyCode &&
+ subsidiary.baseCurrencyCode !== current.data.baseCurrencyCode
+ ) {
+ try {
+ await service.updateCompanyWithBaseCurrencyChange(
+ ctx.asSystem.pg,
+ id,
+ { ...subsidiary, updatedBy: ctx.auditUserId },
+ Object.keys(subsidiaryValidator.shape).filter((key) => key !== "id")
+ );
+ } catch (error) {
+ return ctx.error("internal", "Failed to update subsidiary", error);
+ }
+ } else {
+ const result = await service.updateSubsidiary(ctx.asCaller.supabase, id, {
+ ...subsidiary,
+ updatedBy: ctx.auditUserId
+ });
+ if (result.error) {
+ return ctx.error(
+ "internal",
+ "Failed to update subsidiary",
+ result.error
+ );
+ }
}
await invalidateCompanyTimeZone(id);
return { id };
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 5c0f92f8a9..75e7181f09 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -207,6 +207,7 @@ import {
} from "@carbon/ee/plan.server";
import { patchRampSettings } from "@carbon/ee/ramp.server";
import { resolveCapabilities } from "@carbon/ee/sync";
+import { flags } from "@carbon/env/flags.server";
import { trigger } from "@carbon/jobs";
import {
compatibilityStatus,
@@ -669,7 +670,7 @@ export async function isIntegrationInstallWithheld(
!isIntegrationComingSoon(integration, {
edition: CarbonEdition,
email,
- hasEarlyAccess: hasIntegrationEarlyAccess(userId)
+ hasEarlyAccess: await hasIntegrationEarlyAccess({ companyId, userId })
})
) {
return false;
@@ -1260,17 +1261,19 @@ export async function updateCompany(
export async function updateCompanyWithBaseCurrencyChange(
db: Kysely<KyselyDatabase>,
companyId: string,
- company: Partial<z.infer<typeof companyValidator>> & {
+ company: Partial<z.infer<typeof subsidiaryValidator>> & {
updatedBy: string;
- }
+ },
+ // The subsidiary update also writes `parentCompanyId`.
+ allowedFields: readonly string[] = Object.keys(companyValidator.shape)
) {
// An explicit allow-list of the company form's fields, never the caller's
// object: Kysely bypasses RLS and the API passes `company` through with
// whatever keys were sent, so a spread would reach any column of the row.
- const allowed = new Set<string>(Object.keys(companyValidator.shape));
+ const allowed = new Set<string>(allowedFields);
const fields = Object.fromEntries(
Object.entries(sanitize(company)).filter(([key]) => allowed.has(key))
- ) as Partial<z.infer<typeof companyValidator>>;
+ ) as Partial<z.infer<typeof subsidiaryValidator>>;
return db.transaction().execute(async (trx) => {
await trx
@@ -3397,8 +3400,8 @@ export async function saveCompanySettings(
return error ? ctx.error("internal", failure, error) : null;
}
-/** Multi-company management is open to internal (Carbon) users only, for now. */
-export async function refuseUnlessInternalUser(
+/** Multi-company management: Carbon staff, and the companies the `multi-company-management` flag turns it on for. */
+export async function refuseUnlessCanManageCompanies(
ctx: ServiceContext
): Promise<CarbonError | null> {
const refused = ctx.error(
@@ -3411,7 +3414,14 @@ export async function refuseUnlessInternalUser(
.select("email")
.eq("id", ctx.actor.userId)
.maybeSingle();
- return isInternalEmail(data?.email ?? "") ? null : refused;
+ if (isInternalEmail(data?.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;
}
/** The headquarters location and the creator's job at it: what a new company starts with. */
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 3f75bd10c1..26cf9660aa 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -2,6 +2,7 @@
// 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 { useFeatureFlags } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { useMemo } from "react";
import {
@@ -38,13 +39,13 @@ import { usePlanGate } from "~/hooks/usePlanGate";
import type { AuthenticatedRouteGroup, Role } from "~/types";
import { path } from "~/utils/path";
-const internalOnlyRoutes = new Set<string>([path.to.companies]);
-
export default function useSettingsSubmodules() {
const { t } = useLingui();
const permissions = usePermissions();
const { isCloud, isControlledEnvironment, isInternal, isLocalDev } =
useFlags();
+ const { feature } = useFeatureFlags();
+ const canManageCompanies = isInternal || feature("multi-company-management");
// Enterprise: backups are a Business plan feature, but internal staff and
// local dev keep access (mirrors the server `canManageBackups`).
const { isGated: backupsGated } = usePlanGate({ feature: "BACKUPS" });
@@ -263,7 +264,7 @@ export default function useSettingsSubmodules() {
if (route.requiresCloudEnvironment && !isCloud) return false;
if (route.requiresControlledEnvironment && !isControlledEnvironment)
return false;
- if (!isInternal && internalOnlyRoutes.has(route.to)) return false;
+ if (route.to === path.to.companies && !canManageCompanies) return false;
// Backups: visible to Business/Enterprise, internal staff, or local dev.
if (
route.to === path.to.backups &&
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 0a47ad4a2a..54cd0009d6 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -25,6 +25,7 @@ import { withEmailDelivery } from "@carbon/ee";
import { isApprovalRequired } from "@carbon/ee/approvals.server";
import { isAuditLogEnabled } from "@carbon/ee/audit.server";
import { getPlan } from "@carbon/ee/plan.server";
+import { evaluateBrowserFlags } from "@carbon/env/flags.server";
import { getVapidDetails } from "@carbon/env/push.server";
import { SERVER_MAIL_CONFIGURED } from "@carbon/lib/email.server";
import { getLogger } from "@carbon/logger";
@@ -346,6 +347,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
auditLogEnabled,
company,
companies: companies.data ?? [],
+ // Feature flags with `browser: true`, read with `useFeatureFlags().feature(key)`.
+ flags: await evaluateBrowserFlags({ companyId, userId }),
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.tsx
index b65500691b..2c78191104 100644
--- a/apps/erp/app/routes/x+/settings+/companies.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.$id.tsx
@@ -6,6 +6,7 @@ import { carbon, respond } from "@carbon/api/carbon.server";
import { error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { flags } from "@carbon/env/flags.server";
import { validator } from "@carbon/form";
import { isInternalEmail, redirect } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -16,12 +17,19 @@ import { CompanyForm } from "~/modules/settings/ui";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, email } = await requirePermissions(request, {
- view: "settings"
- });
+ const { client, companyId, email, userId } = await requirePermissions(
+ request,
+ {
+ view: "settings"
+ }
+ );
- // Multi-company management is gated to internal (Carbon) users for now.
- if (!isInternalEmail(email)) {
+ // 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 }))
+ ) {
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.tsx
index 807fb9da7b..ed66161598 100644
--- a/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.delete.$id.tsx
@@ -6,6 +6,7 @@ import { error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { flags } from "@carbon/env/flags.server";
import { getLogger } from "@carbon/logger";
import { isInternalEmail, redirect } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -20,12 +21,19 @@ import { path } from "~/utils/path";
const logger = getLogger("erp", "settings-companies-delete");
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, email } = await requirePermissions(request, {
- view: "settings"
- });
+ const { client, companyId, email, userId } = await requirePermissions(
+ request,
+ {
+ view: "settings"
+ }
+ );
- // Multi-company management is gated to internal (Carbon) users for now.
- if (!isInternalEmail(email)) {
+ // 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 }))
+ ) {
throw redirect(path.to.settings);
}
@@ -44,12 +52,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export async function action({ request, params }: ActionFunctionArgs) {
- const { companyGroupId, email } = await requirePermissions(request, {
- delete: "settings"
- });
+ const { companyGroupId, companyId, email, userId } = await requirePermissions(
+ request,
+ {
+ delete: "settings"
+ }
+ );
- // Multi-company management is gated to internal (Carbon) users for now.
- if (!isInternalEmail(email)) {
+ // 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 }))
+ ) {
throw redirect(path.to.settings);
}
diff --git a/apps/erp/app/routes/x+/settings+/companies.tsx b/apps/erp/app/routes/x+/settings+/companies.tsx
index 24622de092..ce24ad3321 100644
--- a/apps/erp/app/routes/x+/settings+/companies.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.tsx
@@ -6,6 +6,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { flags } from "@carbon/env/flags.server";
import {
HStack,
RecordOutlet,
@@ -36,12 +37,19 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { companyGroupId, email } = await requirePermissions(request, {
- view: "settings"
- });
+ const { companyGroupId, companyId, email, userId } = await requirePermissions(
+ request,
+ {
+ view: "settings"
+ }
+ );
- // Multi-company management is gated to internal (Carbon) users for now.
- if (!isInternalEmail(email)) {
+ // 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 }))
+ ) {
throw redirect(path.to.settings);
}
diff --git a/apps/erp/app/routes/x+/settings+/integrations.tsx b/apps/erp/app/routes/x+/settings+/integrations.tsx
index 3f6392a038..948e4bfe2e 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.tsx
@@ -78,8 +78,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
return data({
integrations: items,
activeRoles,
- // Decided here so the early access list never reaches the browser.
- hasEarlyAccess: hasIntegrationEarlyAccess(userId)
+ // Decided here so the flag's rules never reach the browser.
+ 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 this
diff --git a/apps/mes/app/entry.server.tsx b/apps/mes/app/entry.server.tsx
index 9b96448879..df1db86d13 100644
--- a/apps/mes/app/entry.server.tsx
+++ b/apps/mes/app/entry.server.tsx
@@ -9,6 +9,8 @@ import {
setStrictContentSecurityPolicy
} from "@carbon/auth/middleware/security.server";
import { getProcessPool } from "@carbon/database/client";
+import { initFlags } from "@carbon/env/flags.server";
+import { redisFlagsStore } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
import { ensureLoggingConfigured } from "@carbon/logger/config.server";
import { getRequestId } from "@carbon/logger/middleware.server";
@@ -35,6 +37,17 @@ export const instrumentations = createTracing({
afterRequest: process.env.VERCEL ? (flush) => waitUntil(flush()) : undefined
});
+// Feature flags: every process reads the shared copy in Redis and syncs it in
+// the background. Until the first document loads, each flag answers its
+// registry default.
+const flagsLog = getLogger("mes", "flags");
+void initFlags({
+ store: redisFlagsStore,
+ waitUntil: process.env.VERCEL ? waitUntil : undefined,
+ // Structured, so Axiom can alert on stale flags (`ageMs`) and archived reads.
+ onWarning: (message, properties) => flagsLog.warn(message, properties)
+});
+
const log = getLogger("mes");
// Process-level safety net: errors that escape the request lifecycle entirely
diff --git a/apps/mes/package.json b/apps/mes/package.json
index 3701a9265f..691ce19144 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -13,6 +13,7 @@
"@carbon/dev": "workspace:*",
"@carbon/documents": "workspace:*",
"@carbon/ee": "workspace:*",
+ "@carbon/env": "workspace:*",
"@carbon/files": "workspace:*",
"@carbon/form": "workspace:*",
"@carbon/jobs": "workspace:*",
diff --git a/ci/package.json b/ci/package.json
index 4401076ef7..17284b256b 100644
--- a/ci/package.json
+++ b/ci/package.json
@@ -4,6 +4,9 @@
"version": "0.0.1",
"description": "Deployment scripts for Carbon",
"dependencies": {
+ "@carbon/env": "workspace:*",
+ "@openfeature/core": "catalog:",
+ "@openfeature/flagd-core": "catalog:",
"@supabase/supabase-js": "catalog:",
"dotenv": "16.3.1",
"execa": "8.0.1",
diff --git a/ci/src/deploy.ts b/ci/src/deploy.ts
index 76339b3b23..22aec90a69 100644
--- a/ci/src/deploy.ts
+++ b/ci/src/deploy.ts
@@ -5,6 +5,7 @@
import { $ } from "execa";
import { client } from "./client";
+import { fetchFlagsDocument } from "./flags";
export type Workspace = {
id: number;
@@ -91,6 +92,10 @@ export type Workspace = {
xero_client_id: string | null;
xero_client_secret: string | null;
xero_webhook_secret: string | null;
+
+ // Feature flags, fetched at deploy time (fetchFlagsDocument).
+ flags_endpoint: string | null;
+ flags_token: string | null;
};
async function deploy(): Promise<void> {
@@ -139,6 +144,8 @@ async function deploy(): Promise<void> {
database_url,
domain_name,
exchange_rates_api_key,
+ flags_endpoint,
+ flags_token,
google_client_id,
google_client_secret,
google_oauth_redirect_url,
@@ -290,6 +297,12 @@ async function deploy(): Promise<void> {
: `https://${assembler_domain}`
: undefined;
+ // Feature flags are fixed at deploy time. A failed fetch fails this
+ // workspace's deploy, and the running release keeps its flags.
+ const carbon_flags_endpoint = flags_endpoint
+ ? await fetchFlagsDocument(flags_endpoint, flags_token, imageTag)
+ : undefined;
+
const $$ = $({
// @ts-ignore
env: {
@@ -300,6 +313,7 @@ async function deploy(): Promise<void> {
ASSEMBLER_SERVICE_URL: assembler_service_url,
AUTH_PROVIDERS: auth_providers ?? undefined,
CARBON_EDITION: carbon_edition ?? "enterprise",
+ CARBON_FLAGS_ENDPOINT: carbon_flags_endpoint,
CERT_ARN_ERP: cert_arn_erp,
CERT_ARN_MES: cert_arn_mes,
CLOUDFLARE_TURNSTILE_SECRET_KEY:
diff --git a/ci/src/flags.test.ts b/ci/src/flags.test.ts
new file mode 100644
index 0000000000..72ae2bb3ed
--- /dev/null
+++ b/ci/src/flags.test.ts
@@ -0,0 +1,74 @@
+// 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 assert from "node:assert/strict";
+import { test } from "node:test";
+import { assertFlagdDocument, fetchFlagsDocument } from "./flags";
+
+const doc = (flags: object) => JSON.stringify({ flags });
+const valid = {
+ "multi-company-management": {
+ state: "ENABLED",
+ variants: { on: true, off: false },
+ defaultVariant: "off"
+ }
+};
+
+test("accepts a valid document", () => {
+ assert.doesNotThrow(() => assertFlagdDocument(doc(valid)));
+});
+
+test("refuses a string variant on a registered boolean flag", () => {
+ assert.throws(
+ () =>
+ assertFlagdDocument(
+ doc({
+ "multi-company-management": {
+ state: "ENABLED",
+ variants: { on: "true" },
+ defaultVariant: "on"
+ }
+ })
+ ),
+ /must have boolean variants/
+ );
+});
+
+test("refuses a default variant that is not an own variant", () => {
+ assert.throws(() =>
+ assertFlagdDocument(
+ doc({ x: { state: "ENABLED", variants: {}, defaultVariant: "toString" } })
+ )
+ );
+});
+
+test("refuses an invalid state", () => {
+ assert.throws(() =>
+ assertFlagdDocument(
+ doc({ x: { state: "enabled", variants: { on: true }, defaultVariant: "on" } })
+ )
+ );
+});
+
+test("refuses an invalid targeting rule", () => {
+ assert.throws(() =>
+ assertFlagdDocument(
+ doc({
+ x: {
+ state: "ENABLED",
+ variants: { on: true },
+ defaultVariant: "on",
+ targeting: { nope: [1] }
+ }
+ })
+ )
+ );
+});
+
+test("never sends a token over http:", async () => {
+ await assert.rejects(
+ fetchFlagsDocument("http://flags.example.com", "secret", "abc"),
+ /must use https/
+ );
+});
diff --git a/ci/src/flags.ts b/ci/src/flags.ts
new file mode 100644
index 0000000000..be8a629d33
--- /dev/null
+++ b/ci/src/flags.ts
@@ -0,0 +1,71 @@
+// 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 { FLAGS } from "@carbon/env/flags";
+import { MemoryStorage } from "@openfeature/flagd-core";
+
+// The data: URL rides in the ECS task definition, which AWS caps at 64 KiB in
+// total, so the document gets a much smaller cap than the provider's 1 MB.
+const MAX_FLAGS_DOCUMENT_BYTES = 32 * 1024;
+
+/**
+ * The workspace's feature flags document as a `data:` URL for
+ * `CARBON_FLAGS_ENDPOINT`. The instance loads it once and never calls the
+ * source at runtime. Throws on any failure.
+ */
+export async function fetchFlagsDocument(
+ endpoint: string,
+ token: string | null,
+ commit: string
+): Promise<string> {
+ if (token && !endpoint.startsWith("https://")) {
+ throw new Error("flags_endpoint must use https: when flags_token is set");
+ }
+ const res = await fetch(endpoint, {
+ headers: {
+ // 12 characters, as the apps send it.
+ "X-Carbon-Commit": commit.slice(0, 12),
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
+ },
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!res.ok) {
+ throw new Error(`The flags source answered ${res.status}`);
+ }
+ if (Number(res.headers.get("content-length") ?? 0) > MAX_FLAGS_DOCUMENT_BYTES) {
+ throw new Error("The flags document is larger than 32 KiB");
+ }
+ // Read through a cap, so a wrong endpoint never downloads a large file.
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for await (const chunk of res.body ?? []) {
+ size += chunk.byteLength;
+ if (size > MAX_FLAGS_DOCUMENT_BYTES) {
+ throw new Error("The flags document is larger than 32 KiB");
+ }
+ chunks.push(chunk);
+ }
+ const body = Buffer.concat(chunks).toString("utf8");
+ assertFlagdDocument(body);
+ return `data:application/json;base64,${Buffer.from(body).toString("base64")}`;
+}
+
+// flagd-core's strict mode checks the flag and targeting schemas that the
+// provider's lenient parse only logs, and every registered flag is a boolean
+// (`@carbon/env/flags`). A bad document fails the deploy instead of running a
+// whole release on code defaults.
+const silent = { debug() {}, info() {}, warn() {}, error() {} };
+
+export function assertFlagdDocument(body: string): void {
+ new MemoryStorage(silent).setConfigurations(body, true);
+ const { flags } = JSON.parse(body) as {
+ flags: Record<string, { variants?: Record<string, unknown> }>;
+ };
+ for (const key of Object.keys(FLAGS)) {
+ const variants = Object.values(flags[key]?.variants ?? {});
+ if (variants.some((value) => typeof value !== "boolean")) {
+ throw new Error(`Flag "${key}" must have boolean variants`);
+ }
+ }
+}
diff --git a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml
index 27b289c8c6..3afe7d03a9 100644
--- a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml
+++ b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml
@@ -69,6 +69,9 @@ services:
CARBON_EDITION: ${CARBON_EDITION:-community}
MAINTENANCE_MODE: ${MAINTENANCE_MODE:-}
SYSTEM_STATUS_URL: ${SYSTEM_STATUS_URL:-}
+ CARBON_FLAGS_ENDPOINT: ${CARBON_FLAGS_ENDPOINT:-}
+ CARBON_FLAGS_HEADERS: ${CARBON_FLAGS_HEADERS:-}
+ CARBON_COMMIT_SHA: ${CARBON_COMMIT_SHA:-}
AUTH_PROVIDERS: ${AUTH_PROVIDERS:-email,google,azure}
DOMAIN: ${DOMAIN}
ERP_URL: ${ERP_URL}
@@ -118,6 +121,9 @@ services:
CARBON_EDITION: ${CARBON_EDITION:-community}
MAINTENANCE_MODE: ${MAINTENANCE_MODE:-}
SYSTEM_STATUS_URL: ${SYSTEM_STATUS_URL:-}
+ CARBON_FLAGS_ENDPOINT: ${CARBON_FLAGS_ENDPOINT:-}
+ CARBON_FLAGS_HEADERS: ${CARBON_FLAGS_HEADERS:-}
+ CARBON_COMMIT_SHA: ${CARBON_COMMIT_SHA:-}
AUTH_PROVIDERS: ${AUTH_PROVIDERS:-email,google,azure}
DOMAIN: ${DOMAIN}
ERP_URL: ${ERP_URL}
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index 0e93d73490..147e9208f8 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -77,7 +77,7 @@ pnpm --filter @carbon/ee typecheck
- **Ledger delegation**: when a spend provider's mode declares `ownsLedgerFamilies`, `applyLedgerDelegation` sets that family to `"none"` AND disables its backing entities — derived from `POSTING_POLICY`, never a hard-coded `"bill"`. Each half alone is wrong (families-only leaves the document pushing; entity-only parks a `DOC_SYNC_DISABLED` Warning forever). `getJournalPostingPolicyDecision` accepts only `EffectivePostingSyncSettings`, so the compiler refuses a posting decision made from raw settings
- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions
- **Workflow integration connections**: `./integrations/connections` — named per-company connections to Activepieces pieces (`integrationConnection` table + its own `connection:`-prefixed vault RPCs). Distinct from `./integrations/secrets`, which serves `companyIntegration` and allows only one row per integration per company. Tokens go to the vault, never to `metadata`; refresh is claimed via `refreshingAt`. The piece itself ships as an ORDINARY integration config (`google-calendar/config.tsx`, `gmail/config.tsx`, `slack/config.tsx`; `id` === the piece name) — the accounts list is a tab on its card, not a separate panel. Slack's Carbon Assistant (`slack/lib/service.ts`) is a *consumer* of that connection (`getSlackWorkspace`, oldest Active; inbound by `team_id`), never a second store. See `.claude/rules/workflow-integrations.md`
-- **Internal-only integrations**: `internalOnly: true` on a descriptor makes it installable on Carbon Cloud only by Carbon staff (`isInternalEmail`), in any company, and by users whose id is in `INTEGRATION_EARLY_ACCESS_USER_IDS` (`hasIntegrationEarlyAccess`, `./plan.server`; comma-separated, read on the server only, so the list never reaches the browser or the code); everyone else sees a Coming soon card. Self-hosted editions are not gated. `isIntegrationComingSoon` (`./plan`) is the one rule; the ERP's `isIntegrationInstallWithheld` (`modules/settings/settings.service.ts`) applies it in the connect route, the install action and the `onshape-v2` install route, and only to a company that does not have the integration installed. An integration with its own install route must call it there too
+- **Internal-only integrations**: `internalOnly: true` on a descriptor makes it installable on Carbon Cloud only by Carbon staff (`isInternalEmail`), in any company, and by the users the `integration-early-access` feature flag is on for, in the companies its rules name, or whose id is in `INTEGRATION_EARLY_ACCESS_USER_IDS` (a fallback until a flags source is live) (`hasIntegrationEarlyAccess({ companyId, userId })`, `./plan.server`; evaluated on the server, so neither the rules nor the list reach the browser); everyone else sees a Coming soon card. Self-hosted editions are not gated. `isIntegrationComingSoon` (`./plan`) is the one rule; the ERP's `isIntegrationInstallWithheld` (`modules/settings/settings.service.ts`) applies it in the connect route, the install action and the `onshape-v2` install route, and only to a company that does not have the integration installed. An integration with its own install route must call it there too
- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.service.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`
- **Onshape panel auth** (`./onshape/panel-session.server`, `src/onshape/panel/session.server.ts`): the `cps_` bearer credential for the Onshape iframe, which the `SameSite=Lax` `carbon` cookie cannot reach. Mints, stores (Redis `panel-session:<token>`, 12 h) and revokes sessions, and exports `requireOnshapePanelPermissions`, the panel routes' gate: the same claims check as `requirePermissions`, answering 401/403 with no redirect. Imports `getUserClaims`, `userHasVerifiedTotpFactor`, `getUserScopedClient` and `hasPermission` from `@carbon/auth`; auth never imports it back. See `.claude/rules/onshape-panel.md`
- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./audit.server`, `./backups.server`, `./email-notifications.server`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./mcp`, `./mcp.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./onshape/integration-id`, `./onshape/panel-session.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, `./oee`, `./oee.server`, `./sense/hooks.server`, etc.
diff --git a/packages/ee/src/plan.server.ts b/packages/ee/src/plan.server.ts
index a5b32ed263..62eae94a22 100644
--- a/packages/ee/src/plan.server.ts
+++ b/packages/ee/src/plan.server.ts
@@ -14,6 +14,7 @@ import {
} from "@carbon/auth/company.server";
import { flash } from "@carbon/auth/session.server";
import type { Database } from "@carbon/database";
+import { flags } from "@carbon/env/flags.server";
import { Edition, normalizePlanId, Plan, redirect } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import {
@@ -33,12 +34,22 @@ function isBypassCompany(companyId: string): boolean {
/**
* Whether this user may install an `internalOnly` integration on Carbon Cloud
- * without a Carbon email (`isIntegrationComingSoon`): their id is listed in
- * `INTEGRATION_EARLY_ACCESS_USER_IDS`. The list is deployment configuration,
- * so no customer's id is in the code.
+ * without a Carbon email (`isIntegrationComingSoon`): the
+ * `integration-early-access` flag is on for them 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 function hasIntegrationEarlyAccess(userId: string): boolean {
- return isListedUserId(INTEGRATION_EARLY_ACCESS_USER_IDS, userId);
+export async function hasIntegrationEarlyAccess(context: {
+ companyId: string;
+ userId: string;
+}): Promise<boolean> {
+ return (
+ isListedUserId(INTEGRATION_EARLY_ACCESS_USER_IDS, context.userId) ||
+ flags.bool("integration-early-access", context)
+ );
}
// The plan read is `getCompanyPlanId` (`@carbon/auth`): service role, cached, and
diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.ts
index 20fb2f0761..ad85a22410 100644
--- a/packages/ee/src/types.ts
+++ b/packages/ee/src/types.ts
@@ -210,11 +210,12 @@ export type IntegrationConfig = {
*/
active?: boolean;
/**
- * Installable on Carbon Cloud by Carbon staff and early access users only,
- * while the integration is rolled out. Everyone else sees a "Coming soon"
- * card. They may install it in any company they belong to, and the install
- * then works for that company like any other. See `isIntegrationComingSoon`
- * (`plan.ts`) and `hasIntegrationEarlyAccess` (`plan.server.ts`).
+ * Installable on Carbon Cloud by Carbon staff, in any company, and by the
+ * users the `integration-early-access` flag is on for, in the companies its
+ * rules name, while the integration is rolled out. Everyone else sees a
+ * "Coming soon" card. The install then works for that company like any
+ * other. See `isIntegrationComingSoon` (`plan.ts`) and
+ * `hasIntegrationEarlyAccess` (`plan.server.ts`).
*/
internalOnly?: boolean;
/** Category for grouping in the UI (e.g., "Accounting", "CAD", "Email") */
diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.md
index 6b86317b91..09102bed2c 100644
--- a/packages/env/AGENTS.md
+++ b/packages/env/AGENTS.md
@@ -46,6 +46,12 @@ pnpm --filter @carbon/env test
- **Integrations:** Stripe, SMTP email, Slack, Xero, Jira, OnShape, QuickBooks keys (all optional)
- **Web Push (`@carbon/env/push.server`, server-only — imports `node:crypto`):** `getVapidDetails()`, `isPushConfigured()`, `deriveVapidDetails(secret, appUrl)`. The VAPID pair is derived from `SESSION_SECRET` by HKDF, so there are no push env vars; keep it out of `src/index.ts`, which the browser imports.
+- **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`).
+ - `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.
+
## Cross-References
- `.claude/rules/environment-configuration.md` — full env architecture, `.env` vs `.env.local`, URL resolution
diff --git a/packages/env/package.json b/packages/env/package.json
index 743ef5c336..275b3d3f7e 100644
--- a/packages/env/package.json
+++ b/packages/env/package.json
@@ -6,7 +6,9 @@
"exports": {
".": "./src/index.ts",
"./push.server": "./src/push.server.ts",
- "./validate": "./src/validate.ts"
+ "./validate": "./src/validate.ts",
+ "./flags": "./src/flags.ts",
+ "./flags.server": "./src/flags.server.ts"
},
"main": "./src/index.ts",
"types": "./src/index.ts",
@@ -19,6 +21,9 @@
},
"dependencies": {
"@carbon/utils": "workspace:*",
+ "@openfeature/core": "catalog:",
+ "@openfeature/flagd-core": "catalog:",
+ "@openfeature/server-sdk": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
diff --git a/packages/env/src/flags.server.test.ts b/packages/env/src/flags.server.test.ts
new file mode 100644
index 0000000000..9f6dea30ce
--- /dev/null
+++ b/packages/env/src/flags.server.test.ts
@@ -0,0 +1,477 @@
+// 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.
+
+/// <reference types="node" />
+import { createServer, type Server } from "node:http";
+import { OpenFeature } from "@openfeature/server-sdk";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi
+} from "vitest";
+import {
+ CarbonFlagsProvider,
+ evaluateBrowserFlags,
+ type FlagsStore,
+ flags,
+ parseHeaders,
+ type StoredFlags
+} from "./flags.server";
+
+type Rule = Record<string, unknown>;
+
+const flagDoc = (
+ targeting: Rule | null,
+ metadata: Record<string, unknown> = {}
+) =>
+ JSON.stringify({
+ $schema: "https://flagd.dev/schema/v0/flags.json",
+ flags: {
+ "multi-company-management": {
+ state: "ENABLED",
+ variants: { on: true, off: false },
+ defaultVariant: "off",
+ ...(targeting ? { targeting } : {}),
+ metadata
+ }
+ }
+ });
+
+const companyRule = (ids: string[]) => ({
+ if: [{ in: [{ var: "companyId" }, ids] }, "on", null]
+});
+
+/** A local flags source. `doc` and `mode` can change between requests. */
+let server: Server;
+let url = "";
+let doc = flagDoc(companyRule(["cmp_123"]));
+let etag = '"v1"';
+let mode: "ok" | "hang" | "big" | "down" = "ok";
+let requests: {
+ ifNoneMatch?: string;
+ authorization?: string;
+ commit?: string;
+}[] = [];
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ requests.push({
+ ifNoneMatch: req.headers["if-none-match"] as string | undefined,
+ authorization: req.headers.authorization,
+ commit: req.headers["x-carbon-commit"] as string | undefined
+ });
+ if (mode === "hang") return;
+ if (mode === "down") return res.writeHead(503).end();
+ if (mode === "big")
+ return res.writeHead(200).end("x".repeat((1 << 20) + 10));
+ if (req.headers["if-none-match"] === etag) return res.writeHead(304).end();
+ res.writeHead(200, { ETag: etag }).end(doc);
+ }).listen(0);
+ await new Promise((resolve) => server.once("listening", resolve));
+ url = `http://127.0.0.1:${(server.address() as { port: number }).port}/flags`;
+});
+
+afterAll(() => {
+ server.closeAllConnections();
+ server.close();
+});
+
+afterEach(async () => {
+ doc = flagDoc(companyRule(["cmp_123"]));
+ etag = '"v1"';
+ mode = "ok";
+ requests = [];
+ vi.restoreAllMocks();
+ await OpenFeature.clearProviders();
+});
+
+/** A shared store in memory, with the same lease semantics as Redis. */
+function memoryStore(): FlagsStore & { data: Map<string, StoredFlags> } {
+ const data = new Map<string, StoredFlags>();
+ const leases = new Set<string>();
+ return {
+ data,
+ readMeta: async (scope) => {
+ const value = data.get(scope);
+ return value ? { etag: value.etag, fetchedAt: value.fetchedAt } : null;
+ },
+ readBody: async (scope) => data.get(scope)?.body ?? null,
+ write: async (scope, value) => {
+ data.set(scope, { ...(data.get(scope) as StoredFlags), ...value });
+ },
+ tryLease: async (scope) => {
+ if (leases.has(scope)) return { status: "held" };
+ leases.add(scope);
+ return {
+ status: "acquired",
+ release: async () => {
+ leases.delete(scope);
+ }
+ };
+ }
+ };
+}
+
+const unavailableStore: FlagsStore = {
+ readMeta: async () => null,
+ readBody: async () => null,
+ write: async () => undefined,
+ tryLease: async () => ({ status: "unavailable" })
+};
+
+let domain = 0;
+async function start(provider: CarbonFlagsProvider) {
+ const name = `test-${domain++}`;
+ await OpenFeature.setProviderAndWait(name, provider);
+ const client = OpenFeature.getClient(name);
+ return (companyId: string, userId?: string) =>
+ client.getBooleanValue("multi-company-management", false, {
+ targetingKey: userId ?? companyId,
+ companyId
+ });
+}
+
+describe("parseHeaders", () => {
+ it("keeps '+', decodes '%2C' and '=', and skips a malformed pair", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ expect(
+ parseHeaders(
+ "Authorization=Bearer%20ab+c%2Cd=,X-Bad=%zz, X-Carbon-Instance = inst_1,no-equals"
+ )
+ ).toEqual({
+ authorization: "Bearer ab+c,d=",
+ "x-carbon-instance": "inst_1"
+ });
+ expect(warn).toHaveBeenCalledOnce();
+ });
+});
+
+describe("CarbonFlagsProvider", () => {
+ it("answers the default when no endpoint is set", async () => {
+ const read = await start(new CarbonFlagsProvider({}));
+ expect(await read("cmp_123")).toBe(false);
+ expect(requests).toHaveLength(0);
+ });
+
+ it("targets companies, and sends the configured headers", async () => {
+ const read = await start(
+ new CarbonFlagsProvider({
+ endpoint: url,
+ headers: "Authorization=Bearer%20tok+1"
+ })
+ );
+ expect(await read("cmp_123")).toBe(true);
+ expect(await read("cmp_999")).toBe(false);
+ expect(requests[0]?.authorization).toBe("Bearer tok+1");
+ });
+
+ it("treats header names case-insensitively, and a configured commit wins", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ expect(parseHeaders("Authorization=a,authorization=b")).toEqual({
+ authorization: "b"
+ });
+ await start(
+ new CarbonFlagsProvider({
+ endpoint: url,
+ commit: "aaaaaaaaaaaaaaaa",
+ headers: "X-Carbon-Commit=bbbbbbbbbbbb"
+ })
+ );
+ expect(requests[0]?.commit).toBe("bbbbbbbbbbbb");
+ });
+
+ it("sends the first 12 characters of the build's commit as X-Carbon-Commit", async () => {
+ await start(
+ new CarbonFlagsProvider({
+ endpoint: url,
+ commit: "abc123def4567890abc123def4567890abc12345"
+ })
+ );
+ expect(requests[0]?.commit).toBe("abc123def456");
+ });
+
+ it("targets users inside a company", async () => {
+ doc = flagDoc({
+ if: [
+ {
+ and: [
+ { in: [{ var: "companyId" }, ["cmp_A"]] },
+ { in: [{ var: "targetingKey" }, ["usr_X"]] }
+ ]
+ },
+ "on",
+ null
+ ]
+ });
+ const read = await start(new CarbonFlagsProvider({ endpoint: url }));
+ expect(await read("cmp_A", "usr_X")).toBe(true);
+ expect(await read("cmp_B", "usr_X")).toBe(false);
+ expect(await read("cmp_A", "usr_Y")).toBe(false);
+ });
+
+ it("adds tenancy and edition to the context", async () => {
+ doc = flagDoc({
+ if: [
+ {
+ and: [
+ { "==": [{ var: "tenancy" }, "single"] },
+ { in: [{ var: "edition" }, ["enterprise"]] }
+ ]
+ },
+ "on",
+ null
+ ]
+ });
+ const on = await start(
+ new CarbonFlagsProvider({
+ endpoint: url,
+ tenancy: "single",
+ edition: "enterprise"
+ })
+ );
+ const off = await start(
+ new CarbonFlagsProvider({
+ endpoint: url,
+ tenancy: "multi",
+ edition: "enterprise"
+ })
+ );
+ const cloud = await start(
+ new CarbonFlagsProvider({
+ endpoint: url,
+ tenancy: "single",
+ edition: "cloud"
+ })
+ );
+ expect(await on("cmp_1")).toBe(true);
+ expect(await off("cmp_1")).toBe(false);
+ expect(await cloud("cmp_1")).toBe(false);
+ });
+
+ it("sends the ETag and keeps the flags on a 304", async () => {
+ const provider = new CarbonFlagsProvider({ endpoint: url });
+ const read = await start(provider);
+ await provider.refresh();
+ expect(requests.at(-1)?.ifNoneMatch).toBe('"v1"');
+ expect(provider.lastError).toBeUndefined();
+ expect(await read("cmp_123")).toBe(true);
+ });
+
+ it("refuses a body over 1 MB and keeps the loaded flags", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const provider = new CarbonFlagsProvider({ endpoint: url });
+ const read = await start(provider);
+ mode = "big";
+ await provider.refresh();
+ expect(provider.lastError).toMatch(/larger than 1 MB/);
+ expect(await read("cmp_123")).toBe(true);
+ });
+
+ it("refuses an invalid document and keeps the loaded flags", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const provider = new CarbonFlagsProvider({ endpoint: url });
+ const read = await start(provider);
+ doc = '{"flags":{"x":{"state":"MAYBE"}}}';
+ etag = '"v2"';
+ await provider.refresh();
+ expect(provider.lastError).toBeDefined();
+ expect(await read("cmp_123")).toBe(true);
+ });
+
+ it("waits at most 2 s at boot when the source hangs and the store is empty", async () => {
+ mode = "hang";
+ const started = Date.now();
+ const read = await start(
+ new CarbonFlagsProvider({ endpoint: url, store: memoryStore() })
+ );
+ expect(Date.now() - started).toBeLessThan(2_600);
+ expect(await read("cmp_123")).toBe(false);
+ });
+
+ it("does not wait for the source when the store has a copy", async () => {
+ const store = memoryStore();
+ await start(new CarbonFlagsProvider({ endpoint: url, store }));
+ mode = "hang";
+ const started = Date.now();
+ const read = await start(new CarbonFlagsProvider({ endpoint: url, store }));
+ expect(Date.now() - started).toBeLessThan(200);
+ expect(await read("cmp_123")).toBe(true);
+ });
+
+ it("lets 5 processes share one store with 1 source request", async () => {
+ const store = memoryStore();
+ const providers = Array.from(
+ { length: 5 },
+ () => new CarbonFlagsProvider({ endpoint: url, store })
+ );
+ const reads = await Promise.all(providers.map(start));
+ expect(requests).toHaveLength(1);
+ for (const read of reads) expect(await read("cmp_123")).toBe(true);
+
+ // Within 60 s, syncs read the store and never call the source.
+ await Promise.all(providers.map((provider) => provider.refresh()));
+ expect(requests).toHaveLength(1);
+ });
+
+ it("carries a new document from one process to another through the store", async () => {
+ const store = memoryStore();
+ const a = new CarbonFlagsProvider({ endpoint: url, store });
+ const b = new CarbonFlagsProvider({ endpoint: url, store });
+ await start(a);
+ const readB = await start(b);
+ expect(await readB("cmp_456")).toBe(false);
+
+ doc = flagDoc(companyRule(["cmp_456"]));
+ etag = '"v2"';
+ for (const value of store.data.values()) value.fetchedAt = 0; // make it stale
+ await a.refresh();
+ await b.refresh();
+ expect(await readB("cmp_456")).toBe(true);
+ expect(requests).toHaveLength(2);
+ });
+
+ it("keeps the lease after a failed fetch, so the fleet retries once per lease", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const store = memoryStore();
+ const a = new CarbonFlagsProvider({ endpoint: url, store });
+ const b = new CarbonFlagsProvider({ endpoint: url, store });
+ await start(a);
+ await start(b);
+ expect(requests).toHaveLength(1);
+
+ mode = "down";
+ for (const value of store.data.values()) value.fetchedAt = 0;
+ await a.refresh();
+ await b.refresh();
+ expect(requests).toHaveLength(2);
+ expect(a.lastError).toMatch(/503/);
+ });
+
+ it("fetches the source when the store holds a copy it cannot load", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const store = memoryStore();
+ await start(new CarbonFlagsProvider({ endpoint: url, store }));
+ for (const value of store.data.values()) {
+ value.body = '{"flags":{"x":{"state":"MAYBE"}}}';
+ value.etag = '"bad"';
+ }
+ const read = await start(new CarbonFlagsProvider({ endpoint: url, store }));
+ expect(await read("cmp_123")).toBe(true);
+ // Every process on this scope runs the same flagd-core, so the fetch
+ // repairs the shared copy.
+ for (const value of store.data.values()) expect(value.etag).toBe('"v1"');
+ });
+
+ it("sends warnings to onWarning with structured properties", async () => {
+ const warnings: [string, Record<string, unknown>][] = [];
+ const provider = new CarbonFlagsProvider({
+ endpoint: url,
+ onWarning: (message, properties) => warnings.push([message, properties])
+ });
+ await start(provider);
+ mode = "down";
+ await provider.refresh();
+ expect(warnings).toEqual([
+ [
+ "Feature flags kept after a failed sync",
+ expect.objectContaining({ lastError: expect.stringMatching(/503/) })
+ ]
+ ]);
+ });
+
+ it("fetches the source directly when the store is unavailable", async () => {
+ const read = await start(
+ new CarbonFlagsProvider({ endpoint: url, store: unavailableStore })
+ );
+ expect(await read("cmp_123")).toBe(true);
+ });
+
+ it("loads a data: endpoint once and never fetches again", async () => {
+ const provider = new CarbonFlagsProvider({
+ endpoint: `data:application/json;base64,${Buffer.from(doc).toString("base64")}`
+ });
+ const read = await start(provider);
+ expect(await read("cmp_123")).toBe(true);
+ await read("cmp_123");
+ expect(requests).toHaveLength(0);
+ });
+
+ it("refuses http: off localhost, so the token never goes out unencrypted", async () => {
+ const warnings: string[] = [];
+ const read = await start(
+ new CarbonFlagsProvider({
+ endpoint: "http://flags.example.com/api/flags",
+ headers: "Authorization=Bearer%20secret",
+ onWarning: (message) => warnings.push(message)
+ })
+ );
+ expect(await read("cmp_123")).toBe(false);
+ expect(warnings).toHaveLength(1);
+ });
+
+ it("refuses a file: endpoint with a warning and answers the defaults", async () => {
+ const warnings: string[] = [];
+ const provider = new CarbonFlagsProvider({
+ endpoint: "file:///etc/carbon/flags.json",
+ onWarning: (message) => warnings.push(message)
+ });
+ const read = await start(provider);
+ expect(await read("cmp_123")).toBe(false);
+ expect(warnings).toEqual([
+ "CARBON_FLAGS_ENDPOINT must be an https: or data: URL (http: only on localhost); using the code defaults"
+ ]);
+ });
+
+ it("warns once per archived flag that the code reads", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ doc = flagDoc(companyRule(["cmp_123"]), { archived: true });
+ const read = await start(new CarbonFlagsProvider({ endpoint: url }));
+ await read("cmp_123");
+ await read("cmp_999");
+ expect(
+ warn.mock.calls.filter(([message]) =>
+ String(message).includes("archived")
+ )
+ ).toHaveLength(1);
+ });
+
+ it("answers the default for a DISABLED flag", async () => {
+ doc = JSON.stringify({
+ flags: {
+ "multi-company-management": {
+ state: "DISABLED",
+ variants: { on: true, off: false },
+ defaultVariant: "on"
+ }
+ }
+ });
+ const read = await start(new CarbonFlagsProvider({ endpoint: url }));
+ expect(await read("cmp_123")).toBe(false);
+ });
+});
+
+describe("flags and evaluateBrowserFlags", () => {
+ it("read the registry default and the evaluated value", async () => {
+ expect(
+ await flags.bool("multi-company-management", { companyId: "cmp_123" })
+ ).toBe(false);
+
+ await OpenFeature.setProviderAndWait(
+ new CarbonFlagsProvider({ endpoint: url })
+ );
+ expect(
+ await flags.bool("multi-company-management", { companyId: "cmp_123" })
+ ).toBe(true);
+ expect(
+ await flags.bool("integration-early-access", { companyId: "cmp_123" })
+ ).toBe(false);
+ expect(await evaluateBrowserFlags({ companyId: "cmp_123" })).toEqual({
+ "multi-company-management": true
+ });
+ });
+});
diff --git a/packages/env/src/flags.server.ts b/packages/env/src/flags.server.ts
new file mode 100644
index 0000000000..54ed539708
--- /dev/null
+++ b/packages/env/src/flags.server.ts
@@ -0,0 +1,584 @@
+// 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.
+
+/// <reference types="node" />
+import { createHash } from "node:crypto";
+import { FlagdCore } from "@openfeature/flagd-core";
+import flagdCorePackage from "@openfeature/flagd-core/package.json";
+import {
+ type Client,
+ type EvaluationContext,
+ type JsonValue,
+ type Logger,
+ OpenFeature,
+ type Provider,
+ type ResolutionDetails
+} from "@openfeature/server-sdk";
+import {
+ BROWSER_FLAG_KEYS,
+ type BrowserFlags,
+ type FlagKey,
+ flagDefault
+} from "./flags";
+import {
+ CARBON_COMMIT_SHA,
+ CARBON_FLAGS_ENDPOINT,
+ CARBON_FLAGS_HEADERS,
+ CarbonEdition,
+ SINGLE_TENANT
+} from "./index";
+
+// How often a process re-reads the shared copy, and how old the shared copy may
+// get before one process fetches the source again. Both get ±20% jitter.
+const STORE_SYNC_MS = 10_000;
+const SOURCE_REFRESH_MS = 60_000;
+const JITTER = 0.2;
+const FETCH_TIMEOUT_MS = 5_000;
+// A cold start with nothing in the store waits this long for a first document.
+const BOOT_WAIT_MS = 2_000;
+const BOOT_POLL_MS = 250;
+const MAX_BODY_BYTES = 1 << 20;
+
+type WarnFn = (message: string, properties: Record<string, unknown>) => void;
+
+// The default when the app passes no `onWarning`.
+const consoleWarn: WarnFn = (message, properties) => {
+ // biome-ignore lint/suspicious/noConsole: @carbon/logger depends on this package
+ console.warn(`flags: ${message}`, properties);
+};
+
+/**
+ * `CARBON_FLAGS_HEADERS` in the `OTEL_EXPORTER_OTLP_HEADERS` format: `k=v`
+ * pairs separated by commas, keys and values percent-encoded. A malformed pair
+ * is skipped, never thrown: flags must not stop the app from starting.
+ */
+export function parseHeaders(raw = ""): Record<string, string> {
+ const headers: Record<string, string> = {};
+ for (const pair of raw.split(",")) {
+ const i = pair.indexOf("=");
+ const key = pair.slice(0, i).trim();
+ if (i < 0 || !key) continue;
+ try {
+ // Header names are case-insensitive: keep one spelling, the last wins.
+ const name = decodeURIComponent(key).toLowerCase();
+ if (name in headers) {
+ consoleWarn("A CARBON_FLAGS_HEADERS name appears twice", { name });
+ }
+ headers[name] = decodeURIComponent(pair.slice(i + 1).trim());
+ } catch {
+ consoleWarn("Skipping a malformed CARBON_FLAGS_HEADERS pair", { key });
+ }
+ }
+ return headers;
+}
+
+export type StoredFlags = { body: string; etag: string; fetchedAt: number };
+
+export type FlagsStoreLease =
+ | { status: "acquired"; release: () => Promise<void> }
+ | { status: "held" }
+ | { status: "unavailable" };
+
+/**
+ * The copy of the flags document that every process of one instance shares.
+ * `@carbon/kv` implements it with Redis (`redisFlagsStore`); it cannot live
+ * here because `@carbon/kv` depends on this package. Reads answer null on a
+ * miss or when the store is down; only `tryLease` tells the two apart.
+ */
+export type FlagsStore = {
+ readMeta(scope: string): Promise<Omit<StoredFlags, "body"> | null>;
+ readBody(scope: string): Promise<string | null>;
+ write(
+ scope: string,
+ value: Partial<StoredFlags> & { fetchedAt: number }
+ ): Promise<void>;
+ tryLease(scope: string): Promise<FlagsStoreLease>;
+};
+
+export type CarbonFlagsOptions = {
+ endpoint?: string;
+ /** Raw `CARBON_FLAGS_HEADERS`. */
+ headers?: string;
+ /** The build's git commit, sent to the source as `X-Carbon-Commit`. */
+ commit?: string;
+ store?: FlagsStore;
+ /** Keeps a background sync alive after the response is sent (Vercel). */
+ waitUntil?: (promise: Promise<unknown>) => void;
+ /**
+ * Receives each warning with structured properties: a failed sync
+ * (`lastError`, `confirmedAt`, `ageMs`) and a read of an archived flag
+ * (`key`). The apps pass their logger, so Axiom can alert on stale flags.
+ */
+ onWarning?: WarnFn;
+ tenancy?: "single" | "multi";
+ edition?: string;
+};
+
+type Mode = "none" | "static" | "remote";
+
+const isLocalhost = (url: string) => {
+ try {
+ const host = new URL(url).hostname;
+ return (
+ host === "localhost" ||
+ host.endsWith(".localhost") ||
+ host === "127.0.0.1" ||
+ host === "[::1]"
+ );
+ } catch {
+ return false;
+ }
+};
+
+const jittered = (ms: number) => ms * (1 - JITTER + 2 * JITTER * Math.random());
+const sleep = (ms: number) =>
+ new Promise((resolve) => setTimeout(resolve, ms).unref?.());
+
+async function readCapped(res: Response): Promise<string> {
+ if (Number(res.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) {
+ throw new Error("the flags document is larger than 1 MB");
+ }
+ const reader = res.body?.getReader();
+ if (!reader) return "";
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > MAX_BODY_BYTES) {
+ await reader.cancel();
+ throw new Error("the flags document is larger than 1 MB");
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+/**
+ * An OpenFeature provider over a flagd JSON document, in three layers: the
+ * document parsed in process memory (every evaluation, no I/O), the copy in
+ * the store (re-read every 10 s), and the source (fetched under a lease when
+ * the store's copy is older than 60 s). A `data:` endpoint is
+ * loaded once and never touches the store.
+ */
+export class CarbonFlagsProvider implements Provider {
+ readonly metadata = { name: "carbon-flags" };
+ readonly runsOn = "server" as const;
+
+ /** Last time the source confirmed the document (a 200 or a 304). */
+ confirmedAt?: number;
+ lastError?: string;
+
+ private readonly core = new FlagdCore();
+ private readonly mode: Mode;
+ private readonly endpoint: string;
+ private readonly headers: Record<string, string>;
+ private readonly scope: string;
+ private readonly store?: FlagsStore;
+ private readonly waitUntil?: (promise: Promise<unknown>) => void;
+ private readonly onWarning: WarnFn;
+ private readonly context: { tenancy: string; edition: string };
+ private loadedEtag?: string;
+ private storeUnavailable = false;
+ private nextSyncAt = 0;
+ private inFlight?: Promise<void>;
+ private readonly warnedArchived = new Set<string>();
+
+ constructor(options: CarbonFlagsOptions) {
+ this.endpoint = options.endpoint ?? "";
+ // https: polls, data: loads once, and http: polls only on localhost (a
+ // local source in dev): the request carries the token. Anything else,
+ // file: included, is refused here rather than failing in fetch().
+ const scheme = /^[a-z][a-z0-9+.-]*:/i
+ .exec(this.endpoint)?.[0]
+ .toLowerCase();
+ this.mode = !this.endpoint
+ ? "none"
+ : scheme === "https:" ||
+ (scheme === "http:" && isLocalhost(this.endpoint))
+ ? "remote"
+ : scheme === "data:"
+ ? "static"
+ : "none";
+ // The source sees which build each instance runs. Configured headers win.
+ this.headers = {
+ // 12 characters on every platform, the length BYOC's release
+ // versions carry, so the source can compare them.
+ ...(options.commit
+ ? { "x-carbon-commit": options.commit.slice(0, 12) }
+ : {}),
+ ...parseHeaders(options.headers)
+ };
+ // Keyed by the flagd-core version too: processes on two versions that
+ // parse a document differently each keep their own shared copy.
+ this.scope = createHash("sha256")
+ .update(
+ `${this.endpoint}\n${options.headers ?? ""}\n${flagdCorePackage.version}`
+ )
+ .digest("hex")
+ .slice(0, 16);
+ this.store = options.store;
+ this.waitUntil = options.waitUntil;
+ this.onWarning = options.onWarning ?? consoleWarn;
+ if (this.endpoint && this.mode === "none") {
+ this.onWarning(
+ "CARBON_FLAGS_ENDPOINT must be an https: or data: URL (http: only on localhost); using the code defaults",
+ { scheme: scheme ?? null }
+ );
+ }
+ this.context = {
+ tenancy: options.tenancy ?? "multi",
+ edition: options.edition ?? "community"
+ };
+ }
+
+ async initialize() {
+ if (this.mode === "none") return;
+ if (this.mode === "static") {
+ try {
+ // Node's fetch reads data: URLs.
+ this.apply(await readCapped(await fetch(this.endpoint)), "static");
+ this.confirmedAt = Date.now();
+ } catch (error) {
+ this.fail(error);
+ }
+ return;
+ }
+
+ // Start on the shared copy and refresh in the background.
+ if (this.store && (await this.loadFromStore())) {
+ this.maybeSync();
+ return;
+ }
+
+ // Nothing shared yet: wait a little for this process's own sync, or for
+ // the process that holds the lease to write the first copy.
+ const deadline = Date.now() + BOOT_WAIT_MS;
+ const boot = this.sync();
+ this.waitUntil?.(boot);
+ await Promise.race([boot, sleep(BOOT_WAIT_MS)]);
+ while (
+ !this.loadedEtag &&
+ this.store &&
+ !this.storeUnavailable &&
+ Date.now() < deadline
+ ) {
+ await sleep(BOOT_POLL_MS);
+ await this.loadFromStore();
+ }
+ }
+
+ /** Runs a sync now. Used by tests. */
+ refresh(): Promise<void> {
+ this.nextSyncAt = 0;
+ return this.sync();
+ }
+
+ private apply(body: string, etag: string) {
+ this.core.setConfigurations(body);
+ this.loadedEtag = etag;
+ }
+
+ private fail(error: unknown) {
+ this.lastError = error instanceof Error ? error.message : String(error);
+ this.onWarning("Feature flags kept after a failed sync", {
+ lastError: this.lastError,
+ confirmedAt: this.confirmedAt ?? null,
+ ageMs: this.confirmedAt ? Date.now() - this.confirmedAt : null
+ });
+ }
+
+ private async loadFromStore(): Promise<boolean> {
+ if (!this.store) return false;
+ try {
+ const [meta, body] = await Promise.all([
+ this.store.readMeta(this.scope),
+ this.store.readBody(this.scope)
+ ]);
+ if (!meta || !body) return false;
+ if (meta.etag !== this.loadedEtag) this.apply(body, meta.etag);
+ this.confirmedAt = meta.fetchedAt;
+ return true;
+ } catch (error) {
+ this.fail(error);
+ return false;
+ }
+ }
+
+ private async fetchSource(
+ etag: string | undefined
+ ): Promise<{ status: 200; body: string; etag: string } | { status: 304 }> {
+ const res = await fetch(this.endpoint, {
+ headers: { ...this.headers, ...(etag && { "If-None-Match": etag }) },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
+ });
+ if (res.status === 304) return { status: 304 };
+ if (res.status !== 200) {
+ await res.body?.cancel();
+ throw new Error(`the flags source answered ${res.status}`);
+ }
+ const body = await readCapped(res);
+ // Callers apply() the body before they write it to the store. apply()
+ // throws on an invalid document, so a bad one never spreads.
+ const responseEtag =
+ res.headers.get("etag") ??
+ `"${createHash("sha256").update(body).digest("hex").slice(0, 32)}"`;
+ return { status: 200, body, etag: responseEtag };
+ }
+
+ private sync(): Promise<void> {
+ this.inFlight ??= this.runSync().finally(() => {
+ const interval =
+ this.store && !this.storeUnavailable
+ ? STORE_SYNC_MS
+ : SOURCE_REFRESH_MS;
+ this.nextSyncAt = Date.now() + jittered(interval);
+ this.inFlight = undefined;
+ });
+ return this.inFlight;
+ }
+
+ private async runSync() {
+ try {
+ if (!this.store) {
+ await this.syncFromSource();
+ return;
+ }
+
+ const meta = await this.store.readMeta(this.scope);
+ // A copy this process cannot load (corrupt, or written by a bug) must
+ // not block the source: fetch a full document and replace it.
+ let storeRejected = false;
+ if (meta && meta.etag !== this.loadedEtag) {
+ const body = await this.store.readBody(this.scope);
+ try {
+ if (body) this.apply(body, meta.etag);
+ } catch (error) {
+ storeRejected = true;
+ this.fail(error);
+ }
+ }
+ if (
+ meta &&
+ !storeRejected &&
+ Date.now() - meta.fetchedAt < SOURCE_REFRESH_MS
+ ) {
+ this.storeUnavailable = false;
+ this.confirmedAt = meta.fetchedAt;
+ this.lastError = undefined;
+ return;
+ }
+
+ const lease = await this.store.tryLease(this.scope);
+ if (lease.status === "held") return;
+ if (lease.status === "unavailable") {
+ this.storeUnavailable = true;
+ await this.syncFromSource();
+ return;
+ }
+ this.storeUnavailable = false;
+ // With an empty store, or a copy this process rejected, ask for the
+ // full document. On a failure the lease is kept until it expires (10 s),
+ // so a down source gets one attempt per lease period from the whole
+ // fleet, not one per process.
+ const result = await this.fetchSource(
+ storeRejected ? undefined : meta?.etag
+ );
+ const fetchedAt = Date.now();
+ if (result.status === 200) {
+ this.apply(result.body, result.etag);
+ // The scope includes the flagd-core version, so every process on this
+ // key parses alike: a copy this process rejected is bad for all of
+ // them, and the fresh document replaces it.
+ await this.store.write(this.scope, {
+ body: result.body,
+ etag: result.etag,
+ fetchedAt
+ });
+ } else {
+ await this.store.write(this.scope, { fetchedAt });
+ }
+ this.confirmedAt = fetchedAt;
+ this.lastError = undefined;
+ await lease.release().catch(() => undefined);
+ } catch (error) {
+ this.fail(error);
+ }
+ }
+
+ private async syncFromSource() {
+ const result = await this.fetchSource(this.loadedEtag);
+ if (result.status === 200) this.apply(result.body, result.etag);
+ this.confirmedAt = Date.now();
+ this.lastError = undefined;
+ }
+
+ // Sync on read, not on a timer: Vercel pauses the process between requests.
+ private maybeSync() {
+ if (this.mode !== "remote" || this.inFlight) return;
+ if (Date.now() < this.nextSyncAt) return;
+ const promise = this.sync();
+ this.waitUntil?.(promise);
+ }
+
+ private evaluate<T>(
+ key: string,
+ result: ResolutionDetails<T> & { flagMetadata?: Record<string, unknown> }
+ ): ResolutionDetails<T> {
+ if (
+ result.flagMetadata?.archived === true &&
+ !this.warnedArchived.has(key)
+ ) {
+ this.warnedArchived.add(key);
+ this.onWarning("Code read an archived feature flag", { key });
+ }
+ return result;
+ }
+
+ private withContext(context: EvaluationContext): EvaluationContext {
+ return { ...context, ...this.context };
+ }
+
+ async resolveBooleanEvaluation(
+ key: string,
+ defaultValue: boolean,
+ context: EvaluationContext,
+ logger: Logger
+ ) {
+ this.maybeSync();
+ return this.evaluate(
+ key,
+ this.core.resolveBooleanEvaluation(
+ key,
+ defaultValue,
+ this.withContext(context),
+ logger
+ )
+ );
+ }
+
+ async resolveStringEvaluation(
+ key: string,
+ defaultValue: string,
+ context: EvaluationContext,
+ logger: Logger
+ ) {
+ this.maybeSync();
+ return this.evaluate(
+ key,
+ this.core.resolveStringEvaluation(
+ key,
+ defaultValue,
+ this.withContext(context),
+ logger
+ )
+ );
+ }
+
+ async resolveNumberEvaluation(
+ key: string,
+ defaultValue: number,
+ context: EvaluationContext,
+ logger: Logger
+ ) {
+ this.maybeSync();
+ return this.evaluate(
+ key,
+ this.core.resolveNumberEvaluation(
+ key,
+ defaultValue,
+ this.withContext(context),
+ logger
+ )
+ );
+ }
+
+ async resolveObjectEvaluation<T extends JsonValue>(
+ key: string,
+ defaultValue: T,
+ context: EvaluationContext,
+ logger: Logger
+ ) {
+ this.maybeSync();
+ return this.evaluate(
+ key,
+ this.core.resolveObjectEvaluation(
+ key,
+ defaultValue,
+ this.withContext(context),
+ logger
+ )
+ );
+ }
+}
+
+declare global {
+ var __carbonFlags: CarbonFlagsProvider | undefined;
+}
+
+/**
+ * Sets the provider from `CARBON_FLAGS_ENDPOINT` and `CARBON_FLAGS_HEADERS`.
+ * Each app calls it once in `app/entry.server.tsx`; a second call (HMR, a warm
+ * lambda) does nothing. Until it resolves, every flag answers its default.
+ */
+export async function initFlags(
+ options: Pick<CarbonFlagsOptions, "store" | "waitUntil" | "onWarning"> = {}
+): Promise<void> {
+ if (globalThis.__carbonFlags) return;
+ const provider = new CarbonFlagsProvider({
+ endpoint: CARBON_FLAGS_ENDPOINT,
+ headers: CARBON_FLAGS_HEADERS,
+ commit: CARBON_COMMIT_SHA,
+ store: options.store,
+ waitUntil: options.waitUntil,
+ onWarning: options.onWarning,
+ tenancy: SINGLE_TENANT ? "single" : "multi",
+ edition: CarbonEdition
+ });
+ globalThis.__carbonFlags = provider;
+ await OpenFeature.setProviderAndWait(provider);
+}
+
+/**
+ * `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.
+ */
+export type FlagContext = { companyId: string; userId?: string };
+
+let client: Client | undefined;
+const getClient = () => {
+ client ??= OpenFeature.getClient();
+ return client;
+};
+
+const toContext = ({ companyId, userId }: FlagContext): EvaluationContext => ({
+ targetingKey: userId ?? companyId,
+ companyId,
+ ...(userId ? { userId } : {})
+});
+
+/**
+ * The only way code reads a flag. The default comes from the registry
+ * (`FLAGS`), so two call sites cannot disagree on it. Never throws.
+ */
+export const flags = {
+ bool: (key: FlagKey, context: FlagContext): Promise<boolean> =>
+ getClient().getBooleanValue(key, flagDefault(key), toContext(context))
+};
+
+/** The value of every flag with `browser: true`, for the layout loaders. */
+export async function evaluateBrowserFlags(
+ context: FlagContext
+): Promise<BrowserFlags> {
+ return Object.fromEntries(
+ await Promise.all(
+ BROWSER_FLAG_KEYS.map(async (key) => [
+ key,
+ await flags.bool(key, context)
+ ])
+ )
+ );
+}
diff --git a/packages/env/src/flags.ts b/packages/env/src/flags.ts
new file mode 100644
index 0000000000..dc0a08d6ef
--- /dev/null
+++ b/packages/env/src/flags.ts
@@ -0,0 +1,43 @@
+// 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.
+
+// The feature flag registry. Every flag the code reads is declared here once,
+// with the value the code uses when no flags source answers. This file is
+// safe for the browser: the evaluation lives in `./flags.server`. Flags are
+// booleans until one needs another type.
+
+type FlagDefinition = { default: boolean; browser: boolean };
+
+/**
+ * `default` is the safe value: what an instance does with no flags source,
+ * when the source has no such flag, or when the flag is DISABLED there.
+ * `browser: true` sends the evaluated value to React through the
+ * authenticated layout loader (`useFeatureFlags().feature(key)`).
+ */
+export const FLAGS = {
+ // Settings → Companies. Carbon staff keep access without it.
+ "multi-company-management": { default: false, browser: true },
+ // Install of an `internalOnly` integration on Carbon Cloud. Carbon staff
+ // keep access without it. Rules name the users and their company.
+ "integration-early-access": { default: false, browser: false }
+} as const satisfies Record<string, FlagDefinition>;
+
+type Flags = typeof FLAGS;
+
+export type FlagKey = keyof Flags;
+
+export type BrowserFlagKey = {
+ [K in FlagKey]: Flags[K]["browser"] extends true ? K : never;
+}[FlagKey];
+
+/** What the layout loaders send: the evaluated value of each browser flag. */
+export type BrowserFlags = Partial<Record<BrowserFlagKey, boolean>>;
+
+export function flagDefault(key: FlagKey): boolean {
+ return FLAGS[key].default;
+}
+
+export const BROWSER_FLAG_KEYS = (Object.keys(FLAGS) as FlagKey[]).filter(
+ (key) => FLAGS[key].browser
+) as BrowserFlagKey[];
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index b04c435ca2..e566236e42 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -133,10 +133,19 @@ export const SINGLE_TENANT = getEnv("TENANT_TYPE") === "single";
export const SYSTEM_STATUS_URL = getEnv("SYSTEM_STATUS_URL");
+// A fallback beside the `integration-early-access` flag until a flags source
+// is live (`hasIntegrationEarlyAccess`, `@carbon/ee/plan.server`).
export const INTEGRATION_EARLY_ACCESS_USER_IDS = getEnv(
"INTEGRATION_EARLY_ACCESS_USER_IDS"
);
+// Feature flags (`@carbon/env/flags.server`). Unset means every flag answers
+// its registry default.
+export const CARBON_FLAGS_ENDPOINT = getEnv("CARBON_FLAGS_ENDPOINT");
+export const CARBON_FLAGS_HEADERS = getEnv("CARBON_FLAGS_HEADERS");
+// The build's git commit: Vercel's VERCEL_GIT_COMMIT_SHA, or IMAGE_TAG on AWS.
+export const CARBON_COMMIT_SHA = getEnv("CARBON_COMMIT_SHA");
+
// Carbon GovCloud Rider metadata. These are the authoritative `docVersion` /
// `docHash` stamped onto every ITAR certification, and the target of the
// "View the full Rider" link. `ITAR_RIDER_SHA256` is the sha256 of the Rider PDF
diff --git a/packages/env/src/schema.ts b/packages/env/src/schema.ts
index 378ef136d0..678f372324 100644
--- a/packages/env/src/schema.ts
+++ b/packages/env/src/schema.ts
@@ -140,7 +140,25 @@ export const schema = define({
INTEGRATION_EARLY_ACCESS_USER_IDS: {
group: "core",
description:
- "Comma-separated user ids that can install Coming soon integrations on Cloud"
+ "Comma-separated user ids that can install Coming soon integrations on Cloud. A fallback beside the integration-early-access feature flag until a flags source is live"
+ },
+ CARBON_FLAGS_ENDPOINT: {
+ group: "core",
+ description:
+ "Feature flags document (flagd JSON): an https: URL to poll (http: only on localhost), or a data: URL loaded once",
+ type: url
+ },
+ CARBON_COMMIT_SHA: {
+ group: "core",
+ description:
+ "Git commit of this build, sent to the flags source as X-Carbon-Commit. Vercel sets it; AWS deploys forward IMAGE_TAG",
+ aliases: ["VERCEL_GIT_COMMIT_SHA"]
+ },
+ CARBON_FLAGS_HEADERS: {
+ group: "core",
+ description:
+ "Request headers for CARBON_FLAGS_ENDPOINT, as k=v pairs separated by commas (the OTEL headers format)",
+ secret: true
},
DEFAULT_LANGUAGE: {
group: "core",
diff --git a/packages/kv/AGENTS.md b/packages/kv/AGENTS.md
index 678ace2b22..ecb7d84a58 100644
--- a/packages/kv/AGENTS.md
+++ b/packages/kv/AGENTS.md
@@ -36,6 +36,7 @@ pnpm --filter @carbon/kv typecheck
| `Ratelimit.fixedWindow(tokens, window)` | Fixed window algorithm (simple, low memory) |
| `Ratelimit.slidingWindow(tokens, window)` | Sliding window (smoother, prevents boundary bursts) |
| `Ratelimit.tokenBucket(refillRate, interval, maxTokens?)` | Token bucket (allows controlled bursts) |
+| `redisFlagsStore` | The `FlagsStore` for `initFlags` (`@carbon/env/flags.server`): the shared flags document per source in the hash `flags:<scope>` (`body`, `etag`, `fetchedAt`, at most 1 MB) and the refresh lease `flags:<scope>:refresh` |
| `Duration` type | Time duration strings like `"10 s"`, `"1 m"`, `"1 h"` |
## Cross-References
diff --git a/packages/kv/src/flags-store.ts b/packages/kv/src/flags-store.ts
new file mode 100644
index 0000000000..d90c95d6b4
--- /dev/null
+++ b/packages/kv/src/flags-store.ts
@@ -0,0 +1,62 @@
+// 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 type { FlagsStore } from "@carbon/env/flags.server";
+import redis from "./client";
+import { acquireLease, releaseLease } from "./lease";
+
+// One hash per flags source (`scope` hashes the endpoint, the headers and the
+// flagd-core version): the
+// document every ERP and MES process of the instance shares. The provider
+// caps the document at 1 MB.
+const key = (scope: string) => `flags:${scope}`;
+
+// Every 200 and 304 refreshes it, so only a scope nothing reads any more (an
+// old token, a changed endpoint, a deleted worktree) runs out.
+const DOCUMENT_TTL_SECONDS = 24 * 60 * 60;
+
+// Long enough for one fetch from the source (5 s timeout) and the write.
+const REFRESH_LEASE_MS = 10_000;
+
+/**
+ * The Redis `FlagsStore` for `initFlags` (`@carbon/env/flags.server`). Reads
+ * answer null on a miss and when Redis is down (the client fails soft);
+ * `tryLease` answers "unavailable" when Redis is down, and the provider then
+ * fetches the source itself.
+ */
+export const redisFlagsStore: FlagsStore = {
+ async readMeta(scope) {
+ const [etag, fetchedAt] = (await redis.hmget(
+ key(scope),
+ "etag",
+ "fetchedAt"
+ )) ?? [null, null];
+ if (!etag || !fetchedAt) return null;
+ return { etag, fetchedAt: Number(fetchedAt) };
+ },
+
+ async readBody(scope) {
+ return redis.hget(key(scope), "body");
+ },
+
+ async write(scope, value) {
+ const fields: Record<string, string> = {
+ fetchedAt: String(value.fetchedAt)
+ };
+ if (value.body !== undefined) fields.body = value.body;
+ if (value.etag !== undefined) fields.etag = value.etag;
+ await redis.hset(key(scope), fields);
+ await redis.expire(key(scope), DOCUMENT_TTL_SECONDS);
+ },
+
+ async tryLease(scope) {
+ const leaseKey = `${key(scope)}:refresh`;
+ const lease = await acquireLease(leaseKey, REFRESH_LEASE_MS);
+ if (lease.status !== "acquired") return lease;
+ return {
+ status: "acquired",
+ release: () => releaseLease(leaseKey, lease.owner)
+ };
+ }
+};
diff --git a/packages/kv/src/index.ts b/packages/kv/src/index.ts
index 637d73285e..a04538f3b0 100644
--- a/packages/kv/src/index.ts
+++ b/packages/kv/src/index.ts
@@ -4,6 +4,7 @@
import redis from "./client";
+export { redisFlagsStore } from "./flags-store";
export type { LeaseAcquisition } from "./lease";
export { acquireLease, releaseLease, renewLease, withLease } from "./lease";
export type {
diff --git a/packages/react/package.json b/packages/react/package.json
index 497cb34181..055106c1ba 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -3,6 +3,7 @@
"dependencies": {
"@base-ui/react": "1.6.0",
"@carbon/content": "workspace:*",
+ "@carbon/env": "workspace:*",
"@carbon/files": "workspace:*",
"@carbon/logger": "workspace:*",
"@carbon/tiptap": "workspace:*",
@@ -75,7 +76,6 @@
"devDependencies": {
"@carbon/config": "workspace:*",
"@carbon/database": "workspace:*",
- "@carbon/env": "workspace:*",
"@radix-ui/react-avatar": "1.1.11",
"@react-types/button": "3.15.1",
"@react-types/calendar": "3.8.3",
diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
index 6599b5b90a..98037f9787 100644
--- a/packages/react/src/hooks/index.ts
+++ b/packages/react/src/hooks/index.ts
@@ -7,6 +7,7 @@ import useDebounce from "./useDebounce";
import useDisclosure from "./useDisclosure";
import { useEdition } from "./useEdition";
import useEscape from "./useEscape";
+import { useFeatureFlags } from "./useFeatureFlags";
import useHydrated from "./useHydrated";
import { useIdle } from "./useIdle";
import useInitialDimensions from "./useInitialDimenions";
@@ -42,6 +43,7 @@ export {
useDisclosure,
useEdition,
useEscape,
+ useFeatureFlags,
useHydrated,
useIdle,
useInitialDimensions,
diff --git a/packages/react/src/hooks/useFeatureFlags.tsx b/packages/react/src/hooks/useFeatureFlags.tsx
new file mode 100644
index 0000000000..04304c7cfb
--- /dev/null
+++ b/packages/react/src/hooks/useFeatureFlags.tsx
@@ -0,0 +1,22 @@
+// 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 {
+ type BrowserFlagKey,
+ type BrowserFlags,
+ flagDefault
+} from "@carbon/env/flags";
+import { useRouteData } from "./useRouteData";
+
+/**
+ * The feature flags the authenticated layout loader (`/x`) evaluated for this
+ * user and company. The ERP sends them; the MES sends none yet, so there
+ * `feature(key)` answers the flag's registry default (`@carbon/env/flags`).
+ */
+export function useFeatureFlags() {
+ const flags = useRouteData<{ flags?: BrowserFlags }>("/x")?.flags;
+ return {
+ feature: (key: BrowserFlagKey): boolean => flags?.[key] ?? flagDefault(key)
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f63ab6ff70..fad19a1321 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -69,6 +69,15 @@ catalogs:
'@medicomind/rolldown-compression':
specifier: 2.5.3
version: 2.5.3
+ '@openfeature/core':
+ specifier: 1.12.0
+ version: 1.12.0
+ '@openfeature/flagd-core':
+ specifier: 5.0.0
+ version: 5.0.0
+ '@openfeature/server-sdk':
+ specifier: 1.23.0
+ version: 1.23.0
'@opentelemetry/api':
specifier: 1.9.0
version: 1.9.0
@@ -1207,6 +1216,9 @@ importers:
'@carbon/ee':
specifier: workspace:*
version: link:../../packages/ee
+ '@carbon/env':
+ specifier: workspace:*
+ version: link:../../packages/env
'@carbon/files':
specifier: workspace:*
version: link:../../packages/files
@@ -1670,6 +1682,15 @@ importers:
ci:
dependencies:
+ '@carbon/env':
+ specifier: workspace:*
+ version: link:../packages/env
+ '@openfeature/core':
+ specifier: 'catalog:'
+ version: 1.12.0
+ '@openfeature/flagd-core':
+ specifier: 'catalog:'
+ version: 5.0.0(@openfeature/[email protected])
'@supabase/supabase-js':
specifier: 'catalog:'
version: 2.117.2(@opentelemetry/[email protected])
@@ -2640,9 +2661,6 @@ importers:
'@modelcontextprotocol/client':
specifier: 2.3.1
version: 2.3.1
- '@slack/types':
- specifier: 2.20.1
- version: 2.20.1
'@supabase/supabase-js':
specifier: 'catalog:'
version: 2.117.2(@opentelemetry/[email protected])
@@ -2682,6 +2700,15 @@ importers:
'@carbon/utils':
specifier: workspace:*
version: link:../utils
+ '@openfeature/core':
+ specifier: 'catalog:'
+ version: 1.12.0
+ '@openfeature/flagd-core':
+ specifier: 'catalog:'
+ version: 5.0.0(@openfeature/[email protected])
+ '@openfeature/server-sdk':
+ specifier: 'catalog:'
+ version: 1.23.0(@openfeature/[email protected])
zod:
specifier: 'catalog:'
version: 4.6.6
@@ -3465,6 +3492,9 @@ importers:
'@carbon/content':
specifier: workspace:*
version: link:../../docs/content
+ '@carbon/env':
+ specifier: workspace:*
+ version: link:../env
'@carbon/files':
specifier: workspace:*
version: link:../files
@@ -3697,9 +3727,6 @@ importers:
'@carbon/database':
specifier: workspace:*
version: link:../database
- '@carbon/env':
- specifier: workspace:*
- version: link:../env
'@radix-ui/react-avatar':
specifier: 1.1.11
@@ -6176,6 +6203,20 @@ packages:
'@one-ini/[email protected]':
resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==}
+ '@openfeature/[email protected]':
+ resolution: {integrity: sha512-7PCPzyd1OC19begz30+CRknFB0ChtyaZUhk7YWrk+Bov1fpVw0HYkTXtoxxsvPfDZB9P9WsT7uixN+Z8f9+bcA==}
+
+ '@openfeature/[email protected]':
+ resolution: {integrity: sha512-efrtGMK3CO66/GAzGaRV2PnRkCgI4LtISrEg3WbT9PcNM0Dl73QHUOrzzI05dXE4Jf//ex0uh11KdNE1HHkgPw==}
+ peerDependencies:
+ '@openfeature/core': '>=1.6.0'
+
+ '@openfeature/[email protected]':
+ resolution: {integrity: sha512-JWeLvltJIV0AFgOfbw7hK9b9Rw/5wWq+RMhCIU9sJtAqarxr8hSPglG+JAGGhYdElAz3Qwe9W3ApWyPNkQEyqg==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ '@openfeature/core': ^1.12.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==}
engines: {node: '>=8.0.0'}
@@ -12790,6 +12831,10 @@ packages:
resolution: {integrity: sha512-pYkiyXVL2Mf3pozdlDGV6NAObxQx13Ae8knZk1UJRJ6uRW/ZRmTGHlQYtrsSl7ubuE5F8CD1z+s1n4RHNuTtuA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
+ engines: {node: '>=0.8.19'}
+
resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
engines: {node: '>=8'}
@@ -13221,6 +13266,10 @@ packages:
resolution: {integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==}
+ resolution: {integrity: sha512-Q7L18Ds60urcXPfw2yNJgE21zJOqvoBvVLLHnvzH3NR1GfFeoDu+YxCdLsHBNYiWzO5UAsv3T77VaUVeslmbrA==}
+ engines: {node: '>=12.22.7'}
+
resolution: {integrity: sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==}
@@ -19051,6 +19100,20 @@ snapshots:
'@one-ini/[email protected]': {}
+ '@openfeature/[email protected]': {}
+
+ '@openfeature/[email protected](@openfeature/[email protected])':
+ dependencies:
+ '@openfeature/core': 1.12.0
+ imurmurhash: 0.1.4
+ json-logic-engine: 5.0.7
+ object-hash: 3.0.0
+ semver: 7.7.4
+
+ '@openfeature/[email protected](@openfeature/[email protected])':
+ dependencies:
+ '@openfeature/core': 1.12.0
+
'@opentelemetry/[email protected]':
dependencies:
'@opentelemetry/api': 1.9.0
@@ -27024,6 +27087,8 @@ snapshots:
cjs-module-lexer: 2.2.0
module-details-from-path: 1.0.4
+
@@ -27500,6 +27565,8 @@ snapshots:
dependencies:
bignumber.js: 9.3.1
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 191c8d08a9..8441a91f89 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -92,6 +92,9 @@ catalog:
'@orpc/openapi': 1.15.0
'@orpc/openapi-client': 1.15.0
'@orpc/server': 1.15.0
+ '@openfeature/core': 1.12.0
+ '@openfeature/flagd-core': 5.0.0
+ '@openfeature/server-sdk': 1.23.0
'@opentelemetry/api': 1.9.0
'@opentelemetry/exporter-trace-otlp-proto': 0.223.0
'@opentelemetry/instrumentation': 0.223.0
diff --git a/sst.config.ts b/sst.config.ts
index 4377a29e71..e35ffc0e45 100644
--- a/sst.config.ts
+++ b/sst.config.ts
@@ -69,6 +69,8 @@ export default $config({
DOMAIN: process.env.DOMAIN ?? "carbon.ms",
MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,
SYSTEM_STATUS_URL: process.env.SYSTEM_STATUS_URL,
+ CARBON_FLAGS_ENDPOINT: process.env.CARBON_FLAGS_ENDPOINT,
+ CARBON_COMMIT_SHA: process.env.IMAGE_TAG,
ERP_URL: process.env.URL_ERP ? `https://${process.env.URL_ERP}` : "https://itar.carbon.ms",
EXCHANGE_RATES_API_KEY: process.env.EXCHANGE_RATES_API_KEY,
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
@@ -189,6 +191,8 @@ export default $config({
DOMAIN: process.env.DOMAIN ?? "carbon.ms",
MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,
SYSTEM_STATUS_URL: process.env.SYSTEM_STATUS_URL,
+ CARBON_FLAGS_ENDPOINT: process.env.CARBON_FLAGS_ENDPOINT,
+ CARBON_COMMIT_SHA: process.env.IMAGE_TAG,
ERP_URL: process.env.URL_ERP ? `https://${process.env.URL_ERP}` : "https://itar.carbon.ms",
EXCHANGE_RATES_API_KEY: process.env.EXCHANGE_RATES_API_KEY,
INNGEST_BASE_URL: process.env.INNGEST_BASE_URL,