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.

crbn: use `pathe`

Sidwebworksdbae6a929ab0
diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.ts
index 7be617ac07..f091d888f7 100644
--- a/packages/database/src/seed.ts
+++ b/packages/database/src/seed.ts
@@ -4,6 +4,7 @@ import * as dotenv from "dotenv";
import { devPrices } from "./seed/index.ts";
import type { Database } from "./types.ts";
+dotenv.config({ path: ".env.local" });
dotenv.config();
const supabaseAdmin = createClient<Database>(
@@ -21,9 +22,7 @@ async function seed() {
const upsertConfig = await supabaseAdmin.from("config").upsert([
{
id: true,
- apiUrl: process.env.SUPABASE_URL!.includes("localhost")
- ? "http://host.docker.internal:54321"
- : process.env.SUPABASE_URL!,
+ apiUrl: resolveApiUrl(),
anonKey: process.env.SUPABASE_ANON_KEY!
}
]);
@@ -41,6 +40,25 @@ async function seed() {
if (upsertPlans.error) throw upsertPlans.error;
}
+// Postgres triggers + edge functions call back to the API from inside the
+// docker network, so the public portless hostname (https://<branch>.api.dev)
+// won't resolve. Use host.docker.internal with the worktree's PORT_API
+// (written to .env.local by `crbn up`). Cloud runs (e.g. CI seeding a fresh
+// workspace) have no PORT_API and a `*.supabase.co` URL — return as-is.
+function resolveApiUrl(): string {
+ const supabaseUrl = process.env.SUPABASE_URL!;
+ const port = process.env.PORT_API;
+ const isCrbnDevHost =
+ /\.api\.dev(\/|$)/.test(supabaseUrl) || supabaseUrl.includes("localhost");
+ if (!isCrbnDevHost) return supabaseUrl;
+ if (!port) {
+ throw new Error(
+ "seed: SUPABASE_URL looks like a crbn dev host but PORT_API is unset — run via `crbn` so .env.local is loaded."
+ );
+ }
+ return `http://host.docker.internal:${port}`;
+}
+
seed().catch((e) => {
console.error(e);
process.exit(1);
diff --git a/packages/dev/package.json b/packages/dev/package.json
index 632bf7e3ae..87888178f4 100644
--- a/packages/dev/package.json
+++ b/packages/dev/package.json
@@ -20,6 +20,7 @@
"cli-table3": "^0.6.5",
"dotenv": "16.3.1",
"execa": "^8.0.1",
+ "pathe": "^2.0.3",
"pg": "8.20.0",
"picocolors": "^1.1.1"
},
diff --git a/packages/dev/src/commands/copy.ts b/packages/dev/src/commands/copy.ts
index 6c4ef73f09..b572fa5401 100644
--- a/packages/dev/src/commands/copy.ts
+++ b/packages/dev/src/commands/copy.ts
@@ -1,6 +1,6 @@
import { copyFileSync, existsSync, readFileSync } from "node:fs";
-import { join } from "node:path";
import { intro, log, outro } from "@clack/prompts";
+import { join } from "pathe";
import pc from "picocolors";
import { mainCheckoutRoot } from "../git.js";
import { isAtLeastAsNew } from "../helpers.js";
diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.ts
index 7949f46f61..d29d15e63e 100644
--- a/packages/dev/src/commands/migrate.ts
+++ b/packages/dev/src/commands/migrate.ts
@@ -1,8 +1,8 @@
import { existsSync } from "node:fs";
-import { join } from "node:path";
import { intro, log, outro, tasks } from "@clack/prompts";
import { config as loadDotenv } from "dotenv";
import { execa } from "execa";
+import { join } from "pathe";
import { requireNumberEnv, tryConnect } from "../helpers.js";
import { applyMigrations } from "../services/migrations.js";
import { getWorktreeRoot } from "../worktree.js";
diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.ts
index 43490ff3b4..52a24b6d7a 100644
--- a/packages/dev/src/commands/new.ts
+++ b/packages/dev/src/commands/new.ts
@@ -1,6 +1,6 @@
import { copyFileSync, existsSync } from "node:fs";
-import { basename, dirname, join, relative, resolve } from "node:path";
import { intro, outro, tasks } from "@clack/prompts";
+import { basename, dirname, join, relative, resolve } from "pathe";
import pc from "picocolors";
import { addWorktree, currentBranch } from "../git.js";
import {
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index 1da8233f1b..d19716cc77 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -1,7 +1,7 @@
-import { join } from "node:path";
import { box, intro, log, outro, progress, tasks } from "@clack/prompts";
import { config as loadDotenv } from "dotenv";
import { execa } from "execa";
+import { join } from "pathe";
import type { AppId } from "../constants.js";
import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";
import { currentBranch, isLinkedWorktree } from "../git.js";
@@ -101,7 +101,7 @@ export async function up(opts: UpOpts = {}) {
await waitForServices(ctx);
await runDatabaseMigrations(ctx, { shouldMigrate, shouldRegen });
await setupPortless(ctx, selectedApps);
- ensureHostsFile();
+ await ensureHostsFile();
if (process.env.CARBON_EDITION === "cloud") {
spawnStripeListener(root);
@@ -339,7 +339,7 @@ async function setupPortless(ctx: Ctx, selectedApps: AppId[]) {
}
// Skip sudo sync when root daemon already auto-syncs, or hosts unchanged.
-function ensureHostsFile() {
+async function ensureHostsFile() {
if (proxyRunsAsRoot()) {
log.info("/etc/hosts auto-synced by root proxy daemon");
return;
@@ -349,7 +349,7 @@ function ensureHostsFile() {
return;
}
log.step("sudo portless hosts sync");
- return syncHostsFile();
+ await syncHostsFile();
}
async function runAppsThenTeardown(root: string, selectedApps: AppId[]) {
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index ce03ae5e4b..8ebfa03c71 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -1,5 +1,5 @@
import { existsSync, unlinkSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
+import { join } from "pathe";
import { APP_CHOICES } from "./constants.js";
import { type JwtCreds, type PortMap, SHARED_REDIS_PORT } from "./worktree.js";
diff --git a/packages/dev/src/git.ts b/packages/dev/src/git.ts
index 1d9e528b47..50e32ede24 100644
--- a/packages/dev/src/git.ts
+++ b/packages/dev/src/git.ts
@@ -1,5 +1,5 @@
-import { dirname, resolve } from "node:path";
import { execa } from "execa";
+import { dirname, resolve } from "pathe";
export type Worktree = {
path: string;
diff --git a/packages/dev/src/helpers.test.ts b/packages/dev/src/helpers.test.ts
index e2e3610bae..da788f2b67 100644
--- a/packages/dev/src/helpers.test.ts
+++ b/packages/dev/src/helpers.test.ts
@@ -1,7 +1,7 @@
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { createServer, type Server } from "node:net";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join } from "pathe";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { isAtLeastAsNew, requireNumberEnv, tryConnect } from "./helpers.js";
diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.ts
index 2af78092ed..490ed0927d 100644
--- a/packages/dev/src/prompts.ts
+++ b/packages/dev/src/prompts.ts
@@ -1,5 +1,4 @@
import { existsSync } from "node:fs";
-import { join } from "node:path";
import {
cancel,
confirm,
@@ -10,6 +9,7 @@ import {
select,
text
} from "@clack/prompts";
+import { join } from "pathe";
import pc from "picocolors";
import { APP_CHOICES, type AppId } from "./constants.js";
import { branchExists, deleteBranch, listWorktrees } from "./git.js";
diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.ts
index 5afa187659..71efab9b3e 100644
--- a/packages/dev/src/services/apps.ts
+++ b/packages/dev/src/services/apps.ts
@@ -1,5 +1,5 @@
-import { join } from "node:path";
import { type ExecaChildProcess, execa } from "execa";
+import { join } from "pathe";
import pc from "picocolors";
import { isAtLeastAsNew, onShutdown, readLines } from "../helpers.js";
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 06a9836cac..fdbeedf3b1 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
-import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { execa } from "execa";
+import { join } from "pathe";
import pg from "pg";
import { waitForPort } from "../helpers.js";
diff --git a/packages/dev/src/services/portless.test.ts b/packages/dev/src/services/portless.test.ts
deleted file mode 100644
index 9be5499e1e..0000000000
--- a/packages/dev/src/services/portless.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { portlessPrivilegedCmd } from "./portless.js";
-
-describe("portlessPrivilegedCmd", () => {
- it("runs portless directly on Windows (no sudo binary)", () => {
- expect(
- portlessPrivilegedCmd(["proxy", "start"], {
- platform: "win32",
- home: "C:\\Users\\someone"
- })
- ).toEqual({ file: "portless", args: ["proxy", "start"] });
- });
-
- it("wraps in sudo with HOME=... on POSIX shells", () => {
- expect(
- portlessPrivilegedCmd(["proxy", "start"], {
- platform: "linux",
- home: "/home/someone"
- })
- ).toEqual({
- file: "sudo",
- args: ["HOME=/home/someone", "portless", "proxy", "start"]
- });
- });
-});
diff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.ts
index 42eb0dc3cc..f58bc2cac2 100644
--- a/packages/dev/src/services/portless.ts
+++ b/packages/dev/src/services/portless.ts
@@ -23,27 +23,10 @@ function portlessEnv(): NodeJS.ProcessEnv {
return out;
}
-type SudoArgsOptions = {
- platform?: NodeJS.Platform;
- home?: string;
-};
-
-// Builds the privileged command for a portless invocation. On POSIX we
-// shell out to `sudo` (preserving HOME so portless state lands in the
-// user's ~/.portless rather than /var/root/.portless). On Windows there
-// is no `sudo` binary — the terminal itself must be elevated — so we
-// run `portless` directly. If the user isn't elevated, portless will
-// surface its own UAC / permission error, which is the right signal.
-export function portlessPrivilegedCmd(
- args: string[],
- options: SudoArgsOptions = {}
-): { file: string; args: string[] } {
- const platform = options.platform ?? process.platform;
- if (platform === "win32") {
- return { file: "portless", args };
- }
- const home = options.home ?? homedir();
- return { file: "sudo", args: [`HOME=${home}`, "portless", ...args] };
+// `sudo` preserves HOME so portless state lands in the user's ~/.portless
+// rather than /var/root/.portless.
+function sudoPortless(args: string[]): string[] {
+ return [`HOME=${homedir()}`, "portless", ...args];
}
export async function ensurePortlessInstalled() {
@@ -195,51 +178,37 @@ export async function ensureProxyPrivileges() {
].join("\n")
);
- const isWin = process.platform === "win32";
const proceed = await confirm({
- message: isWin
- ? "Set it up now? Will run portless to bind :443, install the local CA, and write the hosts file. Terminal must be elevated (Run as Administrator)."
- : "Set it up now? Will run sudo to bind :443, install the local CA, and write /etc/hosts entries.",
+ message:
+ "Set it up now? Will run sudo to bind :443, install the local CA, and write /etc/hosts entries.",
initialValue: true
});
if (isCancel(proceed) || !proceed) {
throw new Error(
- isWin
- ? "Aborted. From an elevated terminal run: `portless proxy stop && portless proxy start --tld dev && portless trust`. Then re-run `crbn up`."
- : "Aborted. Run manually: `sudo portless proxy stop && sudo portless proxy start --tld dev && sudo portless trust`. Then re-run `crbn up`."
+ "Aborted. Run manually: `sudo portless proxy stop && sudo portless proxy start --tld dev && sudo portless trust`. Then re-run `crbn up`."
);
}
- if (process.platform === "win32") {
- log.info(
- "running portless commands — terminal must be elevated (Run as Administrator)"
- );
- } else {
- log.info("running sudo commands — you'll be prompted for your password");
- }
+ log.info("running sudo commands — you'll be prompted for your password");
- const stopCmd = portlessPrivilegedCmd(["proxy", "stop"]);
- await execa(stopCmd.file, stopCmd.args, {
+ await execa("sudo", sudoPortless(["proxy", "stop"]), {
stdio: "inherit",
reject: false
});
- const startCmd = portlessPrivilegedCmd([
- "proxy",
- "start",
- "--tld",
- PORTLESS_TLD
- ]);
- const start = await execa(startCmd.file, startCmd.args, {
- stdio: "inherit",
- reject: false
- });
+ const start = await execa(
+ "sudo",
+ sudoPortless(["proxy", "start", "--tld", PORTLESS_TLD]),
+ {
+ stdio: "inherit",
+ reject: false
+ }
+ );
if (start.exitCode !== 0) {
throw new Error(`portless proxy start failed (exit ${start.exitCode})`);
}
- const trustCmd = portlessPrivilegedCmd(["trust"]);
- const trust = await execa(trustCmd.file, trustCmd.args, {
+ const trust = await execa("sudo", sudoPortless(["trust"]), {
stdio: "inherit",
reject: false
});
@@ -261,8 +230,7 @@ export async function ensureProxyPrivileges() {
// Push registered routes into /etc/hosts. Needs sudo; idempotent.
export async function syncHostsFile() {
- const hostsCmd = portlessPrivilegedCmd(["hosts", "sync"]);
- const r = await execa(hostsCmd.file, hostsCmd.args, {
+ const r = await execa("sudo", sudoPortless(["hosts", "sync"]), {
stdio: "inherit",
reject: false
});
diff --git a/packages/dev/src/worktree.test.ts b/packages/dev/src/worktree.test.ts
index b879b2a978..e87b4bf7a1 100644
--- a/packages/dev/src/worktree.test.ts
+++ b/packages/dev/src/worktree.test.ts
@@ -1,5 +1,8 @@
-import { describe, expect, it } from "vitest";
-import { slugify } from "./worktree.js";
+import { mkdtempSync, rmSync, symlinkSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "pathe";
+import { afterAll, describe, expect, it } from "vitest";
+import { sameWorktreePath, slugify } from "./worktree.js";
describe("slugify", () => {
it("lowercases", () => {
@@ -33,3 +36,26 @@ describe("slugify", () => {
expect(slugify("///")).toBe("");
});
});
+
+describe("sameWorktreePath", () => {
+ const real = mkdtempSync(join(tmpdir(), "carbon-worktree-"));
+ const link = `${real}-link`;
+ symlinkSync(real, link);
+
+ afterAll(() => {
+ rmSync(link, { force: true });
+ rmSync(real, { recursive: true, force: true });
+ });
+
+ it("treats a symlink and its real path as the same worktree", () => {
+ expect(sameWorktreePath(real, link)).toBe(true);
+ });
+
+ it("ignores trailing slashes", () => {
+ expect(sameWorktreePath(`${real}/`, real)).toBe(true);
+ });
+
+ it("distinguishes unrelated paths", () => {
+ expect(sameWorktreePath(real, tmpdir())).toBe(false);
+ });
+});
diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.ts
index 3e157d3d84..5f1a890c77 100644
--- a/packages/dev/src/worktree.ts
+++ b/packages/dev/src/worktree.ts
@@ -1,9 +1,15 @@
import { createHmac, randomBytes } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ writeFileSync
+} from "node:fs";
import net from "node:net";
import { homedir } from "node:os";
-import { basename, dirname, join } from "node:path";
import { execa } from "execa";
+import { basename, dirname, join, normalize } from "pathe";
// ---------------------------------------------------------------------------
// Types & constants
@@ -67,6 +73,22 @@ export function projectName(slug: string): string {
return `carbon-${slug}`;
}
+// Resolve symlinks + normalize separators / trailing slashes so two strings
+// pointing at the same worktree compare equal (e.g. /tmp/x vs symlinked path).
+function canonicalWorktreePath(input: string): string {
+ let p = input.trim();
+ try {
+ p = realpathSync.native(p);
+ } catch {
+ // Best-effort: fall through to string normalization.
+ }
+ return normalize(p).replace(/\/+$/, "");
+}
+
+export function sameWorktreePath(a: string, b: string): boolean {
+ return canonicalWorktreePath(a) === canonicalWorktreePath(b);
+}
+
export async function ensureSlugAvailable(slug: string, worktreeRoot: string) {
const project = projectName(slug);
let runningPath: string | null = null;
@@ -87,7 +109,7 @@ export async function ensureSlugAvailable(slug: string, worktreeRoot: string) {
} catch {
return;
}
- if (runningPath && runningPath !== worktreeRoot) {
+ if (runningPath && !sameWorktreePath(runningPath, worktreeRoot)) {
throw new Error(
`Slug "${slug}" is already in use by another worktree at:\n ${runningPath}\n\nSet CARBON_WORKTREE to a unique slug for this worktree, or stop the other stack.`
);
@@ -114,7 +136,7 @@ export async function resolveSlot(
const existing = registry[slug];
// Fast path: registry entry is valid and points at this worktree.
- if (existing && existing.worktreeRoot === worktreeRoot) {
+ if (existing && sameWorktreePath(existing.worktreeRoot, worktreeRoot)) {
return {
ports: existing.ports,
redisDb: existing.redisDb,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f674d54e78..922a0199dc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -666,7 +666,7 @@ importers:
'@novu/framework':
specifier: 2.10.0
'@novu/headless':
specifier: 2.7.0-alpha.0
version: 2.7.0-alpha.0
@@ -774,7 +774,7 @@ importers:
inngest:
specifier: ^3.52.7
intl-parse-accept-language:
specifier: 'catalog:'
version: 1.0.0
@@ -1888,6 +1888,9 @@ importers:
execa:
specifier: ^8.0.1
version: 8.0.1
+ pathe:
+ specifier: ^2.0.3
+ version: 2.0.3
pg:
specifier: 8.20.0
version: 8.20.0
@@ -14047,7 +14050,7 @@ snapshots:
dependencies:
'@novu/shared': 2.6.6
dependencies:
ajv: 8.18.0
ajv-formats: 2.1.1([email protected])
@@ -14060,7 +14063,7 @@ snapshots:
pluralize: 8.0.0
sanitize-html: 2.17.3
optionalDependencies:
- express: 5.2.1
+ express: 4.22.1
zod: 3.25.76
zod-to-json-schema: 3.25.2([email protected])
transitivePeerDependencies:
@@ -20456,6 +20459,43 @@ snapshots:
+ dependencies:
+ '@bufbuild/protobuf': 2.11.0
+ '@inngest/ai': 0.1.7
+ '@jpwilliams/waitgroup': 2.1.1
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/auto-instrumentations-node': 0.72.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))
+ '@opentelemetry/context-async-hooks': 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-http': 0.214.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.6.1(@opentelemetry/[email protected])
+ '@standard-schema/spec': 1.1.0
+ '@traceloop/instrumentation-anthropic': 0.20.0
+ '@types/debug': 4.1.13
+ '@types/ms': 2.1.0
+ canonicalize: 1.0.8
+ chalk: 4.1.2
+ cross-fetch: 4.1.0
+ debug: 4.4.3([email protected])
+ hash.js: 1.1.7
+ json-stringify-safe: 5.0.1
+ ms: 2.1.3
+ serialize-error-cjs: 0.1.4
+ strip-ansi: 5.2.0
+ temporal-polyfill: 0.2.5
+ ulid: 2.4.0
+ zod: 3.25.76
+ optionalDependencies:
+ express: 4.22.1
+ hono: 4.12.14
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - '@opentelemetry/core'
+ - encoding
+ - supports-color
+
dependencies:
'@bufbuild/protobuf': 2.11.0