Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Environment variables: one schema and a grouped startup report (#1860)
Sid9d668ea5a552
diff --git a/.ai/plans/2026-10-07-env-schema.md b/.ai/plans/2026-10-07-env-schema.mdnew file mode 100644index 0000000000..61626033cc--- /dev/null+++ b/.ai/plans/2026-10-07-env-schema.md@@ -0,0 +1,51 @@+# Environment schema — one declaration, clear startup report++Goal: one schema in `@carbon/env`, a grouped startup report, and no Vercel- or+Supabase-specific names in app logic — without changing what any deployment has+to set. Audit taken at `59ed755d52`, re-verified at `c1b539854c`.++## Rules that keep every deployment booting++1. New names fall back to old ones, inside `@carbon/env` only.+2. The report lists everything, but only exits on what exits today+ (`SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_DB_URL`, `SESSION_SECRET`,+ `REDIS_URL`, `INNGEST_SIGNING_KEY` / `INNGEST_EVENT_KEY` unless+ `INNGEST_DEV`). Newly required variables are warnings for one release.+3. A test pins what each real deployment sets and asserts no startup error.+4. A derived OAuth callback never overrides a variable that is set.++## PR 1 — schema, reporter, aliases (no behaviour change)++- [x] `packages/env/src/schema.ts`: every variable once (type, group,+ description, secret, browser, required level, aliases)+- [x] `packages/env/src/validate.ts`: `validateEnv` + `formatReport`, pure+- [x] `index.ts` reads through the schema; named exports unchanged+- [x] `APP_URL` (← `VERCEL_URL`), `APP_ENV` (← `VERCEL_ENV`), `DATABASE_URL`+ (← `SUPABASE_DB_URL`); old exports stay+- [x] `Window.env` type and `getBrowserEnv()` checked against the browser flag+- [x] Reporter tests + deployment test (SST, `crbn up`)+- [x] Deployment test for Vercel (`carbon` and `mes` projects, names read with+ the Vercel CLI on 2026-10-07)+- [ ] Deployment test for the BYOC chart — the chart is not in this repository++## PR 2 — move direct `process.env` reads++- [ ] The direct-only variables into the schema (AI, Resend, Inngest URLs,+ QuickBooks/Xero redirect, `GIT_COMMIT_SHA`, sweep and dev variables)+- [ ] Call sites off `VERCEL_URL` / `VERCEL_ENV` onto `APP_URL` / `APP_ENV`+- [ ] One `DATABASE_URL` precedence in `packages/checks` and `packages/database`+- [ ] Derive the four live OAuth callbacks from the ERP origin when unset+- [ ] `packages/dev/src/env.ts` and `sst.config.ts` write the new names+- [ ] Biome `noProcessEnv` with the exempt list++## PR 3 — housekeeping++- [ ] Generate `.env.example` from the schema + a staleness check+- [ ] Build-affecting variables in `turbo.json`+- [ ] Remove dead exports; move non-env constants out of the env file++## Follow-up release++- [ ] Flip `required: "warn"` and half-configured features to startup errors+- [ ] Remove aliases: `VERCEL_URL`, `VERCEL_ENV`, `SUPABASE_DB_URL`,+ `OPENAI_API_KEY`, `VERCEL_GIT_COMMIT_SHA`, the old QuickBooks webhook namediff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.mdindex 5f69397ea2..fc47699f1c 100644--- a/.claude/rules/environment-configuration.md+++ b/.claude/rules/environment-configuration.md@@ -23,12 +23,23 @@ both resolve here. Prefer importing the exported constant over readingimport { SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY } from "@carbon/auth";```-`getEnv(name, { isRequired = true, isSecret = true })` is the accessor:-- Throws `${name} is not set` when a required var is missing (validation happens- at module load, so a missing required var crashes app boot).-- When `isSecret` and running in the browser, returns `""` (secrets never reach- client code).-- Server reads `process.env`; browser reads `window.env`.+Every variable is declared once in `packages/env/src/schema.ts`: group, one-line+description, optional zod `type`, `secret`, `browser`, `required` and `aliases`.+`getEnv(name)` reads one — its own name first, then its deprecated aliases+(`APP_URL` ← `VERCEL_URL`, `APP_ENV` ← `VERCEL_ENV`, `DATABASE_URL` ←+`SUPABASE_DB_URL`, `AI_API_KEY` ← `OPENAI_API_KEY`).+- Server reads `process.env`; browser reads `window.env`, and a `secret`+ variable reads as `""` there.+- `validateEnv` (`validate.ts`) runs once at module load on the server and+ `formatReport` prints every problem together, grouped as Required, Invalid and+ half-configured features, plus the features that are off. A secret's value is+ never printed.+- `required: "error"` throws that report. `required: "warn"`, an invalid type and+ a half-configured feature (some of a group's `needed` variables set, not all)+ are only printed for now and become errors in the next release.+- Not validated under Vitest or with `SKIP_ENV_VALIDATION` set.+- `src/deployments.test.ts` reads what `sst.config.ts` and `crbn up` set and+ fails when either would hit a startup error.`window.env` is populated by `getBrowserEnv()`, injected via an inline script ineach app's `root.tsx` (`apps/erp/app/root.tsx`, `apps/mes/app/root.tsx`). Only the@@ -118,7 +129,7 @@ checked against the caller's company and user). Managed deployment propagates bovars through `ci/src/deploy.ts` → `sst.config.ts` → the ERP service only.**Analytics / config** — `POSTHOG_API_HOST`, `POSTHOG_PROJECT_PUBLIC_KEY`-(required, public), `CARBON_EDITION` (`community|cloud|enterprise|test` →+(optional, public), `CARBON_EDITION` (`community|cloud|enterprise|test` →`CarbonEdition`), `CONTROLLED_ENVIRONMENT` (ITAR flag), `DEFAULT_LANGUAGE`(default `en`), `GTM_URL`, `GTM_EVENTS_API_SECRET_KEY`.@@ -130,8 +141,9 @@ the OTel SDK (not `@carbon/env`): `OTEL_EXPORTER_OTLP_ENDPOINT` (orUnset = no tracing. See `packages/logger/AGENTS.md` → Tracing. The Rust assemblerreads the same variables (`apps/assembler/AGENTS.md` → Tracing).-**Deployment** — `VERCEL_URL` (required at module load; value unused off-Vercel,-set to `production` in prod compose), `VERCEL_ENV`, `NODE_ENV`. `ERP_URL` /+**Deployment** — `APP_URL` (this app's own origin, optional; `VERCEL_URL` is its+deprecated alias), `APP_ENV` (`production | preview | development`; alias+`VERCEL_ENV`, defaults to `NODE_ENV`), `NODE_ENV`. `ERP_URL` /`MES_URL` drive `getAppUrl()` / `getMESUrl()`.## URL resolution@@ -144,14 +156,17 @@ set to `production` in prod compose), `VERCEL_ENV`, `NODE_ENV`. `ERP_URL` /## Gotchas-- Required-var validation runs at **module load** — a missing `SUPABASE_URL`,- `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_DB_URL`, `REDIS_URL`, `SESSION_SECRET`,- `POSTHOG_*`, or `VERCEL_URL` crashes boot, not lazily at first use.+- Validation runs at **module load**. Missing `SUPABASE_SERVICE_ROLE_KEY`,+ `DATABASE_URL` (or `SUPABASE_DB_URL`), `REDIS_URL`, `SESSION_SECRET`, or the+ Inngest keys without `INNGEST_DEV`, stops boot. Missing `SUPABASE_URL`,+ `SUPABASE_ANON_KEY`, and outside Cloud in production `ERP_URL`, `MES_URL` and+ `SMTP_FROM`, is a warning for now. `POSTHOG_*` and `APP_URL` are optional.- Email is deliberately lazy: `packages/lib/src/email.server.ts` builds theSMTP transport on first send, never at import, so a deployment with no mailconfig boots fine and `sendEmail` no-ops.- Only keys in `getBrowserEnv()` reach the client; adding a public var means- adding it there AND to the `Window.env` interface declaration.+ `browser: true` in the schema, adding it there (typecheck enforces this), AND+ adding it to each app's root-loader `env` object.- Don't put ports/URLs/Supabase/Redis/Inngest dev values in `.env` — `crbn up`owns them via `.env.local`, which overrides `.env`.diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.mdindex fb3b9db16d..b3558dda52 100644--- a/packages/env/AGENTS.md+++ b/packages/env/AGENTS.md@@ -5,13 +5,15 @@ Single source of truth for all environment variable access. Validates at module## Always- Import env constants from `@carbon/env` (or `@carbon/auth` which re-exports it) — never read `process.env` directly.-- Use `getEnv(name, { isRequired, isSecret })` for any new env var. `isSecret: true` returns `""` in browser context.-- Add browser-safe vars to both the export AND `getBrowserEnv()` + the `Window.env` interface declaration.-- Required vars crash at **module load** if missing — verify `.env` / `.env.local` has them before boot.+- Declare a new variable once in `src/schema.ts` (group, description, `type`, `secret`, `browser`, `required`, `aliases`), then export it from `src/index.ts` with `getEnv("NAME")`. `secret: true` reads as `""` in the browser.+- A `browser: true` variable must also be returned by `getBrowserEnv()` — the `satisfies` there fails typecheck until it is — AND added to each app's root-loader `env` object. The `Window.env` type is derived from the schema.+- `validateEnv` runs once at **module load** on the server and reports every problem together (`formatReport`). `required: "error"` stops startup; `required: "warn"`, an invalid type and a half-configured feature are printed and become errors in the next release.+- Rename a variable by adding the old name to the new one's `aliases`; keep the old export as a `@deprecated` constant.+- Tests are not validated (`VITEST`); mock the module or stub `process.env`. `SKIP_ENV_VALIDATION=1` does the same for a script.## Ask First-- Adding new required env vars — this changes boot requirements for all environments (dev, CI, prod).+- Adding a `required: "error"` variable, or flipping `"warn"` to `"error"` — this changes boot requirements for every deployment. `src/deployments.test.ts` must pass for each of them first.- Changing `getAppUrl()` / `getMESUrl()` resolution logic — affects cross-app links across all editions.## Never@@ -24,14 +26,17 @@ Single source of truth for all environment variable access. Validates at module```bashpnpm --filter @carbon/env typecheck+pnpm --filter @carbon/env test```## Key Exports-All from `src/index.ts` (single file):+`src/schema.ts` declares the variables, `src/validate.ts` checks and reports them, `src/index.ts` exports the values:-- **`getEnv(name, opts)`** — accessor with required/secret validation-- **Supabase:** `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_DB_URL`, `SUPABASE_JWT_SECRET`+- **`schema`, `validateEnv(source)`, `formatReport(report)`** — the declaration and the startup report+- **`getEnv(name)`** — reads one schema variable (its own name, then its aliases)+- **Deployment:** `APP_URL` (this app's origin; alias `VERCEL_URL`), `APP_ENV` (alias `VERCEL_ENV`, defaults to `NODE_ENV`)+- **Database / Supabase:** `DATABASE_URL` (alias `SUPABASE_DB_URL`), `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_JWT_SECRET`- **Redis/Jobs:** `REDIS_URL`, `INNGEST_SIGNING_KEY`, `INNGEST_EVENT_KEY`- **Auth:** `SESSION_SECRET`, `SESSION_MAX_AGE`, `RATE_LIMIT`, `AUTH_PROVIDERS`, `isAuthProviderEnabled()`- **Edition:** `CarbonEdition` (Community/Cloud/Enterprise/Test), `CONTROLLED_ENVIRONMENT` (ITAR flag)diff --git a/packages/env/package.json b/packages/env/package.jsonindex 9c1e3a5a54..df7d760308 100644--- a/packages/env/package.json+++ b/packages/env/package.json@@ -12,14 +12,17 @@"scripts": {"clean": "rimraf .turbo node_modules","lint": "biome lint --fix",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsgo --noEmit",+ "test": "vitest run"},"dependencies": {"@carbon/utils": "workspace:*",- "@types/node": "20.19.39"+ "@types/node": "20.19.39",+ "zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",- "typescript": "catalog:"+ "typescript": "catalog:",+ "vitest": "catalog:"}}diff --git a/packages/env/src/deployments.test.ts b/packages/env/src/deployments.test.tsnew file mode 100644index 0000000000..23e6a5e1e6--- /dev/null+++ b/packages/env/src/deployments.test.ts@@ -0,0 +1,51 @@+// 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 { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";+import { validateEnv } from "./validate";+import vercel from "./vercel-production.json";++// What each real deployment sets today, read from the file that sets it. A+// variable that starts stopping startup must already be set by all of them.+const root = new URL("../../../", import.meta.url);+const read = (path: string) => readFileSync(new URL(path, root), "utf8");+const set = (keys: Iterable<string>) =>+ Object.fromEntries([...keys].map((key) => [key, "set"]));+const errors = (env: Record<string, string>) =>+ validateEnv(env)+ .problems.filter((p) => p.level === "error")+ .map((p) => p.name);++describe("deployments keep starting", () => {+ const services = read("sst.config.ts").split("environment: {").slice(1);++ it.each(+ ["erp", "mes"].map((name, i) => [name, services[i]])+ )("SST %s service", (_, block = "") => {+ const keys = [+ ...(block.split("\n },")[0] ?? "").matchAll(/^\s+([A-Z0-9_]+):/gm)+ ];+ expect(keys.length).toBeGreaterThan(20);+ expect(errors(set(keys.map((m) => m[1] as string)))).toEqual([]);+ });++ it("local crbn up", () => {+ const written = read("packages/dev/src/env.ts").matchAll(+ /[`"]([A-Z0-9_]+)=/g+ );+ const example = read(".env.example").matchAll(/^([A-Z0-9_]+)=/gm);+ const keys = [...written, ...example].map((m) => m[1] as string);+ expect(keys).toContain("SUPABASE_DB_URL");+ expect(errors(set(keys))).toEqual([]);+ });++ // Names only, from `vercel env ls production` plus the team's shared+ // variables, on 2026-10-07. Vercel itself adds NODE_ENV at runtime.+ it.each(Object.entries(vercel))("Vercel %s project", (_, keys) => {+ expect(errors(set([...keys, "NODE_ENV"]))).toEqual([]);+ });++ it.todo("BYOC Helm chart: the chart is not in this repository");+});diff --git a/packages/env/src/index.test.ts b/packages/env/src/index.test.tsnew file mode 100644index 0000000000..c8b3c14c7e--- /dev/null+++ b/packages/env/src/index.test.ts@@ -0,0 +1,49 @@+// 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 { afterEach, describe, expect, it, vi } from "vitest";++afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ vi.doUnmock("@carbon/utils");+ vi.resetModules();+});++describe("module load", () => {+ it("stops a server with one report of everything missing", async () => {+ vi.stubEnv("VITEST", "");+ vi.stubEnv("SESSION_SECRET", "");+ vi.stubEnv("REDIS_URL", "");+ await expect(import("./index")).rejects.toThrow(+ /Carbon can't start[\s\S]*REDIS_URL[\s\S]*SESSION_SECRET/+ );+ });++ it("never throws in the browser, and keeps secrets out", async () => {+ vi.doMock("@carbon/utils", async (original) => ({+ ...(await original<typeof import("@carbon/utils")>()),+ isBrowser: true+ }));+ vi.stubGlobal("window", {+ env: { VERCEL_URL: "https://erp.test", SESSION_SECRET: "leaked" }+ });+ const env = await import("./index");+ expect(env.APP_URL).toBe("https://erp.test");+ expect(env.SESSION_SECRET).toBe("");+ expect(env.SUPABASE_URL).toBeUndefined();+ });++ it.each([+ ["carbon-git-x.vercel.app", "https://carbon-git-x.vercel.app"],+ ["https://preview.example.com", "https://preview.example.com"]+ ])("a preview URL from %s has one scheme", async (url, expected) => {+ vi.stubEnv("APP_ENV", "preview");+ vi.stubEnv("NODE_ENV", "development");+ vi.stubEnv("APP_URL", url);+ const env = await import("./index");+ expect(env.getAppUrl()).toBe(expected);+ expect(env.getMESUrl()).toBe(expected);+ });+});diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex cd12b6016b..5a57168207 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -4,119 +4,46 @@/// <reference types="node" />import { Edition, isBrowser, parseBoolean } from "@carbon/utils";+import { type BrowserEnvName, type EnvName, resolve, schema } from "./schema";+import { formatReport, validateEnv } from "./validate";++export { schema } from "./schema";+export { formatReport, validateEnv } from "./validate";++// VERCEL_URL and VERCEL_ENV are the deprecated names of APP_URL and APP_ENV;+// the root loaders and cached browser bundles still use them.+type BrowserEnv = Record<+ | BrowserEnvName+ | "CARBON_SLACK_ENABLED"+ | "STRIPE_CONNECT_ENABLED"+ | "VERCEL_URL"+ | "VERCEL_ENV",+ string+>;declare global {interface Window {- env: {- AUTH_PROVIDERS: string;- CARBON_EDITION: string;- CARBON_API_URL: string;- CARBON_SLACK_ENABLED: string;- STRIPE_CONNECT_ENABLED: string;- CONTROLLED_ENVIRONMENT: string;- ERP_URL: string;- JIRA_CLIENT_ID: string;- LOG_LEVEL: string;- MES_URL: string;- NODE_ENV: string;- ONSHAPE_CLIENT_ID: string;- POSTHOG_API_HOST: string;- POSTHOG_PROJECT_PUBLIC_KEY: string;- RAMP_CLIENT_ID: string;- SUPABASE_URL: string;- SUPABASE_ANON_KEY: string;- VERCEL_URL: string;- VERCEL_ENV: string;- QUICKBOOKS_CLIENT_ID: string;- XERO_CLIENT_ID: string;- DEFAULT_LANGUAGE: string;- };+ env: BrowserEnv;}}-declare global {- namespace NodeJS {- interface ProcessEnv {- CARBON_EDITION: string;- CARBON_API_URL: string;- CLOUDFLARE_TURNSTILE_SITE_KEY: string;- CLOUDFLARE_TURNSTILE_SECRET_KEY: string;- DOMAIN: string;- ERP_URL: string;- JIRA_CLIENT_ID: string;- JIRA_CLIENT_SECRET: string;- JIRA_OAUTH_REDIRECT_URL: string;- JIRA_STATE_SECRET: string;- LOG_LEVEL: string;- MES_URL: string;- ONSHAPE_CLIENT_ID: string;- ONSHAPE_CLIENT_SECRET: string;- ONSHAPE_OAUTH_REDIRECT_URL: string;- POSTHOG_API_HOST: string;- POSTHOG_PROJECT_PUBLIC_KEY: string;- QUICKBOOKS_CLIENT_SECRET: string;- QUICKBOOKS_ENVIRONMENT: string;- QUICKBOOKS_WEBHOOK_SECRET: string;- RESEND_API_KEY: string;- SESSION_SECRET: string;- SESSION_KEY: string;- SESSION_ERROR_KEY: string;- SLACK_CLIENT_ID: string;- SLACK_CLIENT_SECRET: string;- SLACK_OAUTH_REDIRECT_URL: string;- SLACK_SIGNING_SECRET: string;- SLACK_STATE_SECRET: string;- SMTP_FROM: string;- SMTP_HOST: string;- SMTP_PASSWORD: string;- SMTP_PORT: string;- SMTP_USER: string;- STRIPE_SECRET_KEY: string;- STRIPE_WEBHOOK_SECRET: string;- STRIPE_CONNECT_WEBHOOK_SECRET: string;- STRIPE_BYPASS_COMPANY_IDS: string;- STRIPE_BYPASS_USER_IDS: string;- GTM_URL: string;- GTM_EVENTS_API_SECRET_KEY: string;- SUPABASE_ANON_KEY: string;- SUPABASE_URL: string;- SUPABASE_DB_URL: string;- SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID: string;- SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID: string;- SUPABASE_SERVICE_ROLE_KEY: string;- REDIS_URL: string;- VERCEL_URL: string;- VERCEL_ENV: string;- INNGEST_SIGNING_KEY: string;- INNGEST_EVENT_KEY: string;- XERO_CLIENT_SECRET: string;- XERO_WEBHOOK_SECRET: string;- DEFAULT_LANGUAGE: string;- EXTRACTION_CONFIDENCE_THRESHOLD: string;- }- }+const source: Record<string, string | undefined> =+ (isBrowser ? window.env : process.env) ?? {};++// One report for the whole environment, once per process. The browser never+// validates. Tests supply values by mocking this module or stubbing+// process.env; SKIP_ENV_VALIDATION does the same for a script that must run+// without a full environment.+if (!isBrowser && !source.VITEST && !source.SKIP_ENV_VALIDATION) {+ const report = validateEnv(source);+ if (report.fatal) throw new Error(formatReport(report));+ // biome-ignore lint/suspicious/noConsole: @carbon/logger depends on this package+ if (report.problems.length) console.warn(formatReport(report));}-type EnvOptions = {- isSecret?: boolean;- isRequired?: boolean;-};--export function getEnv(- name: string,- { isRequired, isSecret }: EnvOptions = { isRequired: true, isSecret: true }-) {- if (isBrowser && isSecret) return "";-- const source = (isBrowser ? window.env : process.env) ?? {};-- const value = source[name as keyof typeof source];-- if (!value && isRequired) {- throw new Error(`${name} is not set`);- }-- return value;+export function getEnv(name: EnvName) {+ if (isBrowser && "secret" in schema[name]) return "";+ return resolve(source, name);}/**@@ -125,25 +52,15 @@ export function getEnv(export type AuthProvider = "email" | "google" | "azure" | "passkey" | "sso";-export const AUTH_PROVIDERS =- getEnv("AUTH_PROVIDERS", {- isRequired: false,- isSecret: false- }) ?? "email,google,azure";+export const AUTH_PROVIDERS = getEnv("AUTH_PROVIDERS") ?? "email,google,azure";export function isAuthProviderEnabled(provider: AuthProvider) {const AUTH_PROVIDERS_LIST = AUTH_PROVIDERS.split(",").map((p) => p.trim());return AUTH_PROVIDERS_LIST.includes(provider);}-export const BINDERY_PRESS_API_KEY = getEnv("BINDERY_PRESS_API_KEY", {- isRequired: false,- isSecret: true-});+export const BINDERY_PRESS_API_KEY = getEnv("BINDERY_PRESS_API_KEY");-const CARBON_EDITION = getEnv("CARBON_EDITION", {- isRequired: false,- isSecret: false-});+const CARBON_EDITION = getEnv("CARBON_EDITION");const getEdition = () => {if (CARBON_EDITION === "cloud") {@@ -161,80 +78,42 @@ const getEdition = () => {export const CarbonEdition = getEdition();export const CARBON_API_URL =- getEnv("CARBON_API_URL", {- isRequired: false,- isSecret: false- }) ?? getEnv("SUPABASE_URL", { isSecret: false });+ getEnv("CARBON_API_URL") ?? getEnv("SUPABASE_URL");-export const DOMAIN = getEnv("DOMAIN", { isRequired: false }); // preview environments need no domain+export const DOMAIN = getEnv("DOMAIN"); // preview environments need no domain-export const EXCHANGE_RATES_API_KEY = getEnv("EXCHANGE_RATES_API_KEY", {- isRequired: false,- isSecret: true-});+export const EXCHANGE_RATES_API_KEY = getEnv("EXCHANGE_RATES_API_KEY");export const EXTRACTION_CONFIDENCE_THRESHOLD = Number.parseFloat(- getEnv("EXTRACTION_CONFIDENCE_THRESHOLD", {- isRequired: false,- isSecret: false- }) ?? "0.85"+ getEnv("EXTRACTION_CONFIDENCE_THRESHOLD") ?? "0.85");-const INNGEST_DEV = getEnv("INNGEST_DEV", { isRequired: false });--export const INNGEST_SIGNING_KEY = getEnv("INNGEST_SIGNING_KEY", {- isRequired: !INNGEST_DEV,- isSecret: true-});-export const INNGEST_EVENT_KEY = getEnv("INNGEST_EVENT_KEY", {- isRequired: !INNGEST_DEV,- isSecret: true-});--export const ERP_URL =- getEnv("ERP_URL", { isRequired: false, isSecret: false }) ??- "https://app.carbon.ms";-export const MES_URL =- getEnv("MES_URL", { isRequired: false, isSecret: false }) ??- "https://mes.carbon.ms";--export const ASSEMBLER_SERVICE_URL = getEnv("ASSEMBLER_SERVICE_URL", {- isRequired: false-});+export const INNGEST_SIGNING_KEY = getEnv("INNGEST_SIGNING_KEY");+export const INNGEST_EVENT_KEY = getEnv("INNGEST_EVENT_KEY");++export const ERP_URL = getEnv("ERP_URL") ?? "https://app.carbon.ms";+export const MES_URL = getEnv("MES_URL") ?? "https://mes.carbon.ms";++export const ASSEMBLER_SERVICE_URL = getEnv("ASSEMBLER_SERVICE_URL");// Dev-only (crbn-written): local kong port for the storage-URL rewrite in// internalizeStorageUrl. Unset in prod.-export const PORT_API = getEnv("PORT_API", {- isRequired: false,- isSecret: false-});-export const ASSEMBLER_SERVICE_API_KEY = getEnv("ASSEMBLER_SERVICE_API_KEY", {- isRequired: false,- isSecret: true-});+export const PORT_API = getEnv("PORT_API");+export const ASSEMBLER_SERVICE_API_KEY = getEnv("ASSEMBLER_SERVICE_API_KEY");// Cap on concurrently running assembler-backed Inngest functions (shared across// optimize/compact/convert/plan). Must stay within the Inngest plan's account// concurrency or app sync fails ("function has higher concurrency limits than// your plan"); raise it via env on plans that allow more.-export const ASSEMBLER_JOB_CONCURRENCY = getEnv("ASSEMBLER_JOB_CONCURRENCY", {- isRequired: false,- isSecret: false-});+export const ASSEMBLER_JOB_CONCURRENCY = getEnv("ASSEMBLER_JOB_CONCURRENCY");// Dev-only: public tunnel origin substituted into assembler-bound storage URLs// when the assembler is remote (local `.dev` hosts resolve only on this// machine). Unset in prod/preview.export const ASSEMBLER_STORAGE_PUBLIC_URL = getEnv(- "ASSEMBLER_STORAGE_PUBLIC_URL",- { isRequired: false, isSecret: false }+ "ASSEMBLER_STORAGE_PUBLIC_URL");-export const GOOGLE_PLACES_API_KEY = getEnv("GOOGLE_PLACES_API_KEY", {- isRequired: false-});+export const GOOGLE_PLACES_API_KEY = getEnv("GOOGLE_PLACES_API_KEY");-const itarEnvironment = getEnv("CONTROLLED_ENVIRONMENT", {- isRequired: false,- isSecret: false-});+const itarEnvironment = getEnv("CONTROLLED_ENVIRONMENT");export const CONTROLLED_ENVIRONMENT = parseBoolean(itarEnvironment, false);@@ -248,41 +127,23 @@ export const ITAR_RIDER_SHA256 ="e5ec082dfa511561edd86043060b0eff82c019ff95dda2cc7a6d79eff9560874";export const ITAR_RIDER_PDF_PATH = "https://carbon.ms/itar-rider.pdf";-export const ONSHAPE_CLIENT_ID = getEnv("ONSHAPE_CLIENT_ID", {- isRequired: false-});-export const ONSHAPE_CLIENT_SECRET = getEnv("ONSHAPE_CLIENT_SECRET", {- isRequired: false,- isSecret: true-});-export const ONSHAPE_OAUTH_REDIRECT_URL = getEnv("ONSHAPE_OAUTH_REDIRECT_URL", {- isRequired: false-});+export const ONSHAPE_CLIENT_ID = getEnv("ONSHAPE_CLIENT_ID");+export const ONSHAPE_CLIENT_SECRET = getEnv("ONSHAPE_CLIENT_SECRET");+export const ONSHAPE_OAUTH_REDIRECT_URL = getEnv("ONSHAPE_OAUTH_REDIRECT_URL");// Path to the native gltfpack binary (github.com/zeux/meshoptimizer), used to// compress oversized Onshape GLTF exports into viewer-ready GLBs. Optional:// when unset (and gltfpack isn't on PATH), oversized models are skipped// instead of compressed. The npm gltfpack is WASM with a 4GB memory ceiling// and cannot process large CAD exports — this must point to a native build.-export const GLTFPACK_PATH = getEnv("GLTFPACK_PATH", {- isRequired: false,- isSecret: false-});+export const GLTFPACK_PATH = getEnv("GLTFPACK_PATH");-export const QUICKBOOKS_CLIENT_ID = getEnv("QUICKBOOKS_CLIENT_ID", {- isRequired: false-});+export const QUICKBOOKS_CLIENT_ID = getEnv("QUICKBOOKS_CLIENT_ID");-export const QUICKBOOKS_CLIENT_SECRET = getEnv("QUICKBOOKS_CLIENT_SECRET", {- isRequired: false,- isSecret: true-});+export const QUICKBOOKS_CLIENT_SECRET = getEnv("QUICKBOOKS_CLIENT_SECRET");/** Intuit environment: "sandbox" or "production" (default). */export const QUICKBOOKS_ENVIRONMENT =- getEnv("QUICKBOOKS_ENVIRONMENT", {- isRequired: false,- isSecret: false- }) ?? "production";+ getEnv("QUICKBOOKS_ENVIRONMENT") ?? "production";/*** Carbon's own Ramp OAuth application (the "Connect to Ramp" authorization-code@@ -290,93 +151,43 @@ export const QUICKBOOKS_ENVIRONMENT =* the one app Carbon registers with Ramp. The client id is public (it appears in* the authorize URL); the secret is server-only (code exchange + token refresh).*/-export const RAMP_CLIENT_ID = getEnv("RAMP_CLIENT_ID", {- isRequired: false-});--export const RAMP_CLIENT_SECRET = getEnv("RAMP_CLIENT_SECRET", {- isRequired: false,- isSecret: true-});--export const QUICKBOOKS_WEBHOOK_SECRET = getEnv("QUICKBOOKS_WEBHOOK_SECRET", {- isRequired: false,- isSecret: true-});--export const SMTP_FROM = getEnv("SMTP_FROM", {- isRequired: false-});-export const SMTP_HOST = getEnv("SMTP_HOST", {- isRequired: false-});-export const SMTP_PASSWORD = getEnv("SMTP_PASSWORD", {- isRequired: false,- isSecret: true-});-export const SMTP_PORT = Number(- getEnv("SMTP_PORT", {- isRequired: false- }) || 587-);-export const SMTP_USER = getEnv("SMTP_USER", {- isRequired: false-});+export const RAMP_CLIENT_ID = getEnv("RAMP_CLIENT_ID");-export const SLACK_BOT_TOKEN = getEnv("SLACK_BOT_TOKEN", {- isRequired: false-});+export const RAMP_CLIENT_SECRET = getEnv("RAMP_CLIENT_SECRET");++export const QUICKBOOKS_WEBHOOK_SECRET = getEnv("QUICKBOOKS_WEBHOOK_SECRET");++export const SMTP_FROM = getEnv("SMTP_FROM");+export const SMTP_HOST = getEnv("SMTP_HOST");+export const SMTP_PASSWORD = getEnv("SMTP_PASSWORD");+export const SMTP_PORT = Number(getEnv("SMTP_PORT") || 587);+export const SMTP_USER = getEnv("SMTP_USER");++export const SLACK_BOT_TOKEN = getEnv("SLACK_BOT_TOKEN");export const CARBON_SLACK_ENABLED = isBrowser? window.env?.CARBON_SLACK_ENABLED === "true": Boolean(SLACK_BOT_TOKEN);-export const SLACK_CLIENT_ID = getEnv("SLACK_CLIENT_ID", {- isRequired: false-});-export const SLACK_CLIENT_SECRET = getEnv("SLACK_CLIENT_SECRET", {- isRequired: false,- isSecret: true-});-export const SLACK_OAUTH_REDIRECT_URL = getEnv("SLACK_OAUTH_REDIRECT_URL", {- isRequired: false-});-export const SLACK_SIGNING_SECRET = getEnv("SLACK_SIGNING_SECRET", {- isRequired: false,- isSecret: true-});-export const SLACK_STATE_SECRET = getEnv("SLACK_STATE_SECRET", {- isRequired: false,- isSecret: true-});+export const SLACK_CLIENT_ID = getEnv("SLACK_CLIENT_ID");+export const SLACK_CLIENT_SECRET = getEnv("SLACK_CLIENT_SECRET");+export const SLACK_OAUTH_REDIRECT_URL = getEnv("SLACK_OAUTH_REDIRECT_URL");+export const SLACK_SIGNING_SECRET = getEnv("SLACK_SIGNING_SECRET");+export const SLACK_STATE_SECRET = getEnv("SLACK_STATE_SECRET");export const SUPABASE_SERVICE_ROLE_KEY = getEnv("SUPABASE_SERVICE_ROLE_KEY");-export const SUPABASE_JWT_SECRET = getEnv("SUPABASE_JWT_SECRET", {- isSecret: true,- isRequired: false-});-export const SUPABASE_DB_URL = getEnv("SUPABASE_DB_URL", {- isRequired: true,- isSecret: true-});+export const SUPABASE_JWT_SECRET = getEnv("SUPABASE_JWT_SECRET");+export const DATABASE_URL = getEnv("DATABASE_URL");+/** @deprecated Use DATABASE_URL. */+export const SUPABASE_DB_URL = DATABASE_URL;export const SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID = getEnv(- "SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID",- {- isRequired: false,- isSecret: true- }+ "SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID");export const SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID = getEnv(- "SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID",- {- isRequired: false,- isSecret: true- }+ "SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID");export const SESSION_SECRET = getEnv("SESSION_SECRET");export const SESSION_KEY = "auth";export const SESSION_ERROR_KEY = "error";-export const STRIPE_SECRET_KEY = getEnv("STRIPE_SECRET_KEY", {- isRequired: false-});+export const STRIPE_SECRET_KEY = getEnv("STRIPE_SECRET_KEY");// Browser-safe boolean signal for whether Stripe (and therefore the Stripe// Connect integration) is configured. STRIPE_SECRET_KEY is a secret, so it is// `""` in the browser — the integration's `active` gate must read this derived@@ -385,36 +196,18 @@ export const STRIPE_SECRET_KEY = getEnv("STRIPE_SECRET_KEY", {export const STRIPE_CONNECT_ENABLED = isBrowser? window.env?.STRIPE_CONNECT_ENABLED === "true": Boolean(STRIPE_SECRET_KEY);-export const STRIPE_WEBHOOK_SECRET = getEnv("STRIPE_WEBHOOK_SECRET", {- isRequired: false-});+export const STRIPE_WEBHOOK_SECRET = getEnv("STRIPE_WEBHOOK_SECRET");// Connect webhook endpoints (`connect: true`) are signed with their OWN secret,// distinct from the platform-account endpoint above — a Connect event verified// against STRIPE_WEBHOOK_SECRET fails signature validation.export const STRIPE_CONNECT_WEBHOOK_SECRET = getEnv(- "STRIPE_CONNECT_WEBHOOK_SECRET",- {- isRequired: false- }+ "STRIPE_CONNECT_WEBHOOK_SECRET");-export const STRIPE_BYPASS_COMPANY_IDS = getEnv("STRIPE_BYPASS_COMPANY_IDS", {- isRequired: false-});-export const STRIPE_BYPASS_USER_IDS = getEnv("STRIPE_BYPASS_USER_IDS", {- isRequired: false-});-export const GTM_URL = getEnv("GTM_URL", {- isRequired: false,- isSecret: false-});-export const GTM_EVENTS_API_SECRET_KEY = getEnv("GTM_EVENTS_API_SECRET_KEY", {- isRequired: false,- isSecret: true-});-export const REDIS_URL = getEnv("REDIS_URL", {- isRequired: true,- isSecret: true-});+export const STRIPE_BYPASS_COMPANY_IDS = getEnv("STRIPE_BYPASS_COMPANY_IDS");+export const STRIPE_BYPASS_USER_IDS = getEnv("STRIPE_BYPASS_USER_IDS");+export const GTM_URL = getEnv("GTM_URL");+export const GTM_EVENTS_API_SECRET_KEY = getEnv("GTM_EVENTS_API_SECRET_KEY");+export const REDIS_URL = getEnv("REDIS_URL");export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days;export const REFRESH_ACCESS_TOKEN_THRESHOLD = 60 * 10; // 10 minutes left before token expires// Session lock / termination (NIST 800-171 3.1.10 / 3.1.11). All in MILLISECONDS@@ -424,49 +217,28 @@ export const REFRESH_ACCESS_TOKEN_THRESHOLD = 60 * 10; // 10 minutes left beforeexport const SESSION_IDLE_LOCK_MS = 15 * 60 * 1000; // 15 min — DISA App-Sec STIG web-app idleexport const SESSION_ABSOLUTE_MAX_MS = 12 * 60 * 60 * 1000; // 12 h — absolute session capexport const SESSION_HEARTBEAT_MS = 60 * 1000; // client activity heartbeat throttle-export const VERCEL_URL = getEnv("VERCEL_URL", { isSecret: false });--export const XERO_CLIENT_ID = getEnv("XERO_CLIENT_ID", {- isRequired: false-});-export const XERO_CLIENT_SECRET = getEnv("XERO_CLIENT_SECRET", {- isRequired: false,- isSecret: true-});-export const XERO_WEBHOOK_SECRET = getEnv("XERO_WEBHOOK_SECRET", {- isRequired: false,- isSecret: true-});--export const JIRA_CLIENT_ID = getEnv("JIRA_CLIENT_ID", {- isRequired: false-});-export const JIRA_CLIENT_SECRET = getEnv("JIRA_CLIENT_SECRET", {- isRequired: false,- isSecret: true-});-export const JIRA_OAUTH_REDIRECT_URL = getEnv("JIRA_OAUTH_REDIRECT_URL", {- isRequired: false-});-export const JIRA_STATE_SECRET = getEnv("JIRA_STATE_SECRET", {- isRequired: false,- isSecret: true-});+export const APP_URL = getEnv("APP_URL");+/** @deprecated Use APP_URL. */+export const VERCEL_URL = APP_URL;++export const XERO_CLIENT_ID = getEnv("XERO_CLIENT_ID");+export const XERO_CLIENT_SECRET = getEnv("XERO_CLIENT_SECRET");+export const XERO_WEBHOOK_SECRET = getEnv("XERO_WEBHOOK_SECRET");++export const JIRA_CLIENT_ID = getEnv("JIRA_CLIENT_ID");+export const JIRA_CLIENT_SECRET = getEnv("JIRA_CLIENT_SECRET");+export const JIRA_OAUTH_REDIRECT_URL = getEnv("JIRA_OAUTH_REDIRECT_URL");+export const JIRA_STATE_SECRET = getEnv("JIRA_STATE_SECRET");/*** Shared envs*/-export const NODE_ENV = getEnv("NODE_ENV", {- isRequired: false,- isSecret: false-});+export const NODE_ENV = getEnv("NODE_ENV");-export const VERCEL_ENV =- getEnv("VERCEL_ENV", {- isRequired: false,- isSecret: false- }) ?? NODE_ENV;+export const APP_ENV = getEnv("APP_ENV") ?? NODE_ENV;+/** @deprecated Use APP_ENV. */+export const VERCEL_ENV = APP_ENV;// True only on a developer's local stack — never in prod, preview, or a// self-hosted deployment (those all run NODE_ENV=production). Gates features@@ -485,38 +257,25 @@ export const IS_LOCAL_DEV =// https://developers.cloudflare.com/turnstile/troubleshooting/testing/export const CLOUDFLARE_TURNSTILE_SITE_KEY = IS_LOCAL_DEV? "1x00000000000000000000AA"- : getEnv("CLOUDFLARE_TURNSTILE_SITE_KEY", {- isRequired: false,- isSecret: false- });+ : getEnv("CLOUDFLARE_TURNSTILE_SITE_KEY");export const CLOUDFLARE_TURNSTILE_SECRET_KEY = IS_LOCAL_DEV? "1x0000000000000000000000000000000AA"- : getEnv("CLOUDFLARE_TURNSTILE_SECRET_KEY", { isRequired: false });+ : getEnv("CLOUDFLARE_TURNSTILE_SECRET_KEY");// Set to "1" by Vercel itself on every build and function — never by SST,// Docker, or a local stack, which all set VERCEL_ENV by hand. Server-only.-export const IS_VERCEL =- getEnv("VERCEL", { isRequired: false, isSecret: true }) === "1";+export const IS_VERCEL = getEnv("VERCEL") === "1";// Which check guards login: "botid" or "turnstile". Unset picks one — BotID// for the Cloud edition on Vercel, else Turnstile when its keys are set. Set it// when the keys are there for something else (GoTrue, another form) and login// should still use BotID. Vercel exposes no variable of its own for BotID.-export const BOT_PROTECTION = getEnv("BOT_PROTECTION", {- isRequired: false,- isSecret: false-});--export const POSTHOG_API_HOST = getEnv("POSTHOG_API_HOST", {- isSecret: false-});-export const POSTHOG_PROJECT_PUBLIC_KEY = getEnv("POSTHOG_PROJECT_PUBLIC_KEY", {- isSecret: false-});-export const SUPABASE_URL = getEnv("SUPABASE_URL", { isSecret: false });-export const SUPABASE_ANON_KEY = getEnv("SUPABASE_ANON_KEY", {- isSecret: false-});+export const BOT_PROTECTION = getEnv("BOT_PROTECTION");++export const POSTHOG_API_HOST = getEnv("POSTHOG_API_HOST");+export const POSTHOG_PROJECT_PUBLIC_KEY = getEnv("POSTHOG_PROJECT_PUBLIC_KEY");+export const SUPABASE_URL = getEnv("SUPABASE_URL");+export const SUPABASE_ANON_KEY = getEnv("SUPABASE_ANON_KEY");// Server-only. In a BYOC/self-hosted k8s deployment, the server's own calls to// Supabase can be pointed at an in-cluster address (bypassing the ingress hop@@ -527,27 +286,20 @@ export const SUPABASE_ANON_KEY = getEnv("SUPABASE_ANON_KEY", {// added to getBrowserEnv() or the Window.env interface, so it cannot leak to// the browser by construction.export const SUPABASE_INTERNAL_URL =- getEnv("SUPABASE_INTERNAL_URL", { isRequired: false, isSecret: false }) ||- SUPABASE_URL;+ getEnv("SUPABASE_INTERNAL_URL") || SUPABASE_URL;-export const DEFAULT_LANGUAGE =- getEnv("DEFAULT_LANGUAGE", {- isRequired: false,- isSecret: false- }) ?? "en";+export const DEFAULT_LANGUAGE = getEnv("DEFAULT_LANGUAGE") ?? "en";// Level for @carbon/logger. Optional + non-secret so it reaches the browser.// The logger derives a sensible default when unset (dev: debug, prod: info,// browser prod: warning), so an invalid/absent value never throws.-export const LOG_LEVEL = getEnv("LOG_LEVEL", {- isRequired: false,- isSecret: false-});--export const RATE_LIMIT = parseInt(- getEnv("RATE_LIMIT", { isRequired: false, isSecret: false }) || "5",- 10-);+export const LOG_LEVEL = getEnv("LOG_LEVEL");++export const RATE_LIMIT = parseInt(getEnv("RATE_LIMIT") || "5", 10);++// Vercel's own VERCEL_URL is a bare host; an APP_URL set by hand is an origin.+const previewUrl = () =>+ APP_URL?.startsWith("http") ? APP_URL : `https://${APP_URL}`;export function getAppUrl() {if (VERCEL_ENV === "production" || NODE_ENV === "production") {@@ -559,7 +311,7 @@ export function getAppUrl() {}if (VERCEL_ENV === "preview") {- return `https://${process.env.VERCEL_URL}`;+ return previewUrl();}// Dev: `crbn up` writes ERP_URL=https://<prefix>.erp.dev into .env.local.@@ -578,7 +330,7 @@ export function getMESUrl() {}if (VERCEL_ENV === "preview") {- return `https://${process.env.VERCEL_URL}`;+ return previewUrl();}// Dev: `crbn up` writes MES_URL=https://<prefix>.mes.dev into .env.local.@@ -609,10 +361,12 @@ export function getBrowserEnv() {RAMP_CLIENT_ID,SUPABASE_ANON_KEY,SUPABASE_URL,+ APP_ENV,+ APP_URL,VERCEL_ENV,VERCEL_URL,XERO_CLIENT_ID- };+ } satisfies Record<keyof BrowserEnv, unknown>;}export function isVercel() {diff --git a/packages/env/src/schema.ts b/packages/env/src/schema.tsnew file mode 100644index 0000000000..7e26b84c0d--- /dev/null+++ b/packages/env/src/schema.ts@@ -0,0 +1,518 @@+// 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 { z } from "zod";++export type Group =+ | "core"+ | "auth"+ | "email"+ | "stripe"+ | "slack"+ | "xero"+ | "quickbooks"+ | "jira"+ | "onshape"+ | "ramp"+ | "ai"+ | "assembler"+ | "observability"+ | "dev";++// A feature is a group that is allowed to be off. It is "half-configured" when+// some of its `needed` variables are set and others are not.+export const FEATURES = {+ email: "Email",+ stripe: "Stripe",+ slack: "Slack",+ xero: "Xero",+ quickbooks: "QuickBooks",+ jira: "Jira",+ onshape: "Onshape",+ ramp: "Ramp",+ ai: "AI",+ assembler: "Assembler"+} satisfies Partial<Record<Group, string>>;++type Source = Record<string, string | undefined>;++export type EnvVar = {+ group: Group;+ description: string;+ type?: z.ZodType;+ /** Server-only: reads as "" in the browser. */+ secret?: boolean;+ /** Sent to the browser in `window.env`. */+ browser?: boolean;+ /**+ * "error" stops startup. "warn" is reported and becomes an error in the next+ * release; do not flip one without updating deployments.test.ts.+ */+ required?: "error" | "warn";+ /** Lifts `required` when it returns true. */+ unless?: (env: Source) => boolean;+ /** The feature needs this variable to work at all. */+ needed?: boolean;+ /** Deprecated names still read, in order, after the variable's own. */+ aliases?: readonly string[];+};++const url = z.url();+const number = z.coerce.number();++// getAppUrl / getMESUrl and the email sender only fall back to Carbon's own+// production values in a production build, and Carbon Cloud means them.+const cloudOrDev = (env: Source) =>+ env.CARBON_EDITION === "cloud" || env.NODE_ENV !== "production";++const define = <const T extends Record<string, EnvVar>>(schema: T) => schema;++export const schema = define({+ // ── core ──────────────────────────────────────────────────────────────────+ NODE_ENV: { group: "core", description: "Node mode", browser: true },+ APP_ENV: {+ group: "core",+ description: "Deployment kind; defaults to NODE_ENV",+ type: z.enum(["production", "preview", "development", "test"]),+ browser: true,+ aliases: ["VERCEL_ENV"]+ },+ // Not typed as a URL yet: the VERCEL_URL it falls back to has no scheme on+ // Vercel and in sst.config.ts.+ APP_URL: {+ group: "core",+ description: "This app's own origin, used in sign-in redirects",+ browser: true,+ aliases: ["VERCEL_URL"]+ },+ ERP_URL: {+ group: "core",+ description: "Public URL of the ERP",+ type: url,+ browser: true,+ required: "warn",+ unless: cloudOrDev+ },+ MES_URL: {+ group: "core",+ description: "Public URL of the MES",+ type: url,+ browser: true,+ required: "warn",+ unless: cloudOrDev+ },+ DOMAIN: {+ group: "core",+ description: "Parent domain shared by the apps (cookies, passkeys)"+ },+ CARBON_EDITION: {+ group: "core",+ description: "community (default), cloud, enterprise or test",+ browser: true+ },+ CONTROLLED_ENVIRONMENT: {+ group: "core",+ description: "true for an ITAR / controlled deployment",+ browser: true+ },+ DEFAULT_LANGUAGE: {+ group: "core",+ description: "Default UI language (en)",+ browser: true+ },+ DATABASE_URL: {+ group: "core",+ description: "Postgres connection string",+ type: url,+ secret: true,+ required: "error",+ aliases: ["SUPABASE_DB_URL"]+ },+ SUPABASE_URL: {+ group: "core",+ description: "Public URL of the Supabase API",+ type: url,+ browser: true,+ required: "warn"+ },+ SUPABASE_ANON_KEY: {+ group: "core",+ description: "Supabase anonymous key",+ browser: true,+ required: "warn"+ },+ SUPABASE_SERVICE_ROLE_KEY: {+ group: "core",+ description: "Supabase service-role key",+ secret: true,+ required: "error"+ },+ SUPABASE_JWT_SECRET: {+ group: "core",+ description: "Secret that signs Supabase JWTs",+ secret: true+ },+ SUPABASE_INTERNAL_URL: {+ group: "core",+ description: "In-cluster Supabase URL for server calls",+ type: url+ },+ CARBON_API_URL: {+ group: "core",+ description: "Public URL of the Carbon API; defaults to SUPABASE_URL",+ type: url,+ browser: true+ },+ REDIS_URL: {+ group: "core",+ description: "Redis connection string",+ type: url,+ secret: true,+ required: "error"+ },+ INNGEST_DEV: {+ group: "core",+ description: "Set to use the local Inngest dev server (no keys needed)"+ },+ INNGEST_SIGNING_KEY: {+ group: "core",+ description: "Inngest signing key",+ secret: true,+ required: "error",+ unless: (env) => Boolean(env.INNGEST_DEV)+ },+ INNGEST_EVENT_KEY: {+ group: "core",+ description: "Inngest event key",+ secret: true,+ required: "error",+ unless: (env) => Boolean(env.INNGEST_DEV)+ },+ EXCHANGE_RATES_API_KEY: {+ group: "core",+ description: "Key for the exchange-rates API",+ secret: true+ },+ GOOGLE_PLACES_API_KEY: {+ group: "core",+ description: "Google Places key for address autocomplete",+ browser: true+ },+ BINDERY_PRESS_API_KEY: {+ group: "core",+ description: "Bindery Press API key",+ secret: true+ },+ GLTFPACK_PATH: {+ group: "core",+ description: "Path to a native gltfpack binary"+ },+ VERCEL: {+ group: "core",+ description: "Set to 1 by Vercel itself; never set it by hand",+ secret: true+ },++ // ── auth ──────────────────────────────────────────────────────────────────+ SESSION_SECRET: {+ group: "auth",+ description: "signs the session cookie",+ secret: true,+ required: "error"+ },+ AUTH_PROVIDERS: {+ group: "auth",+ description: "Comma-separated sign-in methods (email,google,azure)",+ browser: true+ },+ RATE_LIMIT: {+ group: "auth",+ description: "Sign-in attempts allowed per window (5)",+ type: number+ },+ BOT_PROTECTION: {+ group: "auth",+ description: "Login bot check: botid or turnstile",+ type: z.enum(["botid", "turnstile"])+ },+ CLOUDFLARE_TURNSTILE_SITE_KEY: {+ group: "auth",+ description: "Turnstile site key"+ },+ CLOUDFLARE_TURNSTILE_SECRET_KEY: {+ group: "auth",+ description: "Turnstile secret key",+ secret: true+ },+ SUPABASE_AUTH_EXTERNAL_AZURE_CLIENT_ID: {+ group: "auth",+ description: "Azure OAuth client id (also read by GoTrue)",+ secret: true+ },+ SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID: {+ group: "auth",+ description: "Google OAuth client id (also read by GoTrue)",+ secret: true+ },++ // ── email ─────────────────────────────────────────────────────────────────+ SMTP_HOST: { group: "email", description: "SMTP server host", needed: true },+ SMTP_PORT: { group: "email", description: "SMTP port (587)", type: number },+ SMTP_USER: { group: "email", description: "SMTP user" },+ SMTP_PASSWORD: { group: "email", description: "SMTP password", secret: true },+ SMTP_FROM: {+ group: "email",+ description: "From address on outgoing email",+ required: "warn",+ unless: (env) => cloudOrDev(env) || Boolean(env.RESEND_DOMAIN)+ },+ RESEND_API_KEY: {+ group: "email",+ description: "Deprecated shorthand for Resend's SMTP; use SMTP_*",+ secret: true+ },+ RESEND_DOMAIN: {+ group: "email",+ description: "Deprecated: sender domain when SMTP_FROM is unset"+ },++ // ── stripe ────────────────────────────────────────────────────────────────+ STRIPE_SECRET_KEY: {+ group: "stripe",+ description: "Stripe secret key",+ secret: true,+ needed: true+ },+ STRIPE_WEBHOOK_SECRET: {+ group: "stripe",+ description: "Signing secret of the platform webhook endpoint",+ secret: true,+ needed: true+ },+ STRIPE_CONNECT_WEBHOOK_SECRET: {+ group: "stripe",+ description: "Signing secret of the Connect webhook endpoint",+ secret: true+ },+ STRIPE_BYPASS_COMPANY_IDS: {+ group: "stripe",+ description: "Company ids that skip billing"+ },+ STRIPE_BYPASS_USER_IDS: {+ group: "stripe",+ description: "User ids that skip billing"+ },++ // ── slack ─────────────────────────────────────────────────────────────────+ SLACK_CLIENT_ID: {+ group: "slack",+ description: "Slack app client id",+ needed: true+ },+ SLACK_CLIENT_SECRET: {+ group: "slack",+ description: "Slack app client secret",+ secret: true,+ needed: true+ },+ SLACK_SIGNING_SECRET: {+ group: "slack",+ description: "Slack request signing secret",+ secret: true+ },+ SLACK_STATE_SECRET: {+ group: "slack",+ description: "Secret that signs the Slack OAuth state",+ secret: true+ },+ SLACK_OAUTH_REDIRECT_URL: {+ group: "slack",+ description: "Slack OAuth callback URL",+ type: url+ },+ SLACK_BOT_TOKEN: {+ group: "slack",+ description: "Bot token for Carbon's own Slack workspace",+ secret: true+ },++ // ── xero ──────────────────────────────────────────────────────────────────+ XERO_CLIENT_ID: {+ group: "xero",+ description: "Xero app client id",+ browser: true,+ needed: true+ },+ XERO_CLIENT_SECRET: {+ group: "xero",+ description: "Xero app client secret",+ secret: true,+ needed: true+ },+ XERO_WEBHOOK_SECRET: {+ group: "xero",+ description: "Xero webhook signing key",+ secret: true+ },++ // ── quickbooks ────────────────────────────────────────────────────────────+ QUICKBOOKS_CLIENT_ID: {+ group: "quickbooks",+ description: "Intuit app client id",+ browser: true,+ needed: true+ },+ QUICKBOOKS_CLIENT_SECRET: {+ group: "quickbooks",+ description: "Intuit app client secret",+ secret: true,+ needed: true+ },+ QUICKBOOKS_ENVIRONMENT: {+ group: "quickbooks",+ description: "sandbox or production (default)",+ type: z.enum(["sandbox", "production"])+ },+ QUICKBOOKS_WEBHOOK_SECRET: {+ group: "quickbooks",+ description: "Unused; the webhook reads QUICKBOOKS_WEBHOOK_VERIFIER_TOKEN",+ secret: true+ },++ // ── jira ──────────────────────────────────────────────────────────────────+ JIRA_CLIENT_ID: {+ group: "jira",+ description: "Atlassian app client id",+ browser: true,+ needed: true+ },+ JIRA_CLIENT_SECRET: {+ group: "jira",+ description: "Atlassian app client secret",+ secret: true,+ needed: true+ },+ JIRA_OAUTH_REDIRECT_URL: { group: "jira", description: "Unused", type: url },+ JIRA_STATE_SECRET: { group: "jira", description: "Unused", secret: true },++ // ── onshape ───────────────────────────────────────────────────────────────+ ONSHAPE_CLIENT_ID: {+ group: "onshape",+ description: "Onshape app client id",+ browser: true,+ needed: true+ },+ ONSHAPE_CLIENT_SECRET: {+ group: "onshape",+ description: "Onshape app client secret",+ secret: true,+ needed: true+ },+ ONSHAPE_OAUTH_REDIRECT_URL: {+ group: "onshape",+ description: "Onshape OAuth callback URL",+ type: url+ },++ // ── ramp ──────────────────────────────────────────────────────────────────+ RAMP_CLIENT_ID: {+ group: "ramp",+ description: "Carbon's Ramp OAuth app client id",+ browser: true,+ needed: true+ },+ RAMP_CLIENT_SECRET: {+ group: "ramp",+ description: "Carbon's Ramp OAuth app client secret",+ secret: true,+ needed: true+ },++ // ── ai ────────────────────────────────────────────────────────────────────+ AI_API_KEY: {+ group: "ai",+ description: "API key for the OpenAI-compatible model provider",+ secret: true,+ aliases: ["OPENAI_API_KEY"]+ },+ AI_BASE_URL: {+ group: "ai",+ description: "Base URL of the model provider",+ type: url+ },+ AI_MODEL: { group: "ai", description: "Model used to extract documents" },+ EXTRACTION_CONFIDENCE_THRESHOLD: {+ group: "ai",+ description: "Minimum confidence to accept an extracted field (0.85)",+ type: number+ },++ // ── assembler ─────────────────────────────────────────────────────────────+ ASSEMBLER_SERVICE_URL: {+ group: "assembler",+ description: "URL of the CAD assembler service",+ type: url,+ needed: true+ },+ ASSEMBLER_SERVICE_API_KEY: {+ group: "assembler",+ description: "API key for the assembler service",+ secret: true,+ needed: true+ },+ ASSEMBLER_JOB_CONCURRENCY: {+ group: "assembler",+ description: "Cap on concurrent assembler jobs",+ type: number+ },+ ASSEMBLER_STORAGE_PUBLIC_URL: {+ group: "assembler",+ description: "Dev only: public tunnel origin for storage URLs",+ type: url+ },++ // ── observability ─────────────────────────────────────────────────────────+ LOG_LEVEL: {+ group: "observability",+ description: "Log level",+ browser: true+ },+ POSTHOG_API_HOST: {+ group: "observability",+ description: "PostHog host",+ browser: true+ },+ POSTHOG_PROJECT_PUBLIC_KEY: {+ group: "observability",+ description: "PostHog project key",+ browser: true+ },+ GTM_URL: { group: "observability", description: "Go-to-market events URL" },+ GTM_EVENTS_API_SECRET_KEY: {+ group: "observability",+ description: "Go-to-market events API key",+ secret: true+ },++ // ── dev ───────────────────────────────────────────────────────────────────+ PORT_API: {+ group: "dev",+ description: "Written by crbn: local API gateway port"+ }+});++export type EnvName = keyof typeof schema;++export type BrowserEnvName = {+ [K in EnvName]: (typeof schema)[K] extends { browser: true } ? K : never;+}[EnvName];++/** The variable's own value, else the first deprecated alias that is set. */+export function resolve(source: Source, name: EnvName) {+ const { aliases = [] } = schema[name] as EnvVar;+ for (const key of [name, ...aliases]) {+ if (source[key]) return source[key];+ }+ return source[name];+}diff --git a/packages/env/src/validate.test.ts b/packages/env/src/validate.test.tsnew file mode 100644index 0000000000..a7b8d208eb--- /dev/null+++ b/packages/env/src/validate.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { formatReport, validateEnv } from "./validate";++const base = {+ NODE_ENV: "development",+ DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/postgres",+ SUPABASE_URL: "http://localhost:54321",+ SUPABASE_ANON_KEY: "anon",+ SUPABASE_SERVICE_ROLE_KEY: "service",+ SESSION_SECRET: "session",+ REDIS_URL: "redis://localhost:6379",+ INNGEST_DEV: "1"+};++describe("validateEnv", () => {+ it("passes a complete environment", () => {+ expect(validateEnv(base)).toMatchObject({ problems: [], fatal: false });+ });++ it("reports every missing variable together", () => {+ const report = validateEnv({ ...base, SESSION_SECRET: "", REDIS_URL: "" });+ expect(report.fatal).toBe(true);+ const text = formatReport(report);+ expect(text).toContain("Carbon can't start: 2 problems");+ expect(text).toContain("✗ SESSION_SECRET");+ expect(text).toContain("missing: signs the session cookie");+ expect(text).toContain("✗ REDIS_URL");+ });++ it("names an invalid type", () => {+ const text = formatReport(validateEnv({ ...base, REDIS_URL: "localhost" }));+ expect(text).toMatch(/REDIS_URL\s+Invalid URL/);+ });++ it("flags a half-configured feature", () => {+ const report = validateEnv({ ...base, STRIPE_SECRET_KEY: "sk_live_abc" });+ expect(formatReport(report)).toMatch(+ /Stripe \(half-configured\)\n\s+! STRIPE_WEBHOOK_SECRET\s+missing, but STRIPE_SECRET_KEY is set/+ );+ expect(report.off).not.toContain("Stripe");+ });++ it("lists only fully unset features as off", () => {+ const { off } = validateEnv({ ...base, SMTP_HOST: "localhost" });+ expect(off).toContain("Slack");+ expect(off).not.toContain("Email");+ });++ it("never prints a secret's value", () => {+ const text = formatReport(+ validateEnv({+ ...base,+ REDIS_URL: "hunter2",+ STRIPE_SECRET_KEY: "sk_live_abc"+ })+ );+ expect(text).not.toContain("hunter2");+ expect(text).not.toContain("sk_live_abc");+ });++ it("reads a deprecated alias", () => {+ const report = validateEnv({+ ...base,+ DATABASE_URL: "",+ SUPABASE_DB_URL: base.DATABASE_URL+ });+ expect(report.problems).toEqual([]);+ });++ it("only warns about what did not stop startup before", () => {+ const report = validateEnv({+ ...base,+ SUPABASE_URL: "",+ NODE_ENV: "production"+ });+ expect(report.fatal).toBe(false);+ expect(report.problems.map((p) => p.name)).toEqual([+ "ERP_URL",+ "MES_URL",+ "SUPABASE_URL",+ "SMTP_FROM"+ ]);+ });+});diff --git a/packages/env/src/validate.ts b/packages/env/src/validate.tsnew file mode 100644index 0000000000..c9344460f5--- /dev/null+++ b/packages/env/src/validate.ts@@ -0,0 +1,96 @@+// 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 EnvName, type EnvVar, FEATURES, resolve, schema } from "./schema";++type Problem = {+ /** Report heading: "Required", "Invalid" or a half-configured feature. */+ section: string;+ name: string;+ message: string;+ level: "error" | "warn";+};++export type EnvReport = {+ problems: Problem[];+ /** Features with none of their variables set. */+ off: string[];+ fatal: boolean;+};++const entries = Object.entries(schema) as [EnvName, EnvVar][];++export function validateEnv(+ source: Record<string, string | undefined>+): EnvReport {+ const problems: Problem[] = [];+ const isSet = (name: EnvName) => Boolean(resolve(source, name));++ for (const [name, spec] of entries) {+ const value = resolve(source, name);+ if (!value) {+ if (spec.required && !spec.unless?.(source)) {+ problems.push({+ section: "Required",+ name,+ message: `missing: ${spec.description}`,+ level: spec.required+ });+ }+ continue;+ }+ const issue = spec.type?.safeParse(value).error?.issues[0];+ if (issue) {+ problems.push({+ section: "Invalid",+ name,+ // A secret's value never reaches the report.+ message: issue.message + (spec.secret ? "" : ` (got "${value}")`),+ level: "warn"+ });+ }+ }++ const off: string[] = [];+ for (const [group, label] of Object.entries(FEATURES)) {+ const vars = entries.filter(([, spec]) => spec.group === group);+ const needed = vars.filter(([, spec]) => spec.needed).map(([name]) => name);+ const present = needed.filter(isSet);+ if (!vars.some(([name]) => isSet(name))) {+ off.push(label);+ } else if (present.length > 0 && present.length < needed.length) {+ for (const name of needed.filter((n) => !isSet(n))) {+ problems.push({+ section: `${label} (half-configured)`,+ name,+ message: `missing, but ${present.join(", ")} is set`,+ level: "warn"+ });+ }+ }+ }++ return { problems, off, fatal: problems.some((p) => p.level === "error") };+}++export function formatReport({ problems, off, fatal }: EnvReport) {+ const count = `${problems.length} problem${problems.length === 1 ? "" : "s"} with its environment`;+ const lines = [+ fatal+ ? `Carbon can't start: ${count}`+ : `Carbon started with ${count} (! will stop startup in the next release)`+ ];+ const width = Math.max(0, ...problems.map((p) => p.name.length));+ for (const section of new Set(problems.map((p) => p.section))) {+ lines.push("", ` ${section}`);+ for (const p of problems.filter((p) => p.section === section)) {+ const mark = p.level === "error" ? "✗" : "!";+ lines.push(` ${mark} ${p.name.padEnd(width)} ${p.message}`);+ }+ }+ if (off.length) {+ lines.push("", ` Off, because they aren't configured: ${off.join(", ")}`);+ }+ return lines.join("\n");+}diff --git a/packages/env/src/vercel-production.json b/packages/env/src/vercel-production.jsonnew file mode 100644index 0000000000..378be85368--- /dev/null+++ b/packages/env/src/vercel-production.json@@ -0,0 +1,88 @@+{+ "erp": [+ "ASSEMBLER_SERVICE_API_KEY",+ "ASSEMBLER_SERVICE_URL",+ "AUTH_PROVIDERS",+ "CARBON_API_URL",+ "CARBON_EDITION",+ "CLOUDFLARE_TURNSTILE_SECRET_KEY",+ "CLOUDFLARE_TURNSTILE_SITE_KEY",+ "DOMAIN",+ "EXCHANGE_RATES_API_KEY",+ "GOOGLE_PLACES_API_KEY",+ "GTM_EVENTS_API_SECRET_KEY",+ "GTM_URL",+ "INNGEST_EVENT_KEY",+ "INNGEST_SIGNING_KEY",+ "JIRA_CLIENT_ID",+ "JIRA_CLIENT_SECRET",+ "JIRA_OAUTH_REDIRECT_URL",+ "JIRA_STATE_SECRET",+ "ONSHAPE_CLIENT_ID",+ "ONSHAPE_CLIENT_SECRET",+ "ONSHAPE_OAUTH_REDIRECT_URL",+ "OPENAI_API_KEY",+ "POSTHOG_API_HOST",+ "POSTHOG_PROJECT_PUBLIC_KEY",+ "RAMP_CLIENT_ID",+ "RAMP_CLIENT_SECRET",+ "REDIS_URL",+ "RESEND_API_KEY",+ "SESSION_SECRET",+ "SLACK_BOT_TOKEN",+ "SLACK_CLIENT_ID",+ "SLACK_CLIENT_SECRET",+ "SLACK_OAUTH_REDIRECT_URL",+ "SLACK_SIGNING_SECRET",+ "SLACK_STATE_SECRET",+ "STRIPE_BYPASS_COMPANY_IDS",+ "STRIPE_BYPASS_USER_IDS",+ "STRIPE_CONNECT_WEBHOOK_SECRET",+ "STRIPE_SECRET_KEY",+ "STRIPE_WEBHOOK_SECRET",+ "SUPABASE_ANON_KEY",+ "SUPABASE_DB_URL",+ "SUPABASE_JWT_SECRET",+ "SUPABASE_SERVICE_ROLE_KEY",+ "SUPABASE_URL",+ "VERCEL_URL",+ "XERO_CLIENT_ID",+ "XERO_CLIENT_SECRET",+ "XERO_WEBHOOK_SECRET"+ ],+ "mes": [+ "ASSEMBLER_SERVICE_API_KEY",+ "ASSEMBLER_SERVICE_URL",+ "AUTH_PROVIDERS",+ "CARBON_EDITION",+ "CLOUDFLARE_TURNSTILE_SECRET_KEY",+ "CLOUDFLARE_TURNSTILE_SITE_KEY",+ "DOMAIN",+ "INNGEST_EVENT_KEY",+ "INNGEST_SIGNING_KEY",+ "OPENAI_API_KEY",+ "POSTHOG_API_HOST",+ "POSTHOG_PROJECT_PUBLIC_KEY",+ "REDIS_URL",+ "RESEND_API_KEY",+ "SESSION_SECRET",+ "SLACK_BOT_TOKEN",+ "SLACK_CLIENT_ID",+ "SLACK_CLIENT_SECRET",+ "SLACK_OAUTH_REDIRECT_URL",+ "SLACK_SIGNING_SECRET",+ "SLACK_STATE_SECRET",+ "STRIPE_BYPASS_COMPANY_IDS",+ "STRIPE_BYPASS_USER_IDS",+ "STRIPE_SECRET_KEY",+ "STRIPE_WEBHOOK_SECRET",+ "SUPABASE_ANON_KEY",+ "SUPABASE_DB_URL",+ "SUPABASE_SERVICE_ROLE_KEY",+ "SUPABASE_URL",+ "VERCEL_URL",+ "XERO_CLIENT_ID",+ "XERO_CLIENT_SECRET",+ "XERO_WEBHOOK_SECRET"+ ]+}diff --git a/packages/env/vitest.config.ts b/packages/env/vitest.config.tsnew file mode 100644index 0000000000..c95802b144--- /dev/null+++ b/packages/env/vitest.config.ts@@ -0,0 +1,5 @@+// 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.++export { default } from "@carbon/config/vitest";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 74335be114..1fd8ad603a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2556,6 +2556,9 @@ importers:'@types/node':specifier: 20.19.39version: 20.19.39+ zod:+ specifier: 'catalog:'+ version: 4.5.4devDependencies:'@carbon/config':specifier: workspace:*@@ -2563,6 +2566,9 @@ importers:typescript:specifier: 'catalog:'version: 5.8.3+ vitest:+ specifier: 'catalog:'+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/files:dependencies: