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
// 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 { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "pathe";
import { APP_CHOICES } from "./constants.js";
import { type JwtCreds, type PortMap, SHARED_REDIS_PORT } from "./worktree.js";
/**
* Keys copied from `.env`, which `crbn up` loads into process.env before this
* runs. A key with a `fallback` is always written. One without is left out when
* unset: an empty line in `.env.local` would hide the `.env` value.
*/
const FROM_DOT_ENV: readonly { key: string; fallback?: string }[] = [
// Consumed by docker-compose.dev.yml. Supabase's own services hold ~20
// connections at idle, so the old default of 25 left no room for GoTrue/the
// app and caused "remaining connection slots are reserved..." (53300)
// errors that surfaced as random logouts. Matches the prod default.
{ key: "PG_MAX_CONNECTIONS", fallback: "100" },
// The workflow integrations' Google OAuth app.
{ key: "GOOGLE_CLIENT_ID" },
{ key: "GOOGLE_CLIENT_SECRET" },
{ key: "GOOGLE_OAUTH_REDIRECT_URL" }
];
export function renderEnv(opts: {
slug: string;
ports: PortMap;
redisDb: number;
jwt: JwtCreds;
/** When true, write portless hostnames; when false, write http://localhost:PORT URLs. */
portless: boolean;
/** Required when portless is true. e.g. "dev" for branch "dev". */
branchPrefix?: string;
/**
* Whether the assembler was selected to run. `ASSEMBLER_SERVICE_URL` IS the
* pipeline's feature flag (`assemblerEnabled()` in @carbon/jobs) — writing it
* with no service behind it turns clean job skips into dead-URL failures that
* stamp model rows Failed. Omitted → written (migrate regenerates the env
* without knowing the selection; only `up` passes false). A remote assembler
* pinned in `.env` via `#force` wins regardless.
*/
includeAssembler?: boolean;
}): string {
const {
slug,
ports,
redisDb,
jwt,
portless,
branchPrefix,
includeAssembler = true
} = opts;
const host = (sub: string) => `${sub}.${branchPrefix}.dev`;
const local = (port: number) => `http://localhost:${port}`;
const erpUrl = portless ? `https://${host("erp")}` : local(ports.PORT_ERP);
const lines: string[] = [];
lines.push("# Generated by crbn. Do not edit by hand.");
lines.push("# Vite/React Router auto-load this file alongside .env;");
lines.push("# values here override .env. The user's .env is left untouched.");
lines.push("");
lines.push(`CARBON_WORKTREE=${slug}`);
if (portless) lines.push("PORTLESS_TLD=dev");
lines.push("");
lines.push("# Internal compose ports (apps do not read these directly)");
for (const [k, v] of Object.entries(ports)) lines.push(`${k}=${v}`);
lines.push("");
lines.push("# From .env, or crbn's default when it has one");
for (const { key, fallback } of FROM_DOT_ENV) {
const value = process.env[key] || fallback;
if (value) lines.push(`${key}=${value}`);
}
lines.push("");
lines.push(
portless
? "# App-facing URLs (portless hostnames)"
: "# App-facing URLs (localhost)"
);
lines.push(`DOMAIN=${portless ? `${branchPrefix}.dev` : "localhost"}`);
lines.push(`ERP_URL=${erpUrl}`);
lines.push(
`MES_URL=${portless ? `https://${host("mes")}` : local(ports.PORT_MES)}`
);
lines.push(`VERCEL_URL=${erpUrl}`);
if (portless) lines.push(`GTM_URL=https://${host("erp")}`);
lines.push("");
lines.push(
"# Supabase (per-worktree dev keys, minted from random JWT_SECRET)"
);
lines.push(
`SUPABASE_URL=${portless ? `https://${host("api")}` : local(ports.PORT_API)}`
);
lines.push(
`SUPABASE_DB_URL=postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`
);
lines.push("PGSSLMODE=disable");
lines.push(`SUPABASE_JWT_SECRET=${jwt.secret}`);
lines.push(`SUPABASE_ANON_KEY=${jwt.anonKey}`);
lines.push(`SUPABASE_SERVICE_ROLE_KEY=${jwt.serviceKey}`);
// OAuth callback: portless uses the shared api.carbon.dev alias; localhost
// mode uses the well-known Supabase default port so the redirect URI is
// predictable and can be registered in Google/Azure console once.
const oauthBase = portless
? "https://api.carbon.dev"
: "http://localhost:54321";
lines.push(
`SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI=${oauthBase}/auth/v1/callback`
);
lines.push(
`SUPABASE_AUTH_EXTERNAL_AZURE_REDIRECT_URI=${oauthBase}/auth/v1/callback`
);
lines.push("");
lines.push(
"# Integration OAuth callbacks on this stack's ERP host. Register the"
);
lines.push(
"# URL on the provider's app, or pin your own in .env with #force."
);
lines.push(
`ONSHAPE_V2_OAUTH_REDIRECT_URL=${erpUrl}/api/integrations/onshape-v2/oauth`
);
lines.push("");
lines.push("# Aux services");
lines.push(`REDIS_URL=redis://localhost:${SHARED_REDIS_PORT}/${redisDb}`);
lines.push("INNGEST_DEV=1");
lines.push(`INNGEST_BASE_URL=http://localhost:${ports.PORT_INNGEST}`);
// SDK advertises this as its serve URL during self-register. Must be
// reachable from inside the inngest container (handled via extra_hosts +
// portless CA mount in docker-compose.dev.yml).
lines.push(`INNGEST_SERVE_HOST=${erpUrl}`);
// Hostname (no scheme) that docker-compose maps to host-gateway inside the
// inngest container, so the SDK URL above resolves to the dev server on the
// host. extra_hosts only accepts fully-qualified names — no wildcards —
// which is why we can't reuse ${DOMAIN} (e.g. `main.dev` won't match the
// `erp.main.dev` host the SDK URL points at).
lines.push(`INNGEST_TLS_HOST=${portless ? host("erp") : "localhost"}`);
lines.push(`EMAIL_DEV_PORT=${ports.PORT_EMAIL}`);
lines.push("");
if (includeAssembler) {
lines.push("# Assembler service (CAD conversion + motion planning)");
lines.push(
`ASSEMBLER_SERVICE_URL=${portless ? `https://${host("assembler")}` : local(ports.PORT_ASSEMBLER)}`
);
lines.push("ASSEMBLER_SERVICE_API_KEY=dev-local-key");
} else {
lines.push("# Assembler not selected this run — URL omitted so the CAD");
lines.push("# pipeline skips cleanly (assemblerEnabled() gates on it).");
}
lines.push("");
lines.push("# Dev auth bypass");
lines.push("[email protected]");
lines.push("");
return lines.join("\n");
}
/**
* The `#force` escape hatch: a line in the user-owned `.env` ending with a
* `#force` comment pins that key — the generated `.env.local` omits it, so the
* `.env` value wins even though `.env.local` normally overrides `.env` (Vite
* load order). Survives regeneration by construction: the marker lives in
* `.env`, which crbn never writes. e.g. point the local stack at a remote
* assembler: `ASSEMBLER_SERVICE_URL=https://xxx.execute-api.… #force`
*/
const FORCE_MARKER = /#\s*force\s*$/i;
const ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
export function forcedKeys(dotEnvText: string): Set<string> {
const keys = new Set<string>();
for (const line of dotEnvText.split("\n")) {
if (!FORCE_MARKER.test(line)) continue;
const key = line.match(ENV_KEY)?.[1];
if (key) keys.add(key);
}
return keys;
}
export function omitForcedKeys(content: string, dotEnvText: string): string {
const forced = forcedKeys(dotEnvText);
if (forced.size === 0) return content;
return content
.split("\n")
.map((line) => {
const key = line.match(ENV_KEY)?.[1];
return key && forced.has(key)
? `# ${key} omitted — #force'd in .env`
: line;
})
.join("\n");
}
export function writeEnv(worktreeRoot: string, content: string) {
const dotEnvPath = join(worktreeRoot, ".env");
const dotEnv = existsSync(dotEnvPath) ? readFileSync(dotEnvPath, "utf8") : "";
writeFileSync(
join(worktreeRoot, ".env.local"),
omitForcedKeys(content, dotEnv)
);
}
export function syncAppPortlessConfigs(worktreeRoot: string) {
for (const { value: appId } of APP_CHOICES) {
const path = join(worktreeRoot, "apps", appId, "portless.json");
if (existsSync(path)) {
unlinkSync(path);
}
}
}