From b91d5f86ce6129245620bd6a251bc7c5bb74eabc Mon Sep 17 00:00:00 2001 From: Rafael Thayto Date: Tue, 16 Jun 2026 20:07:20 -0300 Subject: [PATCH 1/5] fix(env): surface CLERK_PLATFORM_API_URL credential mismatch CLERK_PLATFORM_API_URL redirects API traffic to an arbitrary host, but credentials are keyed by environment name, not by URL, so the active env's token is sent to the override host with no isolation. Warn about this in human mode (agent/scripted output stays clean), and report the active environment and API URL in clerk doctor so the mismatch is visible. Refs #329 --- .../platform-api-url-credential-warning.md | 5 ++ packages/cli-core/src/cli-program.ts | 3 ++ .../cli-core/src/commands/doctor/checks.ts | 3 +- packages/cli-core/src/lib/environment.test.ts | 46 +++++++++++++++++++ packages/cli-core/src/lib/environment.ts | 22 +++++++++ 5 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 .changeset/platform-api-url-credential-warning.md create mode 100644 packages/cli-core/src/lib/environment.test.ts diff --git a/.changeset/platform-api-url-credential-warning.md b/.changeset/platform-api-url-credential-warning.md new file mode 100644 index 000000000..a34a01854 --- /dev/null +++ b/.changeset/platform-api-url-credential-warning.md @@ -0,0 +1,5 @@ +--- +"clerk": patch +--- + +Warn (in human mode) when `CLERK_PLATFORM_API_URL` routes requests to a host that differs from the active environment's URL, since credentials are keyed by environment name and not by URL. `clerk doctor` now also reports the active environment and its API URL so the mismatch is visible. diff --git a/packages/cli-core/src/cli-program.ts b/packages/cli-core/src/cli-program.ts index 9ea89cb54..641846c83 100644 --- a/packages/cli-core/src/cli-program.ts +++ b/packages/cli-core/src/cli-program.ts @@ -29,6 +29,7 @@ import { getCurrentEnvName, getAvailableEnvs, getPlapiBaseUrl, + warnIfPlatformApiUrlOverride, } from "./lib/environment.ts"; import { CliError, @@ -135,6 +136,8 @@ export function createProgram(): Program { if (activeEnv !== "production") { process.stderr.write(`[${activeEnv.toUpperCase()}]\n`); } + + warnIfPlatformApiUrlOverride(); }); // Show update notification after each command, except for commands that diff --git a/packages/cli-core/src/commands/doctor/checks.ts b/packages/cli-core/src/commands/doctor/checks.ts index b8bf9afad..53929eecb 100644 --- a/packages/cli-core/src/commands/doctor/checks.ts +++ b/packages/cli-core/src/commands/doctor/checks.ts @@ -16,6 +16,7 @@ import { formatChannelLabel, } from "../../lib/update-check.ts"; import { formatHostStateProbeFailures, getAgentHostStateProbe } from "../../lib/host-execution.ts"; +import { getCurrentEnvName, getPlapiBaseUrl } from "../../lib/environment.ts"; import { isAgent } from "../../mode.ts"; import type { CheckResult, DoctorContext, FixAction } from "./types.ts"; @@ -74,7 +75,7 @@ export async function checkLoggedIn(ctx: DoctorContext): Promise { remedy: "Run `clerk auth login` to authenticate.", }); } - return check.pass("Logged in (token found in credential store)"); + return check.pass(`Logged in — environment "${getCurrentEnvName()}", API ${getPlapiBaseUrl()}`); } export async function checkHostExecution(): Promise { diff --git a/packages/cli-core/src/lib/environment.test.ts b/packages/cli-core/src/lib/environment.test.ts new file mode 100644 index 000000000..59531c8a7 --- /dev/null +++ b/packages/cli-core/src/lib/environment.test.ts @@ -0,0 +1,46 @@ +import { test, expect, describe, beforeEach, afterEach } from "bun:test"; +import { getPlapiBaseUrl, warnIfPlatformApiUrlOverride } from "./environment.ts"; +import { setMode } from "../mode.ts"; +import { useCaptureLog } from "../test/lib/stubs.ts"; + +describe("warnIfPlatformApiUrlOverride", () => { + const captured = useCaptureLog(); + const original = process.env.CLERK_PLATFORM_API_URL; + + beforeEach(() => { + setMode("human"); + delete process.env.CLERK_PLATFORM_API_URL; + }); + + afterEach(() => { + setMode("human"); + if (original === undefined) delete process.env.CLERK_PLATFORM_API_URL; + else process.env.CLERK_PLATFORM_API_URL = original; + }); + + test("warns in human mode when the override differs from the active env URL", () => { + process.env.CLERK_PLATFORM_API_URL = "https://api.staging.example.com"; + warnIfPlatformApiUrlOverride(); + expect(captured.err).toContain("CLERK_PLATFORM_API_URL"); + expect(captured.err).toContain("production"); + }); + + test("does not warn when no override is set", () => { + warnIfPlatformApiUrlOverride(); + expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); + }); + + test("does not warn when the override equals the active env URL", () => { + const profileUrl = getPlapiBaseUrl(); // no override set → active env URL + process.env.CLERK_PLATFORM_API_URL = profileUrl; + warnIfPlatformApiUrlOverride(); + expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); + }); + + test("stays silent in agent mode to avoid corrupting machine-readable output", () => { + setMode("agent"); + process.env.CLERK_PLATFORM_API_URL = "https://api.staging.example.com"; + warnIfPlatformApiUrlOverride(); + expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); + }); +}); diff --git a/packages/cli-core/src/lib/environment.ts b/packages/cli-core/src/lib/environment.ts index a695badd3..e046227bc 100644 --- a/packages/cli-core/src/lib/environment.ts +++ b/packages/cli-core/src/lib/environment.ts @@ -11,6 +11,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; +import { isHuman } from "../mode.ts"; import { log } from "./log.ts"; export interface EnvProfileConfig { @@ -141,6 +142,27 @@ export function getPlapiBaseUrl(): string { return process.env.CLERK_PLATFORM_API_URL ?? getCurrentEnv().platformApiUrl; } +/** + * Warn when CLERK_PLATFORM_API_URL redirects requests to a host that differs + * from the active environment's platform URL. Credentials are keyed by + * environment name, not by URL, so the active env's token is what gets sent to + * the override host — surface that so it isn't a silent surprise. + * + * Human mode only: a per-command warning line would corrupt the machine-readable + * stderr that agent mode emits. Agent/scripted callers get the same information + * from the `clerk doctor` environment report instead. + */ +export function warnIfPlatformApiUrlOverride(): void { + if (!isHuman()) return; + const override = process.env.CLERK_PLATFORM_API_URL; + if (!override) return; + const envName = getCurrentEnvName(); + if (override === getCurrentEnv().platformApiUrl) return; + log.warn( + `CLERK_PLATFORM_API_URL is routing requests to ${override}, but credentials stay keyed to the "${envName}" environment — the "${envName}" token will be sent to that host.`, + ); +} + export function getBapiBaseUrl(): string { return process.env.CLERK_BACKEND_API_URL ?? getCurrentEnv().backendApiUrl; } From 2bbfd456439a4fe6442e8c6e1ff92203af37f912 Mon Sep 17 00:00:00 2001 From: Rafael Thayto Date: Thu, 18 Jun 2026 09:15:30 -0300 Subject: [PATCH 2/5] fix(env): normalize URLs before comparing to avoid spurious mismatch warnings Use new URL().href to normalize both the override and profile URL before comparing, so trailing slashes and host-case differences don't produce false positives. Falls back to raw string comparison when either URL is malformed. Also pin the test to a concrete literal ("https://api.clerk.com") instead of the self-referencing getPlapiBaseUrl() call, and strengthen the positive warning case by asserting the override host appears in the message. --- packages/cli-core/src/lib/environment.test.ts | 6 +++--- packages/cli-core/src/lib/environment.ts | 9 ++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/cli-core/src/lib/environment.test.ts b/packages/cli-core/src/lib/environment.test.ts index 59531c8a7..56ec3adb8 100644 --- a/packages/cli-core/src/lib/environment.test.ts +++ b/packages/cli-core/src/lib/environment.test.ts @@ -1,5 +1,5 @@ import { test, expect, describe, beforeEach, afterEach } from "bun:test"; -import { getPlapiBaseUrl, warnIfPlatformApiUrlOverride } from "./environment.ts"; +import { warnIfPlatformApiUrlOverride } from "./environment.ts"; import { setMode } from "../mode.ts"; import { useCaptureLog } from "../test/lib/stubs.ts"; @@ -23,6 +23,7 @@ describe("warnIfPlatformApiUrlOverride", () => { warnIfPlatformApiUrlOverride(); expect(captured.err).toContain("CLERK_PLATFORM_API_URL"); expect(captured.err).toContain("production"); + expect(captured.err).toContain("api.staging.example.com"); }); test("does not warn when no override is set", () => { @@ -31,8 +32,7 @@ describe("warnIfPlatformApiUrlOverride", () => { }); test("does not warn when the override equals the active env URL", () => { - const profileUrl = getPlapiBaseUrl(); // no override set → active env URL - process.env.CLERK_PLATFORM_API_URL = profileUrl; + process.env.CLERK_PLATFORM_API_URL = "https://api.clerk.com"; warnIfPlatformApiUrlOverride(); expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); }); diff --git a/packages/cli-core/src/lib/environment.ts b/packages/cli-core/src/lib/environment.ts index e046227bc..5354c98e7 100644 --- a/packages/cli-core/src/lib/environment.ts +++ b/packages/cli-core/src/lib/environment.ts @@ -157,7 +157,14 @@ export function warnIfPlatformApiUrlOverride(): void { const override = process.env.CLERK_PLATFORM_API_URL; if (!override) return; const envName = getCurrentEnvName(); - if (override === getCurrentEnv().platformApiUrl) return; + const normalize = (u: string) => { + try { + return new URL(u).href; + } catch { + return u; + } + }; + if (normalize(override) === normalize(getCurrentEnv().platformApiUrl)) return; log.warn( `CLERK_PLATFORM_API_URL is routing requests to ${override}, but credentials stay keyed to the "${envName}" environment — the "${envName}" token will be sent to that host.`, ); From 7d16c9eb96a06944f96fad517bf47042c2b64d4c Mon Sep 17 00:00:00 2001 From: Rafael Thayto Date: Mon, 22 Jun 2026 17:47:51 -0300 Subject: [PATCH 3/5] refactor(env): extract isPlatformApiUrlOverridden and move warn to call site Export `isPlatformApiUrlOverridden()` from environment.ts that returns the override/profile URLs and env name as data, rather than emitting the warning itself. Move the `log.warn` call to the preAction hook in cli-program.ts so the decision of whether/how to warn is at the call site, and so warnings go to stderr unconditionally (not just in human mode) since machine-readable stdout data is never polluted by stderr. Update integration tests to extract the JSON line from stderr before parsing so the warning line doesn't break `JSON.parse(result.stderr)`. --- packages/cli-core/src/cli-program.ts | 13 +++++- packages/cli-core/src/lib/environment.test.ts | 42 +++++++++---------- packages/cli-core/src/lib/environment.ts | 39 ++++++++++------- .../src/test/integration/error-codes.test.ts | 7 +++- .../src/test/integration/input-json.test.ts | 21 ++++++---- 5 files changed, 73 insertions(+), 49 deletions(-) diff --git a/packages/cli-core/src/cli-program.ts b/packages/cli-core/src/cli-program.ts index 641846c83..f77c5a5f6 100644 --- a/packages/cli-core/src/cli-program.ts +++ b/packages/cli-core/src/cli-program.ts @@ -29,7 +29,7 @@ import { getCurrentEnvName, getAvailableEnvs, getPlapiBaseUrl, - warnIfPlatformApiUrlOverride, + isPlatformApiUrlOverridden, } from "./lib/environment.ts"; import { CliError, @@ -137,7 +137,16 @@ export function createProgram(): Program { process.stderr.write(`[${activeEnv.toUpperCase()}]\n`); } - warnIfPlatformApiUrlOverride(); + // Warn when CLERK_PLATFORM_API_URL routes requests to a different host than + // the active environment's platform URL. Credentials are keyed by environment + // name, so the active env's token will be sent to the override host. Emitted + // to stderr so it never corrupts stdout data output. + const override = isPlatformApiUrlOverridden(); + if (override.overridden) { + log.warn( + `CLERK_PLATFORM_API_URL is routing requests to ${override.overrideUrl}, but credentials stay keyed to the "${override.envName}" environment — the "${override.envName}" token will be sent to that host.`, + ); + } }); // Show update notification after each command, except for commands that diff --git a/packages/cli-core/src/lib/environment.test.ts b/packages/cli-core/src/lib/environment.test.ts index 56ec3adb8..827c51e1d 100644 --- a/packages/cli-core/src/lib/environment.test.ts +++ b/packages/cli-core/src/lib/environment.test.ts @@ -1,46 +1,42 @@ import { test, expect, describe, beforeEach, afterEach } from "bun:test"; -import { warnIfPlatformApiUrlOverride } from "./environment.ts"; -import { setMode } from "../mode.ts"; -import { useCaptureLog } from "../test/lib/stubs.ts"; +import { isPlatformApiUrlOverridden } from "./environment.ts"; -describe("warnIfPlatformApiUrlOverride", () => { - const captured = useCaptureLog(); +describe("isPlatformApiUrlOverridden", () => { const original = process.env.CLERK_PLATFORM_API_URL; beforeEach(() => { - setMode("human"); delete process.env.CLERK_PLATFORM_API_URL; }); afterEach(() => { - setMode("human"); if (original === undefined) delete process.env.CLERK_PLATFORM_API_URL; else process.env.CLERK_PLATFORM_API_URL = original; }); - test("warns in human mode when the override differs from the active env URL", () => { + test("returns overridden=true with URLs when the override differs from the active env URL", () => { process.env.CLERK_PLATFORM_API_URL = "https://api.staging.example.com"; - warnIfPlatformApiUrlOverride(); - expect(captured.err).toContain("CLERK_PLATFORM_API_URL"); - expect(captured.err).toContain("production"); - expect(captured.err).toContain("api.staging.example.com"); + const result = isPlatformApiUrlOverridden(); + expect(result.overridden).toBe(true); + if (!result.overridden) return; + expect(result.overrideUrl).toBe("https://api.staging.example.com"); + expect(result.profileUrl).toBe("https://api.clerk.com"); + expect(result.envName).toBe("production"); }); - test("does not warn when no override is set", () => { - warnIfPlatformApiUrlOverride(); - expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); + test("returns overridden=false when no override is set", () => { + const result = isPlatformApiUrlOverridden(); + expect(result.overridden).toBe(false); }); - test("does not warn when the override equals the active env URL", () => { + test("returns overridden=false when the override equals the active env URL", () => { process.env.CLERK_PLATFORM_API_URL = "https://api.clerk.com"; - warnIfPlatformApiUrlOverride(); - expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); + const result = isPlatformApiUrlOverridden(); + expect(result.overridden).toBe(false); }); - test("stays silent in agent mode to avoid corrupting machine-readable output", () => { - setMode("agent"); - process.env.CLERK_PLATFORM_API_URL = "https://api.staging.example.com"; - warnIfPlatformApiUrlOverride(); - expect(captured.err).not.toContain("CLERK_PLATFORM_API_URL"); + test("returns overridden=false when URLs differ only by trailing slash", () => { + process.env.CLERK_PLATFORM_API_URL = "https://api.clerk.com/"; + const result = isPlatformApiUrlOverridden(); + expect(result.overridden).toBe(false); }); }); diff --git a/packages/cli-core/src/lib/environment.ts b/packages/cli-core/src/lib/environment.ts index 5354c98e7..ea6ae9d4a 100644 --- a/packages/cli-core/src/lib/environment.ts +++ b/packages/cli-core/src/lib/environment.ts @@ -11,7 +11,6 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; -import { isHuman } from "../mode.ts"; import { log } from "./log.ts"; export interface EnvProfileConfig { @@ -143,20 +142,28 @@ export function getPlapiBaseUrl(): string { } /** - * Warn when CLERK_PLATFORM_API_URL redirects requests to a host that differs - * from the active environment's platform URL. Credentials are keyed by - * environment name, not by URL, so the active env's token is what gets sent to - * the override host — surface that so it isn't a silent surprise. + * Returns whether CLERK_PLATFORM_API_URL is set to a URL that differs from the + * active environment's configured platform URL, along with both URLs so the + * caller can surface a warning. * - * Human mode only: a per-command warning line would corrupt the machine-readable - * stderr that agent mode emits. Agent/scripted callers get the same information - * from the `clerk doctor` environment report instead. + * Comparison normalises both URLs via `new URL().href` so trailing-slash and + * case differences are ignored; falls back to raw string comparison if either + * value is not a valid URL. */ -export function warnIfPlatformApiUrlOverride(): void { - if (!isHuman()) return; +export function isPlatformApiUrlOverridden(): + | { + overridden: false; + } + | { + overridden: true; + overrideUrl: string; + profileUrl: string; + envName: string; + } { const override = process.env.CLERK_PLATFORM_API_URL; - if (!override) return; - const envName = getCurrentEnvName(); + if (!override) return { overridden: false }; + + const profileUrl = getCurrentEnv().platformApiUrl; const normalize = (u: string) => { try { return new URL(u).href; @@ -164,10 +171,10 @@ export function warnIfPlatformApiUrlOverride(): void { return u; } }; - if (normalize(override) === normalize(getCurrentEnv().platformApiUrl)) return; - log.warn( - `CLERK_PLATFORM_API_URL is routing requests to ${override}, but credentials stay keyed to the "${envName}" environment — the "${envName}" token will be sent to that host.`, - ); + + if (normalize(override) === normalize(profileUrl)) return { overridden: false }; + + return { overridden: true, overrideUrl: override, profileUrl, envName: getCurrentEnvName() }; } export function getBapiBaseUrl(): string { diff --git a/packages/cli-core/src/test/integration/error-codes.test.ts b/packages/cli-core/src/test/integration/error-codes.test.ts index 06c81e83c..311675dfb 100644 --- a/packages/cli-core/src/test/integration/error-codes.test.ts +++ b/packages/cli-core/src/test/integration/error-codes.test.ts @@ -9,7 +9,12 @@ import { useIntegrationTestHarness, clerk, mockState } from "./lib/harness.ts"; useIntegrationTestHarness(); function parseJsonError(stderr: string): { code: string; message: string; docsUrl?: string } { - const parsed = JSON.parse(stderr); + const jsonLine = stderr + .split("\n") + .map((l) => l.trim()) + .find((l) => l.startsWith("{")); + if (!jsonLine) throw new SyntaxError(`No JSON line found in stderr:\n${stderr}`); + const parsed = JSON.parse(jsonLine); return parsed.error; } diff --git a/packages/cli-core/src/test/integration/input-json.test.ts b/packages/cli-core/src/test/integration/input-json.test.ts index 5dfdb500e..13ef92382 100644 --- a/packages/cli-core/src/test/integration/input-json.test.ts +++ b/packages/cli-core/src/test/integration/input-json.test.ts @@ -18,6 +18,15 @@ useIntegrationTestHarness(); const devInstance = getInstance(MOCK_APP, "development"); +function parseJsonFromStderr(stderr: string): { error: { code?: string } } { + const jsonLine = stderr + .split("\n") + .map((l) => l.trim()) + .find((l) => l.startsWith("{")); + if (!jsonLine) throw new SyntaxError(`No JSON line found in stderr:\n${stderr}`); + return JSON.parse(jsonLine) as { error: { code?: string } }; +} + beforeEach(async () => { await setProfile("github.com/test/project", { workspaceId: "", @@ -40,7 +49,7 @@ test("explicit CLI flags override --input-json values", async () => { const result = await clerk.raw("init", "--input-json", '{"mode":"human"}', "--mode", "agent"); expect(result.exitCode).not.toBe(0); // Agent mode emits structured JSON to stderr; human mode emits plain text. - const parsed = JSON.parse(result.stderr); + const parsed = parseJsonFromStderr(result.stderr); expect(parsed.error).toBeDefined(); }); @@ -234,16 +243,14 @@ test("--input-json is registered as a global option", async () => { // stderr is the agent-mode signature, which proves --mode agent was applied. const result = await clerk.raw("--input-json", '{"mode":"agent"}', "doctor", "--json"); expect(result.exitCode).not.toBe(0); - const jsonOutput = result.stderr.split("\n").findLast((line) => line.startsWith("{")); - expect(jsonOutput).toBeDefined(); - const parsed = JSON.parse(jsonOutput!); + const parsed = parseJsonFromStderr(result.stderr); expect(parsed.error).toBeDefined(); }); test("structured JSON error in agent mode for invalid JSON", async () => { const result = await clerk.raw("--mode", "agent", "init", "--input-json", "{bad}"); expect(result.exitCode).not.toBe(0); - const parsed = JSON.parse(result.stderr); + const parsed = parseJsonFromStderr(result.stderr); expect(parsed.error.code).toBe("invalid_json"); }); @@ -256,7 +263,7 @@ test("structured JSON error in agent mode for file not found", async () => { "@/tmp/does-not-exist-clerk.json", ); expect(result.exitCode).not.toBe(0); - const parsed = JSON.parse(result.stderr); + const parsed = parseJsonFromStderr(result.stderr); expect(parsed.error.code).toBe("file_not_found"); }); @@ -269,6 +276,6 @@ test("structured JSON error in agent mode for nested objects", async () => { '{"nested":{"key":"value"}}', ); expect(result.exitCode).not.toBe(0); - const parsed = JSON.parse(result.stderr); + const parsed = parseJsonFromStderr(result.stderr); expect(parsed.error.code).toBe("invalid_json"); }); From 53b8b08d97cd273de6ba13fcddd87bc9f7f1fda3 Mon Sep 17 00:00:00 2001 From: Rafael Thayto Tani Date: Fri, 26 Jun 2026 13:50:05 -0300 Subject: [PATCH 4/5] fix(env): gate CLERK_PLATFORM_API_URL warning on human mode log.warn is not mode-aware; without an isHuman() guard the warning leaks to stderr in agent mode, corrupting machine-readable output. Claude-Session: https://claude.ai/code/session_01Fch1D1a2XLtPBeMD7r5tED --- packages/cli-core/src/cli-program.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/cli-core/src/cli-program.ts b/packages/cli-core/src/cli-program.ts index f77c5a5f6..3ec1d98c1 100644 --- a/packages/cli-core/src/cli-program.ts +++ b/packages/cli-core/src/cli-program.ts @@ -42,7 +42,7 @@ import { throwUsageError, } from "./lib/errors.ts"; import { clerkHelpConfig, formatExamplesBlock, type Example } from "./lib/help.ts"; -import { isAgent } from "./mode.ts"; +import { isAgent, isHuman } from "./mode.ts"; import { log } from "./lib/log.ts"; import { maybeNotifyUpdate, getCurrentVersion } from "./lib/update-check.ts"; import { registerExtras } from "@clerk/cli-extras"; @@ -137,12 +137,13 @@ export function createProgram(): Program { process.stderr.write(`[${activeEnv.toUpperCase()}]\n`); } - // Warn when CLERK_PLATFORM_API_URL routes requests to a different host than - // the active environment's platform URL. Credentials are keyed by environment - // name, so the active env's token will be sent to the override host. Emitted - // to stderr so it never corrupts stdout data output. + // Warn (human mode only) when CLERK_PLATFORM_API_URL routes requests to a + // different host than the active environment's platform URL. Credentials are + // keyed by environment name, so the active env's token will be sent to the + // override host. Agent/scripted mode stays clean — stray lines on stderr + // corrupt machine-readable output; those callers get this info from `doctor`. const override = isPlatformApiUrlOverridden(); - if (override.overridden) { + if (override.overridden && isHuman()) { log.warn( `CLERK_PLATFORM_API_URL is routing requests to ${override.overrideUrl}, but credentials stay keyed to the "${override.envName}" environment — the "${override.envName}" token will be sent to that host.`, ); From 15dfd512cb490aed27347d3a2a835d735359a41f Mon Sep 17 00:00:00 2001 From: Rafael Thayto Date: Wed, 29 Jul 2026 09:18:10 -0300 Subject: [PATCH 5/5] refactor(env): rename getPlatformApiUrlOverride and surface it via log.debug in agent mode isPlatformApiUrlOverridden() returned a discriminated union, not a boolean, so rename it to match. Include profileUrl in the warning so the mismatch is self-diagnosing (shows both the override host and where traffic should be going), and log.debug the same info in agent/scripted mode instead of staying fully silent, so a --verbose re-run surfaces it without touching stderr in the default case. Also covers the new URL parse fallback branch with a test. Addresses review feedback from #344. --- packages/cli-core/src/cli-program.ts | 17 ++++++++------- packages/cli-core/src/lib/environment.test.ts | 21 +++++++++++++------ packages/cli-core/src/lib/environment.ts | 4 ++-- .../src/test/integration/error-codes.test.ts | 11 ++++------ .../src/test/integration/input-json.test.ts | 20 +++++++----------- .../src/test/integration/lib/harness.ts | 15 +++++++++++++ 6 files changed, 53 insertions(+), 35 deletions(-) diff --git a/packages/cli-core/src/cli-program.ts b/packages/cli-core/src/cli-program.ts index 3ec1d98c1..7207effaa 100644 --- a/packages/cli-core/src/cli-program.ts +++ b/packages/cli-core/src/cli-program.ts @@ -29,7 +29,7 @@ import { getCurrentEnvName, getAvailableEnvs, getPlapiBaseUrl, - isPlatformApiUrlOverridden, + getPlatformApiUrlOverride, } from "./lib/environment.ts"; import { CliError, @@ -140,13 +140,14 @@ export function createProgram(): Program { // Warn (human mode only) when CLERK_PLATFORM_API_URL routes requests to a // different host than the active environment's platform URL. Credentials are // keyed by environment name, so the active env's token will be sent to the - // override host. Agent/scripted mode stays clean — stray lines on stderr - // corrupt machine-readable output; those callers get this info from `doctor`. - const override = isPlatformApiUrlOverridden(); - if (override.overridden && isHuman()) { - log.warn( - `CLERK_PLATFORM_API_URL is routing requests to ${override.overrideUrl}, but credentials stay keyed to the "${override.envName}" environment — the "${override.envName}" token will be sent to that host.`, - ); + // override host. Agent/scripted mode stays off stderr — stray lines there + // corrupt machine-readable output — but still gets the info via `log.debug` + // so a `--verbose` re-run of a failing script surfaces it. + const override = getPlatformApiUrlOverride(); + if (override.overridden) { + const msg = `CLERK_PLATFORM_API_URL is routing requests to ${override.overrideUrl} instead of the "${override.envName}" environment's ${override.profileUrl} — the "${override.envName}" token will be sent to that host.`; + if (isHuman()) log.warn(msg); + else log.debug(`env: ${msg}`); } }); diff --git a/packages/cli-core/src/lib/environment.test.ts b/packages/cli-core/src/lib/environment.test.ts index 827c51e1d..e8872afff 100644 --- a/packages/cli-core/src/lib/environment.test.ts +++ b/packages/cli-core/src/lib/environment.test.ts @@ -1,7 +1,7 @@ import { test, expect, describe, beforeEach, afterEach } from "bun:test"; -import { isPlatformApiUrlOverridden } from "./environment.ts"; +import { getPlatformApiUrlOverride } from "./environment.ts"; -describe("isPlatformApiUrlOverridden", () => { +describe("getPlatformApiUrlOverride", () => { const original = process.env.CLERK_PLATFORM_API_URL; beforeEach(() => { @@ -15,7 +15,7 @@ describe("isPlatformApiUrlOverridden", () => { test("returns overridden=true with URLs when the override differs from the active env URL", () => { process.env.CLERK_PLATFORM_API_URL = "https://api.staging.example.com"; - const result = isPlatformApiUrlOverridden(); + const result = getPlatformApiUrlOverride(); expect(result.overridden).toBe(true); if (!result.overridden) return; expect(result.overrideUrl).toBe("https://api.staging.example.com"); @@ -24,19 +24,28 @@ describe("isPlatformApiUrlOverridden", () => { }); test("returns overridden=false when no override is set", () => { - const result = isPlatformApiUrlOverridden(); + const result = getPlatformApiUrlOverride(); expect(result.overridden).toBe(false); }); test("returns overridden=false when the override equals the active env URL", () => { process.env.CLERK_PLATFORM_API_URL = "https://api.clerk.com"; - const result = isPlatformApiUrlOverridden(); + const result = getPlatformApiUrlOverride(); expect(result.overridden).toBe(false); }); test("returns overridden=false when URLs differ only by trailing slash", () => { process.env.CLERK_PLATFORM_API_URL = "https://api.clerk.com/"; - const result = isPlatformApiUrlOverridden(); + const result = getPlatformApiUrlOverride(); expect(result.overridden).toBe(false); }); + + test("falls back to raw string comparison when the override is not a valid URL", () => { + process.env.CLERK_PLATFORM_API_URL = "not a url"; + const result = getPlatformApiUrlOverride(); + expect(result.overridden).toBe(true); + if (!result.overridden) return; + expect(result.overrideUrl).toBe("not a url"); + expect(result.profileUrl).toBe("https://api.clerk.com"); + }); }); diff --git a/packages/cli-core/src/lib/environment.ts b/packages/cli-core/src/lib/environment.ts index ea6ae9d4a..e135663ca 100644 --- a/packages/cli-core/src/lib/environment.ts +++ b/packages/cli-core/src/lib/environment.ts @@ -142,7 +142,7 @@ export function getPlapiBaseUrl(): string { } /** - * Returns whether CLERK_PLATFORM_API_URL is set to a URL that differs from the + * Checks whether CLERK_PLATFORM_API_URL is set to a URL that differs from the * active environment's configured platform URL, along with both URLs so the * caller can surface a warning. * @@ -150,7 +150,7 @@ export function getPlapiBaseUrl(): string { * case differences are ignored; falls back to raw string comparison if either * value is not a valid URL. */ -export function isPlatformApiUrlOverridden(): +export function getPlatformApiUrlOverride(): | { overridden: false; } diff --git a/packages/cli-core/src/test/integration/error-codes.test.ts b/packages/cli-core/src/test/integration/error-codes.test.ts index 311675dfb..f2da6f587 100644 --- a/packages/cli-core/src/test/integration/error-codes.test.ts +++ b/packages/cli-core/src/test/integration/error-codes.test.ts @@ -4,17 +4,14 @@ */ import { test, expect } from "bun:test"; -import { useIntegrationTestHarness, clerk, mockState } from "./lib/harness.ts"; +import { useIntegrationTestHarness, clerk, mockState, parseJsonFromStderr } from "./lib/harness.ts"; useIntegrationTestHarness(); function parseJsonError(stderr: string): { code: string; message: string; docsUrl?: string } { - const jsonLine = stderr - .split("\n") - .map((l) => l.trim()) - .find((l) => l.startsWith("{")); - if (!jsonLine) throw new SyntaxError(`No JSON line found in stderr:\n${stderr}`); - const parsed = JSON.parse(jsonLine); + const parsed = parseJsonFromStderr(stderr) as { + error: { code: string; message: string; docsUrl?: string }; + }; return parsed.error; } diff --git a/packages/cli-core/src/test/integration/input-json.test.ts b/packages/cli-core/src/test/integration/input-json.test.ts index 13ef92382..53d3b9541 100644 --- a/packages/cli-core/src/test/integration/input-json.test.ts +++ b/packages/cli-core/src/test/integration/input-json.test.ts @@ -11,6 +11,7 @@ import { clerk, getInstance, MOCK_APP, + parseJsonFromStderr, } from "./lib/harness.ts"; import { join } from "node:path"; @@ -18,13 +19,8 @@ useIntegrationTestHarness(); const devInstance = getInstance(MOCK_APP, "development"); -function parseJsonFromStderr(stderr: string): { error: { code?: string } } { - const jsonLine = stderr - .split("\n") - .map((l) => l.trim()) - .find((l) => l.startsWith("{")); - if (!jsonLine) throw new SyntaxError(`No JSON line found in stderr:\n${stderr}`); - return JSON.parse(jsonLine) as { error: { code?: string } }; +function parseStructuredError(stderr: string): { error: { code?: string } } { + return parseJsonFromStderr(stderr) as { error: { code?: string } }; } beforeEach(async () => { @@ -49,7 +45,7 @@ test("explicit CLI flags override --input-json values", async () => { const result = await clerk.raw("init", "--input-json", '{"mode":"human"}', "--mode", "agent"); expect(result.exitCode).not.toBe(0); // Agent mode emits structured JSON to stderr; human mode emits plain text. - const parsed = parseJsonFromStderr(result.stderr); + const parsed = parseStructuredError(result.stderr); expect(parsed.error).toBeDefined(); }); @@ -243,14 +239,14 @@ test("--input-json is registered as a global option", async () => { // stderr is the agent-mode signature, which proves --mode agent was applied. const result = await clerk.raw("--input-json", '{"mode":"agent"}', "doctor", "--json"); expect(result.exitCode).not.toBe(0); - const parsed = parseJsonFromStderr(result.stderr); + const parsed = parseStructuredError(result.stderr); expect(parsed.error).toBeDefined(); }); test("structured JSON error in agent mode for invalid JSON", async () => { const result = await clerk.raw("--mode", "agent", "init", "--input-json", "{bad}"); expect(result.exitCode).not.toBe(0); - const parsed = parseJsonFromStderr(result.stderr); + const parsed = parseStructuredError(result.stderr); expect(parsed.error.code).toBe("invalid_json"); }); @@ -263,7 +259,7 @@ test("structured JSON error in agent mode for file not found", async () => { "@/tmp/does-not-exist-clerk.json", ); expect(result.exitCode).not.toBe(0); - const parsed = parseJsonFromStderr(result.stderr); + const parsed = parseStructuredError(result.stderr); expect(parsed.error.code).toBe("file_not_found"); }); @@ -276,6 +272,6 @@ test("structured JSON error in agent mode for nested objects", async () => { '{"nested":{"key":"value"}}', ); expect(result.exitCode).not.toBe(0); - const parsed = parseJsonFromStderr(result.stderr); + const parsed = parseStructuredError(result.stderr); expect(parsed.error.code).toBe("invalid_json"); }); diff --git a/packages/cli-core/src/test/integration/lib/harness.ts b/packages/cli-core/src/test/integration/lib/harness.ts index 5c08e7599..787ac6981 100644 --- a/packages/cli-core/src/test/integration/lib/harness.ts +++ b/packages/cli-core/src/test/integration/lib/harness.ts @@ -503,6 +503,21 @@ clerkStrict.raw = execCLI; */ export const clerk = clerkStrict; +/** + * Extract and parse the last `{`-prefixed line from a command's stderr — + * the structured JSON error/output that agent mode emits. Uses `findLast` + * (not `find`) because stderr can carry other JSON-shaped lines (e.g. debug + * output) before the actual payload; the payload is always the last one. + */ +export function parseJsonFromStderr(stderr: string): unknown { + const jsonLine = stderr + .split("\n") + .map((l) => l.trim()) + .findLast((l) => l.startsWith("{")); + if (!jsonLine) throw new SyntaxError(`No JSON line found in stderr:\n${stderr}`); + return JSON.parse(jsonLine); +} + // ── Test harness ───────────────────────────────────────────────────────────── export interface TestHarness {