Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): keep oauth tokens out of agent cli environments (#106212)

Brandon0501ae4b7ac4
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.ts
index cd3971b09994..738373c40845 100644
--- a/products/desktop/apps/code/src/main/di/bindings.ts
+++ b/products/desktop/apps/code/src/main/di/bindings.ts
@@ -2,6 +2,7 @@ import type { AuthService } from "@posthog/core/auth/auth";
import type { AUTH_SERVICE } from "@posthog/core/auth/auth.module";
import type {
AUTH_CONNECTIVITY,
+ AUTH_FETCH_EXTRA_ORIGINS,
AUTH_OAUTH_FLOW_SERVICE,
AUTH_PREFERENCE_STORE,
AUTH_SESSION_STORE,
@@ -389,6 +390,7 @@ export interface MainBindings {
[AUTH_TOKEN_CIPHER]: TokenCipherPortAdapter;
[AUTH_CONNECTIVITY]: ConnectivityService;
[AUTH_TOKEN_OVERRIDE]: string | null;
+ [AUTH_FETCH_EXTRA_ORIGINS]: readonly string[];
[MAIN_AUTH_SERVICE]: AuthService;
[AUTH_SERVICE]: AuthService;
diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.ts
index 6d82831840ac..167a89d9bb39 100644
--- a/products/desktop/apps/code/src/main/di/container.ts
+++ b/products/desktop/apps/code/src/main/di/container.ts
@@ -14,6 +14,7 @@ import { AuthService } from "@posthog/core/auth/auth";
import { AUTH_SERVICE } from "@posthog/core/auth/auth.module";
import {
AUTH_CONNECTIVITY,
+ AUTH_FETCH_EXTRA_ORIGINS,
AUTH_OAUTH_FLOW_SERVICE,
AUTH_PREFERENCE_STORE,
AUTH_SESSION_STORE,
@@ -422,6 +423,13 @@ container.bind(CONNECTIVITY_CLIENT).toService(WS_CONNECTIVITY_SERVICE);
container
.bind(AUTH_TOKEN_OVERRIDE)
.toConstantValue(process.env.VITE_POSTHOG_ACCESS_TOKEN_OVERRIDE ?? null);
+container
+ .bind(AUTH_FETCH_EXTRA_ORIGINS)
+ .toConstantValue(
+ [process.env.POSTHOG_MCP_URL, process.env.POSTHOG_PROXY_BASE_URL].filter(
+ (value): value is string => Boolean(value),
+ ),
+ );
container.bind(MAIN_AUTH_SERVICE).to(AuthService);
container.bind(AUTH_SERVICE).toService(MAIN_AUTH_SERVICE);
container.load(feedbackCoreModule);
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
index 342542f53a00..d62945c32cf6 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts
@@ -28,11 +28,10 @@ import type {
} from "@posthog/workspace-server/services/agent/ports";
import type { AuthProxyService } from "@posthog/workspace-server/services/auth-proxy/auth-proxy";
import { AUTH_PROXY_SERVICE } from "@posthog/workspace-server/services/auth-proxy/identifiers";
+import { AUTH_PROXY_PLACEHOLDER_CREDENTIAL as PROXY_API_KEY } from "@posthog/workspace-server/services/auth-proxy/ports";
import type { PiRpcClientFactory } from "@posthog/workspace-server/services/pi-session/identifiers";
import { inject, injectable } from "inversify";
-const PROXY_API_KEY = "posthog-code-auth-proxy";
-
@injectable()
export class DesktopPiRpcClientFactory implements PiRpcClientFactory {
constructor(
diff --git a/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts b/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts
index 99052be9dac2..bab14b1da8cc 100644
--- a/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts
+++ b/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts
@@ -10,6 +10,7 @@ const {
mockProcessTracking,
mockWorkspaceService,
mockCleanupAllCodexHomes,
+ mockCleanupAllPinnedSettings,
mockTrackAppEvent,
mockShutdownPostHog,
mockShutdownOtelTransport,
@@ -33,6 +34,7 @@ const {
waitForPendingCreations: vi.fn(() => Promise.resolve()),
},
mockCleanupAllCodexHomes: vi.fn(() => Promise.resolve()),
+ mockCleanupAllPinnedSettings: vi.fn(() => Promise.resolve()),
mockProcessTracking: {
getSnapshot: vi.fn(() =>
Promise.resolve({
@@ -103,6 +105,10 @@ vi.mock("@posthog/workspace-server/services/agent/codex-home", () => ({
cleanupAllCodexHomes: mockCleanupAllCodexHomes,
}));
+vi.mock("@posthog/agent/adapters/claude/session/pinned-settings", () => ({
+ cleanupAllPinnedSettings: mockCleanupAllPinnedSettings,
+}));
+
describe("AppLifecycleService", () => {
let service: AppLifecycleService;
const originalProcessExit = process.exit;
@@ -190,6 +196,14 @@ describe("AppLifecycleService", () => {
expect(mockCleanupAllCodexHomes).toHaveBeenCalledWith("/app-data");
});
+ it("removes pinned Claude settings files", async () => {
+ const promise = service.shutdown();
+ await vi.runAllTimersAsync();
+ await promise;
+
+ expect(mockCleanupAllPinnedSettings).toHaveBeenCalledOnce();
+ });
+
it("tracks app quit event", async () => {
const promise = service.shutdown();
await vi.runAllTimersAsync();
diff --git a/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts b/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts
index 3707a619c70c..b30b0442ceb4 100644
--- a/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts
+++ b/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts
@@ -1,3 +1,4 @@
+import { cleanupAllPinnedSettings } from "@posthog/agent/adapters/claude/session/pinned-settings";
import {
APP_LIFECYCLE_SERVICE,
type IAppLifecycle,
@@ -275,6 +276,12 @@ export class AppLifecycleService {
log.warn("Failed to clean Codex state", error);
}
+ try {
+ await cleanupAllPinnedSettings();
+ } catch (error) {
+ log.warn("Failed to clean pinned Claude settings", error);
+ }
+
// Drain pending native callbacks (e.g. @parcel/watcher ThreadSafeFunction)
// so they fire while JS is still alive, not during FreeEnvironment teardown
await new Promise((resolve) => setImmediate(resolve));
diff --git a/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts b/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts
index 3e8c9187b83c..9b6beb21476b 100644
--- a/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts
+++ b/products/desktop/apps/code/src/main/utils/otel-log-transport.test.ts
@@ -192,6 +192,65 @@ describe("otel-log-transport", () => {
);
});
+ it("redacts tokens, secret headers and the proxy path token before export", async () => {
+ vi.stubEnv("VITE_POSTHOG_API_KEY", "phc_test123");
+ vi.stubEnv("VITE_POSTHOG_API_HOST", "https://test.posthog.com");
+
+ const { initOtelTransport } = await import(
+ "@main/utils/otel-log-transport"
+ );
+ const transport = initOtelTransport("info");
+
+ transport({
+ level: "info",
+ data: [
+ "minted phe_secret1 for pha_secret2",
+ {
+ headers: { authorization: "Bearer anything" },
+ refresh: "phr_secret3",
+ },
+ new Error(`proxy http://127.0.0.1:5000/${"t".repeat(43)}/v1 failed`),
+ ],
+ date: new Date(),
+ } as never);
+
+ const body = mockEmit.mock.calls[0][0].body as string;
+ for (const secret of [
+ "secret1",
+ "secret2",
+ "secret3",
+ "Bearer anything",
+ "t".repeat(43),
+ ]) {
+ expect(body).not.toContain(secret);
+ }
+ expect(body).toContain("[REDACTED]");
+ });
+
+ it("masks name/value header records and redacts the String() fallback", async () => {
+ const { formatBody } = await import("@main/utils/otel-log-transport");
+
+ expect(
+ formatBody([[{ name: "Authorization", value: "Bearer abc123" }]]),
+ ).toBe('[{"name":"Authorization","value":"[REDACTED]"}]');
+ expect(formatBody([["pha_secret5", 1n]])).toBe("[REDACTED],1");
+ });
+
+ it("falls back to String() for a circular value without walking it", async () => {
+ const { formatBody } = await import("@main/utils/otel-log-transport");
+ let reads = 0;
+ const circular: Record<string, unknown> = {
+ get token() {
+ reads += 1;
+ return "pha_secret4";
+ },
+ };
+ circular.self = circular;
+
+ expect(formatBody([circular])).toBe("[object Object]");
+ expect(reads).toBe(1);
+ });
+
it("formats Error objects with message and stack", async () => {
vi.stubEnv("VITE_POSTHOG_API_KEY", "phc_test123");
vi.stubEnv("VITE_POSTHOG_API_HOST", "https://test.posthog.com");
diff --git a/products/desktop/apps/code/src/main/utils/otel-log-transport.ts b/products/desktop/apps/code/src/main/utils/otel-log-transport.ts
index acc4090fef4c..643b7b894fe1 100644
--- a/products/desktop/apps/code/src/main/utils/otel-log-transport.ts
+++ b/products/desktop/apps/code/src/main/utils/otel-log-transport.ts
@@ -6,6 +6,10 @@ import {
LoggerProvider,
} from "@opentelemetry/sdk-logs";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
+import {
+ redactSecrets,
+ secretHeaderReplacer,
+} from "@posthog/agent/utils/redact-secrets";
import type ElectronLog from "electron-log";
import { getAppVersion } from "./env";
@@ -18,15 +22,17 @@ const SEVERITY_TEXT: Record<string, string> = {
let loggerProvider: LoggerProvider | null = null;
-function formatBody(data: unknown[]): string {
+export function formatBody(data: unknown[]): string {
return data
.map((item) => {
- if (typeof item === "string") return item;
- if (item instanceof Error) return `${item.message}\n${item.stack ?? ""}`;
+ if (typeof item === "string") return redactSecrets(item);
+ if (item instanceof Error) {
+ return redactSecrets(`${item.message}\n${item.stack ?? ""}`);
+ }
try {
- return JSON.stringify(item);
+ return redactSecrets(JSON.stringify(item, secretHeaderReplacer));
} catch {
- return String(item);
+ return redactSecrets(String(item));
}
})
.join(" ");
diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.json
index 307dd345a9e8..22ca22e77b48 100644
--- a/products/desktop/packages/agent/package.json
+++ b/products/desktop/packages/agent/package.json
@@ -60,6 +60,10 @@
"types": "./dist/types.d.ts",
"import": "./dist/types.js"
},
+ "./utils/redact-secrets": {
+ "types": "./dist/utils/redact-secrets.d.ts",
+ "import": "./dist/utils/redact-secrets.js"
+ },
"./adapters/claude/questions/utils": {
"types": "./dist/adapters/claude/questions/utils.d.ts",
"import": "./dist/adapters/claude/questions/utils.js"
@@ -84,6 +88,10 @@
"types": "./dist/adapters/claude/machine-auth.d.ts",
"import": "./dist/adapters/claude/machine-auth.js"
},
+ "./adapters/claude/session/pinned-settings": {
+ "types": "./dist/adapters/claude/session/pinned-settings.d.ts",
+ "import": "./dist/adapters/claude/session/pinned-settings.js"
+ },
"./adapters/claude/subscription-login": {
"types": "./dist/adapters/claude/subscription-login.d.ts",
"import": "./dist/adapters/claude/subscription-login.js"
diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.codex.test.ts b/products/desktop/packages/agent/src/adapters/acp-connection.codex.test.ts
new file mode 100644
index 000000000000..d21190eeb139
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/acp-connection.codex.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it, vi } from "vitest";
+
+const codexAgentOptions = vi.hoisted(() => [] as unknown[]);
+
+vi.mock("./codex-app-server/binary-path", () => ({
+ nativeCodexBinaryPath: () => "/bin/codex",
+}));
+vi.mock("./codex-app-server/codex-app-server-agent", () => ({
+ CodexAppServerAgent: vi.fn(function (this: unknown, _client, options) {
+ codexAgentOptions.push(options);
+ return {};
+ }),
+}));
+
+import { createAcpConnection } from "./acp-connection";
+
+describe("createAcpConnection codex options", () => {
+ it("forwards the config-file base URL flag to the codex process", async () => {
+ const connection = createAcpConnection({
+ adapter: "codex",
+ taskRunId: "run-1",
+ taskId: "task-1",
+ codexOptions: {
+ apiBaseUrl: "http://127.0.0.1:5000/token/v1",
+ apiBaseUrlInConfig: true,
+ codexHome: "/tmp/codex-home",
+ },
+ });
+
+ await vi.waitFor(() => expect(codexAgentOptions).toHaveLength(1));
+ expect(codexAgentOptions[0]).toMatchObject({
+ processOptions: {
+ apiBaseUrl: "http://127.0.0.1:5000/token/v1",
+ apiBaseUrlInConfig: true,
+ codexHome: "/tmp/codex-home",
+ },
+ });
+ await connection.cleanup().catch(() => undefined);
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.ts b/products/desktop/packages/agent/src/adapters/acp-connection.ts
index 4a686b043296..ac148bcc5700 100644
--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts
+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts
@@ -244,6 +244,7 @@ function createCodexConnection(config: AcpConnectionConfig): AcpConnection {
binaryPath: nativeBinary,
cwd: codexOptions.cwd,
apiBaseUrl: codexOptions.apiBaseUrl,
+ apiBaseUrlInConfig: codexOptions.apiBaseUrlInConfig,
apiKey: codexOptions.apiKey,
codexHome: codexOptions.codexHome,
useMachineAuth: codexOptions.useMachineAuth,
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
index 22fd1ec072bc..b382c451836a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts
@@ -1,4 +1,5 @@
import * as fs from "node:fs";
+import * as path from "node:path";
import type { AgentSideConnection } from "@agentclientprotocol/sdk";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { POSTHOG_METHODS, POSTHOG_NOTIFICATIONS } from "../../acp-extensions";
@@ -166,6 +167,23 @@ function installFakeSession(
return { session, oldQuery, endSpy, abortController };
}
+function pinSettingsFile(
+ session: { queryOptions: object },
+ sessionId: string,
+): string {
+ const dir = path.join(
+ process.env.CLAUDE_CONFIG_DIR ?? "",
+ "posthog-session-settings",
+ );
+ fs.mkdirSync(dir, { recursive: true });
+ const file = path.join(dir, `${sessionId}.json`);
+ fs.writeFileSync(file, "{}");
+ (session.queryOptions as { extraArgs?: Record<string, string> }).extraArgs = {
+ settings: file,
+ };
+ return file;
+}
+
function findUpdate(
client: ClientMocks,
sessionUpdate: string,
@@ -562,6 +580,18 @@ describe("ClaudeAcpAgent /clear", () => {
).toBeDefined();
});
+ it("removes the pinned settings file when the query stream closes", () => {
+ const { agent } = makeAgent();
+ const { session } = installFakeSession(agent, "s-pinned");
+ const file = pinSettingsFile(session, "s-pinned");
+
+ (
+ agent as unknown as { closeQueryStream(session: unknown): void }
+ ).closeQueryStream(session);
+
+ expect(fs.existsSync(file)).toBe(false);
+ });
+
it("closes the session and reports clearing_failed when the fresh session fails to initialize", async () => {
// A non-timeout failure (SDK subprocess crash) must get the same
// treatment as a timeout: terminate the unproven replacement, close the
@@ -569,6 +599,7 @@ describe("ClaudeAcpAgent /clear", () => {
// it spinning with the session half-swapped.
const { agent, client } = makeAgent();
const { session } = installFakeSession(agent, "s-init-crash");
+ const pinned = pinSettingsFile(session, "s-init-crash");
const init = deferInit();
const promptPromise = agent.prompt({
@@ -579,12 +610,14 @@ describe("ClaudeAcpAgent /clear", () => {
/SDK subprocess crashed/,
);
await vi.waitFor(() => expect(createdQueries).toHaveLength(1));
+ expect(fs.existsSync(pinned)).toBe(true);
init.reject(new Error("SDK subprocess crashed"));
await rejection;
expect((session as unknown as { queryClosed: boolean }).queryClosed).toBe(
true,
);
+ expect(fs.existsSync(pinned)).toBe(false);
// The failed replacement query is torn down, not leaked.
expect(createdQueries).toHaveLength(1);
expect(createdQueries[0].close).toHaveBeenCalled();
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts
index e3e8b5c0a731..1d754e757872 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.refresh.test.ts
@@ -1,3 +1,5 @@
+import * as fs from "node:fs";
+import * as path from "node:path";
import {
type AgentSideConnection,
RequestError,
@@ -187,6 +189,20 @@ function installFakeSession(
};
}
+function pinSettingsFile(session: object, sessionId: string): string {
+ const dir = path.join(
+ process.env.CLAUDE_CONFIG_DIR ?? "",
+ "posthog-session-settings",
+ );
+ fs.mkdirSync(dir, { recursive: true });
+ const file = path.join(dir, `${sessionId}.json`);
+ fs.writeFileSync(file, "{}");
+ (
+ session as { queryOptions: { extraArgs?: Record<string, string> } }
+ ).queryOptions.extraArgs = { settings: file };
+ return file;
+}
+
const freshMcpServers = [
{
name: "posthog",
@@ -490,6 +506,7 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {
// instead of pushing into the retired input stream.
const { agent } = makeAgent();
const { session } = installFakeSession(agent, "s-init-crash");
+ const pinned = pinSettingsFile(session, "s-init-crash");
const init = deferInit();
const refreshPromise = agent.extMethod(POSTHOG_METHODS.REFRESH_SESSION, {
@@ -499,12 +516,14 @@ describe("ClaudeAcpAgent.extMethod refresh_session", () => {
/SDK subprocess crashed/,
);
await vi.waitFor(() => expect(createdQueries).toHaveLength(1));
+ expect(fs.existsSync(pinned)).toBe(true);
init.reject(new Error("SDK subprocess crashed"));
await rejection;
expect((session as unknown as { queryClosed: boolean }).queryClosed).toBe(
true,
);
+ expect(fs.existsSync(pinned)).toBe(false);
// The failed replacement query is torn down, not leaked.
expect(createdQueries).toHaveLength(1);
expect(createdQueries[0].close).toHaveBeenCalled();
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts
index c377cc536ce2..e7335e0f3e71 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts
@@ -1,4 +1,10 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
@@ -73,6 +79,7 @@ vi.mock("../../gateway-models", async (importOriginal) => {
vi.mock("./mcp/tool-metadata", () => ({
fetchMcpToolMetadata: vi.fn().mockResolvedValue(undefined),
+ getCachedMcpTools: vi.fn().mockReturnValue([]),
getConnectedMcpServerNames: vi.fn().mockReturnValue([]),
setMcpToolApprovalStates: vi.fn(),
getMcpToolApprovalState: vi.fn().mockReturnValue("approved"),
@@ -784,4 +791,148 @@ describe("ClaudeAcpAgent session creation", () => {
}
await vi.waitFor(() => expect(extNotification).toHaveBeenCalledTimes(2));
});
+
+ it.skipIf(process.platform === "win32")(
+ "detects the traceparent hook inside a pinned gateway settings file",
+ async () => {
+ const client = {
+ sessionUpdate: vi.fn().mockResolvedValue(undefined),
+ extNotification: vi.fn().mockResolvedValue(undefined),
+ } as unknown as AgentSideConnection;
+ const agent = new ClaudeAcpAgent(client, {
+ gatewayEnv: {
+ anthropicBaseUrl: "http://127.0.0.1:1",
+ anthropicAuthToken: "tok",
+ openaiBaseUrl: "http://127.0.0.1:1/v1",
+ openaiApiKey: "tok",
+ },
+ });
+
+ await agent.newSession({ cwd, mcpServers: [] });
+
+ const settings = createdQueryOptions[0]?.extraArgs?.settings;
+ expect(settings?.startsWith(configDir)).toBe(true);
+ expect(
+ (agent as unknown as { session: { traceparentHookInstalled: boolean } })
+ .session.traceparentHookInstalled,
+ ).toBe(true);
+ },
+ );
+
+ it.skipIf(process.platform === "win32")(
+ "removes pinned settings on replacement and close, keeping a shared file",
+ async () => {
+ const client = {
+ sessionUpdate: vi.fn().mockResolvedValue(undefined),
+ extNotification: vi.fn().mockResolvedValue(undefined),
+ } as unknown as AgentSideConnection;
+ const agent = new ClaudeAcpAgent(client, {
+ gatewayEnv: {
+ anthropicBaseUrl: "http://127.0.0.1:1",
+ anthropicAuthToken: "tok",
+ openaiBaseUrl: "http://127.0.0.1:1/v1",
+ openaiApiKey: "tok",
+ },
+ });
+ const settingsOf = (index: number) =>
+ String(createdQueryOptions[index]?.extraArgs?.settings);
+
+ const { sessionId } = await agent.newSession({ cwd, mcpServers: [] });
+ // Detach the live id so the resume rebuilds the same session.
+ const live = agent as unknown as {
+ sessionId: string;
+ session: { sdkSessionId: string };
+ };
+ live.sessionId = "detached";
+ live.session.sdkSessionId = "detached";
+ await agent.resumeSession({ sessionId, cwd, mcpServers: [] });
+ expect(settingsOf(1)).toBe(settingsOf(0));
+ expect(existsSync(settingsOf(0))).toBe(true);
+
+ await agent.newSession({ cwd, mcpServers: [] });
+ expect(existsSync(settingsOf(0))).toBe(false);
+ expect(existsSync(settingsOf(2))).toBe(true);
+
+ await agent.closeSession();
+ await agent.closeSession();
+ expect(existsSync(settingsOf(2))).toBe(false);
+ },
+ );
+
+ it.skipIf(process.platform === "win32").each(["new", "resume"] as const)(
+ "removes pinned settings when %s session init fails",
+ async (kind) => {
+ let rejectInit!: (error: Error) => void;
+ nextInitPromise = new Promise((_, reject) => {
+ rejectInit = reject;
+ });
+ const client = {
+ sessionUpdate: vi.fn().mockResolvedValue(undefined),
+ extNotification: vi.fn().mockResolvedValue(undefined),
+ } as unknown as AgentSideConnection;
+ const agent = new ClaudeAcpAgent(client, {
+ gatewayEnv: {
+ anthropicBaseUrl: "http://127.0.0.1:1",
+ anthropicAuthToken: "tok",
+ openaiBaseUrl: "http://127.0.0.1:1/v1",
+ openaiApiKey: "tok",
+ },
+ });
+ const params = {
+ sessionId: "0197a000-0000-7000-8000-0000000000fc",
+ cwd,
+ mcpServers: [],
+ };
+
+ const promise =
+ kind === "new" ? agent.newSession(params) : agent.resumeSession(params);
+ const rejection = expect(promise).rejects.toBeInstanceOf(Error);
+ await vi.waitFor(() => expect(createdQueries).toHaveLength(1));
+ const settings = String(createdQueryOptions[0]?.extraArgs?.settings);
+ expect(settings.startsWith(configDir)).toBe(true);
+ expect(existsSync(settings)).toBe(true);
+ rejectInit(new Error("init boom"));
+ await rejection;
+
+ expect(existsSync(settings)).toBe(false);
+ },
+ );
+
+ it.skipIf(process.platform === "win32")(
+ "removes pinned settings when startup configuration fails after init",
+ async () => {
+ let rejectSetModel!: (error: Error) => void;
+ nextSetModel = () =>
+ new Promise((_, reject) => {
+ rejectSetModel = reject;
+ });
+ const client = {
+ sessionUpdate: vi.fn().mockResolvedValue(undefined),
+ extNotification: vi.fn().mockResolvedValue(undefined),
+ } as unknown as AgentSideConnection;
+ const agent = new ClaudeAcpAgent(client, {
+ gatewayEnv: {
+ anthropicBaseUrl: "http://127.0.0.1:1",
+ anthropicAuthToken: "tok",
+ openaiBaseUrl: "http://127.0.0.1:1/v1",
+ openaiApiKey: "tok",
+ },
+ });
+
+ const promise = agent.newSession({ cwd, mcpServers: [] });
+ const rejection = expect(promise).rejects.toThrow(
+ "Session model switch failed",
+ );
+ await vi.waitFor(() =>
+ expect(createdQueries[0]?.setModel).toHaveBeenCalledTimes(1),
+ );
+ const settings = String(createdQueryOptions[0]?.extraArgs?.settings);
+ expect(settings.startsWith(configDir)).toBe(true);
+ expect(existsSync(settings)).toBe(true);
+ rejectSetModel(new Error("set model boom"));
+ await rejection;
+
+ expect(existsSync(settings)).toBe(false);
+ },
+ );
});
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 8bca88cff063..7304e6f269e5 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -156,6 +156,8 @@ import {
buildSystemPrompt,
type GatewayEnv,
type ProcessSpawnedInfo,
+ removePinnedSettings,
+ settingsFlagIncludes,
toEffortFlagSettings,
toSdkEffort,
} from "./session/options";
@@ -492,6 +494,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
this.sideQuestionAbort?.abort();
await super.closeSession();
} finally {
+ if (this.session) removePinnedSettings(this.session.queryOptions);
this.enrichment?.dispose();
this.enrichment = undefined;
this.enrichedReadCache.clear();
@@ -1071,6 +1074,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
session.cancelController = undefined;
session.settingsManager.dispose();
+ removePinnedSettings(session.queryOptions);
session.input.end();
this.toolUseStreamCache.clear();
this.emittedToolCalls.clear();
@@ -2346,6 +2350,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
this.terminateQuery(newQuery, newAbortController);
}
session.queryClosed = true;
+ removePinnedSettings(session.queryOptions);
const message = error instanceof Error ? error.message : String(error);
try {
await this.client.extNotification(POSTHOG_NOTIFICATIONS.STATUS, {
@@ -2699,6 +2704,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
this.terminateQuery(newQuery, newAbortController);
}
prev.queryClosed = true;
+ removePinnedSettings(prev.queryOptions);
const message = error instanceof Error ? error.message : String(error);
throw new RequestError(-32603, message, { sessionId: this.sessionId });
}
@@ -3332,9 +3338,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
},
taskState,
traceparentHookNonce,
- traceparentHookInstalled:
- typeof options.extraArgs?.settings === "string" &&
- options.extraArgs.settings.includes(traceparentHookNonce),
+ traceparentHookInstalled: settingsFlagIncludes(
+ options,
+ traceparentHookNonce,
+ ),
// Custom properties
cwd,
@@ -3343,6 +3350,13 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
};
// A replaced session's consumer never reaches closeQueryStream.
this.emittedToolCalls.clear();
+ const replaced = this.session as Session | undefined;
+ if (
+ replaced &&
+ replaced.queryOptions.extraArgs?.settings !== options.extraArgs?.settings
+ ) {
+ removePinnedSettings(replaced.queryOptions);
+ }
this.session = session;
this.sessionId = sessionId;
@@ -3372,6 +3386,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
);
} catch (err) {
settingsManager.dispose();
+ removePinnedSettings(options);
this.terminateQuery(q, abortController);
if (
err instanceof Error &&
@@ -3478,6 +3493,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
});
} catch (err) {
settingsManager.dispose();
+ removePinnedSettings(options);
this.terminateQuery(q, abortController);
const initMs = Date.now() - initStartedAt;
startupLogger.error("Session initialization failed", {
@@ -3571,6 +3587,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
} catch (err) {
settingsManager.dispose();
+ removePinnedSettings(options);
this.terminateQuery(q, abortController);
session.queryClosed = true;
startupLogger.error("Session configuration failed", {
diff --git a/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts b/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
index fd2a0ffd97af..95860b267898 100644
--- a/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
@@ -6,6 +6,37 @@ export interface MachineClaudeAuth {
oauthToken?: string;
}
+/** Keys that pick the CLI's provider or its endpoint without ANTHROPIC_BASE_URL. */
+export const CLAUDE_PROVIDER_ENV_KEYS = [
+ "CLAUDE_CODE_USE_BEDROCK",
+ "CLAUDE_CODE_USE_VERTEX",
+ "CLAUDE_CODE_USE_FOUNDRY",
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
+ "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
+ "CLAUDE_CODE_USE_MANTLE",
+ "CLAUDE_CODE_USE_GATEWAY",
+ "ANTHROPIC_BEDROCK_BASE_URL",
+ "ANTHROPIC_BEDROCK_MANTLE_BASE_URL",
+ "ANTHROPIC_AWS_BASE_URL",
+ "ANTHROPIC_VERTEX_BASE_URL",
+ "ANTHROPIC_GOOGLE_CLOUD_BASE_URL",
+ "ANTHROPIC_FOUNDRY_BASE_URL",
+ "AWS_ENDPOINT_URL",
+ "AWS_ENDPOINT_URL_BEDROCK",
+ "AWS_ENDPOINT_URL_BEDROCK_RUNTIME",
+] as const;
+
+/** Keys that route the CLI's connections through another socket or proxy. */
+export const CLAUDE_TRANSPORT_ENV_KEYS = [
+ "ANTHROPIC_UNIX_SOCKET",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "all_proxy",
+] as const;
+
export const MACHINE_AUTH_STRIPPED_KEYS = [
"ANTHROPIC_BASE_URL",
"ANTHROPIC_AUTH_TOKEN",
@@ -13,12 +44,7 @@ export const MACHINE_AUTH_STRIPPED_KEYS = [
"ANTHROPIC_CUSTOM_HEADERS",
"OPENAI_BASE_URL",
"OPENAI_API_KEY",
- "CLAUDE_CODE_USE_BEDROCK",
- "CLAUDE_CODE_USE_VERTEX",
- "CLAUDE_CODE_USE_FOUNDRY",
- "CLAUDE_CODE_USE_ANTHROPIC_AWS",
- "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
- "CLAUDE_CODE_USE_MANTLE",
+ ...CLAUDE_PROVIDER_ENV_KEYS,
"CLAUDE_CODE_ENABLE_TELEMETRY",
"CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
"CLAUDE_CODE_PROPAGATE_TRACEPARENT",
@@ -32,14 +58,8 @@ export const MACHINE_AUTH_STRIPPED_KEYS = [
let resolvedMachineAuth: MachineClaudeAuth = {};
export const CLOUD_AUTH_STRIPPED_KEYS = [
- "ANTHROPIC_UNIX_SOCKET",
+ ...CLAUDE_TRANSPORT_ENV_KEYS,
"CLAUDE_CODE_EXECUTABLE",
- "HTTP_PROXY",
- "HTTPS_PROXY",
- "ALL_PROXY",
- "http_proxy",
- "https_proxy",
- "all_proxy",
"NODE_EXTRA_CA_CERTS",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
index 321ab2e07c87..91ab1988e782 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
@@ -8,6 +8,9 @@ import { SUBAGENT_REWRITES } from "../hooks";
import {
buildSessionOptions,
buildSystemPrompt,
+ PINNED_ROUTING_ENV_KEYS,
+ removePinnedSettings,
+ settingsFlagIncludes,
toEffortFlagSettings,
toSdkEffort,
} from "./options";
@@ -821,6 +824,25 @@ describe("buildSessionOptions", () => {
openaiApiKey: "tok",
};
+ let configDir: string;
+ let savedConfigDir: string | undefined;
+ beforeEach(() => {
+ savedConfigDir = process.env.CLAUDE_CONFIG_DIR;
+ configDir = fs.mkdtempSync(path.join(os.tmpdir(), "options-settings-"));
+ process.env.CLAUDE_CONFIG_DIR = configDir;
+ });
+ afterEach(() => {
+ if (savedConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
+ else process.env.CLAUDE_CONFIG_DIR = savedConfigDir;
+ fs.rmSync(configDir, { recursive: true, force: true });
+ });
+
+ function flagSettings(options: Options) {
+ const file = String(options.extraArgs?.settings);
+ expect(path.isAbsolute(file)).toBe(true);
+ return JSON.parse(fs.readFileSync(file, "utf-8"));
+ }
+
it("enables per-turn traceparent when routed through the gateway", () => {
const env = buildSessionOptions({ ...makeParams(), gatewayEnv }).env;
@@ -880,7 +902,7 @@ describe("buildSessionOptions", () => {
it("registers the traceparent hook and hook events for gateway sessions", () => {
const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
- const settings = JSON.parse(String(options.extraArgs?.settings));
+ const settings = flagSettings(options);
const hook = settings.hooks.UserPromptSubmit[0].hooks[0];
expect(hook.command).toContain("$TRACEPARENT");
expect(options.includeHookEvents).toBe(true);
@@ -900,7 +922,191 @@ describe("buildSessionOptions", () => {
userProvidedOptions: { extraArgs: { settings: '{"model":"x"}' } },
});
- expect(options.extraArgs?.settings).toBe('{"model":"x"}');
+ const settings = flagSettings(options);
+ expect(settings.model).toBe("x");
+ expect(settings.hooks).toBeUndefined();
+ expect(settings.env.ANTHROPIC_BASE_URL).toBe("https://gateway.example");
+ });
+
+ it("pins the gateway env in --settings so repo settings cannot redirect it", () => {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+
+ const settings = flagSettings(options);
+ expect(settings.env).toMatchObject({
+ ANTHROPIC_BASE_URL: "https://gateway.example",
+ ANTHROPIC_AUTH_TOKEN: "tok",
+ ANTHROPIC_API_KEY: "tok",
+ });
+ expect(settings.env.ANTHROPIC_CUSTOM_HEADERS).toBe(
+ options.env?.ANTHROPIC_CUSTOM_HEADERS,
+ );
+ });
+
+ it("pins every routing key so repo settings cannot reroute", () => {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+
+ const env = flagSettings(options).env;
+ for (const key of PINNED_ROUTING_ENV_KEYS) {
+ expect(env[key], key).toBe(options.env?.[key] ?? "");
+ }
+ expect(PINNED_ROUTING_ENV_KEYS).toEqual(
+ expect.arrayContaining([
+ "CLAUDE_CODE_USE_GATEWAY",
+ "ANTHROPIC_VERTEX_BASE_URL",
+ "https_proxy",
+ "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
+ "OTEL_LOG_RAW_API_BODIES",
+ ]),
+ );
+ });
+
+ it("pins the session's own telemetry endpoint over a repo's", () => {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+
+ const env = flagSettings(options).env;
+ expect(env.OTEL_EXPORTER_OTLP_ENDPOINT).toBe(
+ options.env?.OTEL_EXPORTER_OTLP_ENDPOINT,
+ );
+ expect(env.OTEL_EXPORTER_OTLP_ENDPOINT).not.toBe("");
+ expect(env.OTEL_LOG_TOOL_CONTENT).toBe("");
+ });
+
+ it("keeps routing values from the user's own settings", () => {
+ const params = makeParams();
+ vi.spyOn(params.settingsManager, "getUserEnv").mockReturnValue({
+ HTTPS_PROXY: "http://corp-proxy.example:3128",
+ ANTHROPIC_VERTEX_BASE_URL: "https://vertex.corp.example",
+ });
+ const options = buildSessionOptions({ ...params, gatewayEnv });
+
+ const env = flagSettings(options).env;
+ expect(env.HTTPS_PROXY).toBe("http://corp-proxy.example:3128");
+ expect(env.https_proxy).toBe("http://corp-proxy.example:3128");
+ expect(env.ANTHROPIC_VERTEX_BASE_URL).toBe("https://vertex.corp.example");
+ });
+
+ it("keeps an inherited routing value in the pin", () => {
+ const saved = process.env.HTTPS_PROXY;
+ process.env.HTTPS_PROXY = "http://corp-proxy.example:3128";
+ try {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+ expect(options.env?.HTTPS_PROXY).toBe("http://corp-proxy.example:3128");
+ const env = flagSettings(options).env;
+ expect(env.HTTPS_PROXY).toBe("http://corp-proxy.example:3128");
+ expect(env.https_proxy).toBe(
+ options.env?.https_proxy ?? "http://corp-proxy.example:3128",
+ );
+ } finally {
+ if (saved === undefined) delete process.env.HTTPS_PROXY;
+ else process.env.HTTPS_PROXY = saved;
+ }
+ });
+
+ it("merges the pins into a caller's SDK settings object", () => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv,
+ userProvidedOptions: {
+ settings: {
+ model: "x",
+ env: { FOO: "1", ANTHROPIC_BASE_URL: "https://elsewhere.example" },
+ },
+ },
+ });
+
+ expect(options.settings).toBeUndefined();
+ expect(flagSettings(options)).toMatchObject({
+ model: "x",
+ env: { FOO: "1", ANTHROPIC_BASE_URL: "https://gateway.example" },
+ });
+ });
+
+ it("removes the pinned settings file and nothing outside its directory", () => {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+ const file = String(options.extraArgs?.settings);
+ const outside = path.join(configDir, "keep.json");
+ fs.writeFileSync(outside, "{}");
+
+ removePinnedSettings(options);
+ removePinnedSettings({ extraArgs: { settings: outside } });
+
+ expect(fs.existsSync(file)).toBe(false);
+ expect(fs.existsSync(outside)).toBe(true);
+ });
+
+ it("keeps the pinned base URL out of argv in an owner-only file", () => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv: {
+ ...gatewayEnv,
+ anthropicBaseUrl: "http://127.0.0.1:5000/secret-token",
+ },
+ });
+
+ const file = String(options.extraArgs?.settings);
+ expect(file).not.toContain("secret-token");
+ expect(file.startsWith(configDir)).toBe(true);
+ if (process.platform !== "win32") {
+ expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ }
+ expect(flagSettings(options).env.ANTHROPIC_BASE_URL).toBe(
+ "http://127.0.0.1:5000/secret-token",
+ );
+ });
+
+ it("detects the traceparent hook in a pinned settings file", () => {
+ const pinned = buildSessionOptions({ ...makeParams(), gatewayEnv });
+ expect(settingsFlagIncludes(pinned, "0123456789abcdef")).toBe(true);
+
+ const skipped = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv,
+ userProvidedOptions: { extraArgs: { settings: '{"model":"x"}' } },
+ });
+ expect(settingsFlagIncludes(skipped, "0123456789abcdef")).toBe(false);
+ });
+
+ it("keeps a hostile session id inside the pinned settings directory", () => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv,
+ sessionId: "../../escape/x",
+ });
+
+ const file = String(options.extraArgs?.settings);
+ expect(path.dirname(file)).toBe(
+ path.join(configDir, "posthog-session-settings"),
+ );
+ removePinnedSettings(options);
+ expect(fs.existsSync(file)).toBe(false);
+ });
+
+ it("keeps project and local settings when the pin is installed", () => {
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+
+ expect(options.settingSources).toEqual(["user", "project", "local"]);
+ });
+
+ it.each([
+ ["a settings file path", { settings: "/tmp/caller-settings.json" }],
+ ["an unparseable settings flag", { extraArgs: { settings: "not json" } }],
+ ])("drops project and local settings when given %s", (_name, provided) => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ gatewayEnv,
+ userProvidedOptions: provided as Options,
+ });
+
+ expect(options.settingSources).toEqual(["user"]);
+ });
+
+ it("drops project and local settings when the pin cannot be written", () => {
+ fs.writeFileSync(path.join(configDir, "posthog-session-settings"), "");
+
+ const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
+
+ expect(options.settingSources).toEqual(["user"]);
+ expect(options.extraArgs?.settings).not.toMatch(/^\//);
});
it("skips the hook when the caller uses the SDK settings option", () => {
@@ -920,7 +1126,9 @@ describe("buildSessionOptions", () => {
Object.defineProperty(process, "platform", { value: "win32" });
try {
const options = buildSessionOptions({ ...makeParams(), gatewayEnv });
- expect(options.extraArgs?.settings).toBeUndefined();
+ const settings = flagSettings(options);
+ expect(settings.hooks).toBeUndefined();
+ expect(settings.env.ANTHROPIC_BASE_URL).toBe("https://gateway.example");
expect(options.includeHookEvents).toBe(false);
} finally {
if (platform) {
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
index 2a4aeaa07bbc..cfe06a6726c8 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -46,6 +46,8 @@ import {
} from "../hooks";
import {
applyMachineClaudeAuth,
+ CLAUDE_PROVIDER_ENV_KEYS,
+ CLAUDE_TRANSPORT_ENV_KEYS,
CLOUD_AUTH_STRIPPED_KEYS,
MACHINE_AUTH_STRIPPED_KEYS,
type MachineClaudeAuth,
@@ -56,6 +58,7 @@ import type { RunBudgetGuard } from "./budget-guard";
import { loadUserClaudeJsonMcpServers } from "./mcp-config";
import { createMemoryKillNoticeHook } from "./memory-kill-hook";
import { DEFAULT_MODEL, resolveFallbackModel } from "./models";
+import { isPinnedSettingsFile, pinnedSettingsDir } from "./pinned-settings";
import { createRtkRewriteHook } from "./rtk-hook";
import type { SettingsManager } from "./settings";
import { buildTraceparentHookSettingsJson } from "./traceparent-hook";
@@ -346,10 +349,8 @@ function applyGatewayAuth(
// are pinned rather than inherited — an ambient OTEL_TRACES_EXPORTER=none or
// unknown protocol registers no tracer and silently drops the traceparent;
// the endpoint stays overridable for a real collector.
- // Residual risk: a repo's .claude/settings.json `env` is applied over these
- // inside the CLI and can redirect the endpoint or turn on content capture
- // (OTEL_LOG_TOOL_CONTENT, …) — pre-existing settingSources exposure, not
- // closable from here; hardening tracked separately.
+ // A gateway session pins these in --settings so a repo's settings env
+ // cannot redirect the endpoint or turn on content capture.
env.CLAUDE_CODE_ENABLE_TELEMETRY = "1";
env.CLAUDE_CODE_ENHANCED_TELEMETRY_BETA = "1";
env.CLAUDE_CODE_PROPAGATE_TRACEPARENT = "1";
@@ -604,6 +605,128 @@ function buildSpawnWrapper(
};
}
+const PINNED_GATEWAY_ENV_KEYS = [
+ "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_AUTH_TOKEN",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_CUSTOM_HEADERS",
+] as const;
+
+const OTLP_SIGNALS = ["", "TRACES_", "LOGS_", "METRICS_"] as const;
+
+// Where telemetry goes and what it carries; the CLI builds the per-signal names.
+const TELEMETRY_ENV_KEYS = [
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
+ "OTEL_TRACES_EXPORTER",
+ "OTEL_LOGS_EXPORTER",
+ "OTEL_METRICS_EXPORTER",
+ ...OTLP_SIGNALS.flatMap((signal) =>
+ ["ENDPOINT", "HEADERS", "PROTOCOL"].map(
+ (field) => `OTEL_EXPORTER_OTLP_${signal}${field}`,
+ ),
+ ),
+ "OTEL_LOG_USER_PROMPTS",
+ "OTEL_LOG_ASSISTANT_RESPONSES",
+ "OTEL_LOG_TOOL_DETAILS",
+ "OTEL_LOG_TOOL_CONTENT",
+ "OTEL_LOG_RAW_API_BODIES",
+];
+
+// Keys that send content or credentials elsewhere without ANTHROPIC_BASE_URL.
+export const PINNED_ROUTING_ENV_KEYS: readonly string[] = [
+ ...CLAUDE_PROVIDER_ENV_KEYS,
+ ...CLAUDE_TRANSPORT_ENV_KEYS,
+ ...TELEMETRY_ENV_KEYS,
+];
+
+const PROXY_CASE_TWINS: Record<string, string> = {
+ HTTP_PROXY: "http_proxy",
+ HTTPS_PROXY: "https_proxy",
+ ALL_PROXY: "all_proxy",
+ http_proxy: "HTTP_PROXY",
+ https_proxy: "HTTPS_PROXY",
+ all_proxy: "ALL_PROXY",
+};
+
+// The pin outranks user settings too, so it keeps the user's own value.
+function routingPinValue(
+ key: string,
+ env: Record<string, string | undefined>,
+ userEnv: Record<string, string>,
+): string {
+ const own = (name: string) => env[name] ?? userEnv[name];
+ const twin = PROXY_CASE_TWINS[key];
+ return own(key) ?? (twin ? own(twin) : undefined) ?? "";
+}
+
+export function settingsFlagIncludes(options: Options, nonce: string): boolean {
+ const settings = options.extraArgs?.settings;
+ if (typeof settings !== "string") return false;
+ if (!isPinnedSettingsFile(settings)) return settings.includes(nonce);
+ try {
+ return fs.readFileSync(settings, "utf-8").includes(nonce);
+ } catch {
+ return false;
+ }
+}
+
+export function removePinnedSettings(options: Options): void {
+ const file = options.extraArgs?.settings;
+ if (!file || !isPinnedSettingsFile(file)) return;
+ try {
+ fs.rmSync(file, { force: true });
+ } catch {
+ // Best-effort: the next session with this id overwrites it.
+ }
+}
+
+/**
+ * Repeats the gateway env in `--settings`, which outranks a repo's project and
+ * local settings. Written to an owner-only file because argv is readable by
+ * any local user and the base URL carries the proxy's path token.
+ */
+function pinGatewayEnvSettings(
+ options: Options,
+ sessionId: string,
+ userEnv: Record<string, string>,
+): boolean {
+ const pins: Record<string, string> = {};
+ for (const key of PINNED_GATEWAY_ENV_KEYS) {
+ const value = options.env?.[key];
+ if (value !== undefined) pins[key] = value;
+ }
+ for (const key of PINNED_ROUTING_ENV_KEYS) {
+ pins[key] = routingPinValue(key, options.env ?? {}, userEnv);
+ }
+ if (typeof options.settings === "string") return false;
+ let base: Settings = options.settings ?? {};
+ const raw = options.extraArgs?.settings;
+ if (raw) {
+ try {
+ base = { ...(JSON.parse(raw) as Settings), ...base };
+ } catch {
+ return false;
+ }
+ }
+ const merged: Settings = { ...base, env: { ...base.env, ...pins } };
+ const dir = pinnedSettingsDir();
+ const file = path.join(
+ dir,
+ `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.json`,
+ );
+ try {
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(file, JSON.stringify(merged), { mode: 0o600 });
+ fs.chmodSync(file, 0o600);
+ } catch {
+ return false;
+ }
+ // The SDK drops extraArgs.settings when `settings` is set, so use one channel.
+ delete options.settings;
+ options.extraArgs = { ...options.extraArgs, settings: file };
+ return true;
+}
+
function ensureLocalSettings(cwd: string): void {
const claudeDir = path.join(cwd, ".claude");
const localSettingsPath = path.join(claudeDir, "settings.local.json");
@@ -735,6 +858,24 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
}),
};
+ if (
+ params.gatewayEnv?.anthropicBaseUrl &&
+ !params.machineAuth &&
+ !pinGatewayEnvSettings(
+ options,
+ params.sessionId,
+ params.settingsManager.getUserEnv(),
+ )
+ ) {
+ // Without the pin, repo settings could repoint the gateway env.
+ params.logger.warn(
+ "Gateway env is not pinned; skipping project and local settings",
+ );
+ options.settingSources = options.settingSources?.filter(
+ (source) => source !== "project" && source !== "local",
+ );
+ }
+
if (params.machineAuth?.oauthToken) {
delete options.pathToClaudeCodeExecutable;
delete options.executable;
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/pinned-settings.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/pinned-settings.test.ts
new file mode 100644
index 000000000000..c72a7ae354da
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/pinned-settings.test.ts
@@ -0,0 +1,39 @@
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { cleanupAllPinnedSettings, pinnedSettingsDir } from "./pinned-settings";
+
+describe("cleanupAllPinnedSettings", () => {
+ let configDir: string;
+ let saved: string | undefined;
+ beforeEach(() => {
+ saved = process.env.CLAUDE_CONFIG_DIR;
+ configDir = fs.mkdtempSync(path.join(os.tmpdir(), "pinned-settings-"));
+ process.env.CLAUDE_CONFIG_DIR = configDir;
+ });
+ afterEach(() => {
+ if (saved === undefined) delete process.env.CLAUDE_CONFIG_DIR;
+ else process.env.CLAUDE_CONFIG_DIR = saved;
+ fs.rmSync(configDir, { recursive: true, force: true });
+ });
+
+ it("removes leftover session files and nothing else", async () => {
+ const dir = pinnedSettingsDir();
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, "s-1.json"), "{}");
+ fs.writeFileSync(path.join(dir, "s-2.json"), "{}");
+ fs.writeFileSync(path.join(dir, "notes.txt"), "keep");
+ const outside = path.join(configDir, "settings.json");
+ fs.writeFileSync(outside, "{}");
+
+ await cleanupAllPinnedSettings();
+
+ expect(fs.readdirSync(dir)).toEqual(["notes.txt"]);
+ expect(fs.existsSync(outside)).toBe(true);
+ });
+
+ it("does nothing when the directory is missing", async () => {
+ await expect(cleanupAllPinnedSettings()).resolves.toBeUndefined();
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/pinned-settings.ts b/products/desktop/packages/agent/src/adapters/claude/session/pinned-settings.ts
new file mode 100644
index 000000000000..32833936250d
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/session/pinned-settings.ts
@@ -0,0 +1,32 @@
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+
+export function pinnedSettingsDir(): string {
+ return path.join(
+ process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"),
+ "posthog-session-settings",
+ );
+}
+
+export function isPinnedSettingsFile(value: string): boolean {
+ return path.dirname(value) === pinnedSettingsDir();
+}
+
+/** Removes every pinned settings file; call only once no session is running. */
+export async function cleanupAllPinnedSettings(): Promise<void> {
+ const dir = pinnedSettingsDir();
+ let entries: string[];
+ try {
+ entries = await fs.promises.readdir(dir);
+ } catch {
+ return;
+ }
+ await Promise.all(
+ entries
+ .filter((entry) => entry.endsWith(".json"))
+ .map((entry) =>
+ fs.promises.rm(path.join(dir, entry), { force: true }).catch(() => {}),
+ ),
+ );
+}
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/settings.ts b/products/desktop/packages/agent/src/adapters/claude/session/settings.ts
index 5c68bc432a43..1737022125c0 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/settings.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/settings.ts
@@ -419,6 +419,11 @@ export class SettingsManager {
return { decision: "ask" };
}
+ /** The `env` block of the user's own settings file, without repo layers. */
+ getUserEnv(): Record<string, string> {
+ return { ...(this.userSettings.env ?? {}) };
+ }
+
getSettings(): ClaudeCodeSettings {
return this.mergedSettings;
}
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts
index f9dc185599aa..fa54c380cc87 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts
@@ -51,6 +51,28 @@ describe("buildAppServerArgs", () => {
);
});
+ it("keeps the base URL out of argv when the codex home config names it", () => {
+ const args = buildAppServerArgs({
+ binaryPath: "/bundle/codex",
+ apiBaseUrl: "http://127.0.0.1:5000/secret-token/v1",
+ apiBaseUrlInConfig: true,
+ codexHome: "/tmp/codex-home",
+ });
+
+ expect(args).toContain('model_provider="posthog"');
+ expect(args.join(" ")).not.toContain("secret-token");
+ });
+
+ it("refuses a config-held base URL without a codex home to hold it", () => {
+ expect(() =>
+ buildAppServerArgs({
+ binaryPath: "/bundle/codex",
+ apiBaseUrl: "http://127.0.0.1:5000/secret-token/v1",
+ apiBaseUrlInConfig: true,
+ }),
+ ).toThrow(/CODEX_HOME/);
+ });
+
it("forwards http headers as a quoted TOML inline table on the posthog provider", () => {
const args = buildAppServerArgs({
binaryPath: "/bundle/codex",
@@ -190,6 +212,17 @@ describe("buildAppServerArgs", () => {
);
});
+ it("escapes control characters in a pinned value", () => {
+ const args = buildAppServerArgs(
+ { binaryPath: "/bundle/codex" },
+ { IS_SANDBOX: "1", BASH_ENV: '/tmp/a"\nb' },
+ );
+
+ expect(args).toContain(
+ 'shell_environment_policy.set.BASH_ENV="/tmp/a\\"\\nb"',
+ );
+ });
+
it("does not override BASH_ENV outside a managed sandbox", () => {
const args = buildAppServerArgs(
{ binaryPath: "/bundle/codex" },
@@ -262,6 +295,21 @@ describe("spawnCodexAppServerProcess", () => {
}
});
+ it("never logs the gateway base URL", () => {
+ const info = vi.fn();
+ mockSpawn.mockReturnValue(fakeChild() as never);
+ spawnCodexAppServerProcess({
+ binaryPath: BINARY_PATH,
+ apiBaseUrl: "http://127.0.0.1:5000/secret-token/v1",
+ logger: { ...silentLogger, info } as unknown as Logger,
+ });
+
+ expect(mockSpawn.mock.lastCall?.[1]).toContain(
+ 'model_providers.posthog.base_url="http://127.0.0.1:5000/secret-token/v1"',
+ );
+ expect(JSON.stringify(info.mock.calls)).not.toContain("secret-token");
+ });
+
it("separates machine login variables from gateway login variables", () => {
const saved = {
access: process.env.CODEX_ACCESS_TOKEN,
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
index c19924e09943..b0c8471a95f5 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
@@ -6,6 +6,7 @@ import {
applyContextWikiEnv,
type ContextWikiEnv,
} from "@posthog/harness/extensions/context-wiki";
+import { tomlBasicString } from "@posthog/shared";
import type { ProcessSpawnedCallback } from "../../types";
import { Logger } from "../../utils/logger";
@@ -23,6 +24,7 @@ export interface ChatgptAuthTokens {
export interface CodexOptions {
cwd?: string;
apiBaseUrl?: string;
+ apiBaseUrlInConfig?: boolean;
apiKey?: string;
model?: string;
reasoningEffort?: string;
@@ -66,6 +68,7 @@ export interface CodexAppServerProcessOptions {
binaryPath: string;
cwd?: string;
apiBaseUrl?: string;
+ apiBaseUrlInConfig?: boolean;
apiKey?: string;
codexHome?: string;
useMachineAuth?: boolean;
@@ -133,11 +136,6 @@ function getUnixProcessTreePids(rootPid: number): number[] | undefined {
return processTreePids;
}
-/** Serialize a string map as a TOML basic string (escapes `\` and `"`). */
-function tomlBasicString(value: string): string {
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
-}
-
/** Render a `Record<string, string>` as a TOML inline table. */
function tomlInlineTable(entries: Record<string, string>): string {
const pairs = Object.entries(entries).map(
@@ -146,6 +144,12 @@ function tomlInlineTable(entries: Record<string, string>): string {
return `{ ${pairs.join(", ")} }`;
}
+const BASE_URL_ARG = "model_providers.posthog.base_url=";
+
+function redactBaseUrlArg(arg: string): string {
+ return arg.startsWith(BASE_URL_ARG) ? `${BASE_URL_ARG}"[REDACTED]"` : arg;
+}
+
export function buildAppServerArgs(
options: CodexAppServerProcessOptions,
environment: NodeJS.ProcessEnv = process.env,
@@ -210,7 +214,17 @@ export function buildAppServerArgs(
if (options.apiBaseUrl) {
args.push("-c", `model_provider="posthog"`);
args.push("-c", `model_providers.posthog.name="PostHog Gateway"`);
- args.push("-c", `model_providers.posthog.base_url="${options.apiBaseUrl}"`);
+ // The loopback proxy URL carries a secret path token, and argv is readable
+ // by any local user, so a desktop session names it in CODEX_HOME instead.
+ if (options.apiBaseUrlInConfig && !options.codexHome) {
+ throw new Error("A config-held gateway base URL needs a CODEX_HOME.");
+ }
+ if (!options.apiBaseUrlInConfig) {
+ args.push(
+ "-c",
+ `model_providers.posthog.base_url=${tomlBasicString(options.apiBaseUrl)}`,
+ );
+ }
args.push("-c", `model_providers.posthog.wire_api="responses"`);
args.push(
"-c",
@@ -296,7 +310,7 @@ export function spawnCodexAppServerProcess(
logger.info("Spawning codex app-server process", {
command: options.binaryPath,
- args,
+ args: args.map(redactBaseUrlArg),
cwd: options.cwd,
});
diff --git a/products/desktop/packages/agent/src/agent.test.ts b/products/desktop/packages/agent/src/agent.test.ts
index 04ecb1d37e2a..66bace44ca1f 100644
--- a/products/desktop/packages/agent/src/agent.test.ts
+++ b/products/desktop/packages/agent/src/agent.test.ts
@@ -130,6 +130,79 @@ describe("Agent", () => {
);
});
+ it.each(["claude", "codex"] as const)(
+ "hands %s the proxy placeholder instead of the OAuth token",
+ async (adapter) => {
+ const getApiKey = vi.fn().mockResolvedValue("pha_oauth");
+ const agent = new Agent({
+ posthog: { apiUrl: "https://us.posthog.com", getApiKey, projectId: 1 },
+ skipLogPersistence: true,
+ });
+
+ await agent.run("__preview__", "run-1", {
+ adapter,
+ model: adapter === "codex" ? "gpt-5.5" : undefined,
+ gatewayUrl: "http://127.0.0.1:4000/tok",
+ gatewayApiKey: "posthog-code-auth-proxy",
+ codexBaseUrlInConfig: true,
+ });
+
+ const [[config]] = createAcpConnectionMock.mock.calls as unknown as [
+ [AcpConnectionConfig],
+ ];
+ expect(JSON.stringify(config)).not.toContain("pha_oauth");
+ if (adapter === "claude") {
+ expect(config.claudeGatewayEnv).toMatchObject({
+ anthropicAuthToken: "posthog-code-auth-proxy",
+ openaiApiKey: "posthog-code-auth-proxy",
+ });
+ } else {
+ expect(config.codexOptions).toMatchObject({
+ apiKey: "posthog-code-auth-proxy",
+ apiBaseUrlInConfig: true,
+ });
+ }
+ },
+ );
+
+ it("refuses a gateway URL override without its key", async () => {
+ const getApiKey = vi.fn().mockResolvedValue("pha_oauth");
+ const agent = new Agent({
+ posthog: { apiUrl: "https://us.posthog.com", getApiKey, projectId: 1 },
+ skipLogPersistence: true,
+ });
+
+ await expect(
+ agent.run("__preview__", "run-1", {
+ adapter: "claude",
+ gatewayUrl: "http://127.0.0.1:4000/tok",
+ }),
+ ).rejects.toThrow("gatewayUrl override requires gatewayApiKey");
+ expect(getApiKey).not.toHaveBeenCalled();
+ expect(createAcpConnectionMock).not.toHaveBeenCalled();
+ });
+
+ it("ignores a gateway key sent without a gateway URL", async () => {
+ const getApiKey = vi.fn().mockResolvedValue("pha_oauth");
+ const agent = new Agent({
+ posthog: { apiUrl: "https://us.posthog.com", getApiKey, projectId: 1 },
+ skipLogPersistence: true,
+ });
+
+ await agent.run("__preview__", "run-1", {
+ adapter: "claude",
+ gatewayApiKey: "stray-key",
+ });
+
+ const [[config]] = createAcpConnectionMock.mock.calls as unknown as [
+ [AcpConnectionConfig],
+ ];
+ expect(JSON.stringify(config)).not.toContain("stray-key");
+ expect(config.claudeGatewayEnv).toMatchObject({
+ anthropicAuthToken: "pha_oauth",
+ });
+ });
+
it("stops before starting Codex without authentication", async () => {
const agent = new Agent({ skipLogPersistence: true });
diff --git a/products/desktop/packages/agent/src/agent.ts b/products/desktop/packages/agent/src/agent.ts
index f348ce55196b..74f1e05824b1 100644
--- a/products/desktop/packages/agent/src/agent.ts
+++ b/products/desktop/packages/agent/src/agent.ts
@@ -65,7 +65,10 @@ export class Agent {
}
}
- private async _resolveGatewayConfig(overrideUrl?: string): Promise<{
+ private async _resolveGatewayConfig(
+ overrideUrl?: string,
+ overrideApiKey?: string,
+ ): Promise<{
gatewayUrl: string;
apiKey: string;
} | null> {
@@ -73,9 +76,13 @@ export class Agent {
return null;
}
+ // An override URL is the loopback proxy; the real token must never back it.
+ if (overrideUrl && !overrideApiKey) {
+ throw new Error("gatewayUrl override requires gatewayApiKey");
+ }
try {
const gatewayUrl = overrideUrl ?? this.posthogAPI.getLlmGatewayUrl();
- const apiKey = await this.posthogAPI.getApiKey();
+ const apiKey = overrideApiKey ?? (await this.posthogAPI.getApiKey());
return { gatewayUrl, apiKey };
} catch (error) {
this.logger.error("Failed to resolve LLM gateway config", error);
@@ -93,7 +100,10 @@ export class Agent {
options.claudeModelAccess === "own-subscription";
const gatewayConfig = claudeSubscription
? null
- : await this._resolveGatewayConfig(options.gatewayUrl);
+ : await this._resolveGatewayConfig(
+ options.gatewayUrl,
+ options.gatewayUrl ? options.gatewayApiKey : undefined,
+ );
this.taskRunId = taskRunId;
const needsAttribution = !claudeSubscription && gatewayConfig !== null;
@@ -142,6 +152,7 @@ export class Agent {
!codexSubscription && gatewayConfig
? {
apiBaseUrl: `${gatewayConfig.gatewayUrl}/v1`,
+ apiBaseUrlInConfig: options.codexBaseUrlInConfig,
apiKey: gatewayConfig.apiKey,
httpHeaders: {
...buildPosthogPropertyHeaderRecord(
diff --git a/products/desktop/packages/agent/src/types.ts b/products/desktop/packages/agent/src/types.ts
index 5b7b7e26ef86..471daeec702d 100644
--- a/products/desktop/packages/agent/src/types.ts
+++ b/products/desktop/packages/agent/src/types.ts
@@ -56,6 +56,8 @@ export interface TaskExecutionOptions {
adapter?: Adapter;
model?: string;
gatewayUrl?: string;
+ gatewayApiKey?: string;
+ codexBaseUrlInConfig?: boolean;
codexModelAccess?: ModelAccess;
claudeModelAccess?: ModelAccess;
codexBinaryPath?: string;
diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
index b3b279563a5f..b9871d51761a 100644
--- a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
+++ b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
@@ -1,9 +1,18 @@
import { describe, expect, it } from "vitest";
-import { redactSecrets, SecretEventRedactor } from "./redact-secrets";
-import { SECRET_HEADERS, TOKEN_RULES } from "./secret-rules";
+import {
+ redactSecrets,
+ SecretEventRedactor,
+ secretHeaderReplacer,
+} from "./redact-secrets";
+import { SECRET_HEADERS, TOKEN_RULES, type TokenRule } from "./secret-rules";
const CHUNK_KINDS = ["agent_message_chunk", "agent_thought_chunk"];
+// A shaped rule (the JWT) matches a complete string only in its full shape.
+function sampleToken(rule: TokenRule): string {
+ return rule.shape ? `${rule.prefix}aaaa.1111` : `${rule.prefix}aaaa1111`;
+}
+
const chunkCases: [string, string, string, string][] = TOKEN_RULES.flatMap(
(rule) =>
CHUNK_KINDS.map((sessionUpdate): [string, string, string, string] => [
@@ -39,6 +48,11 @@ const headerCases: [
{ headers: { [header]: "Bearer leaked-value", "x-id": "123" } },
{ headers: { [header]: "[REDACTED]", "x-id": "123" } },
],
+ [
+ `${header} array map entry`,
+ { headers: { [header]: ["Bearer leaked-value"], "x-id": "123" } },
+ { headers: { [header]: "[REDACTED]", "x-id": "123" } },
+ ],
]);
describe("redactSecrets", () => {
@@ -105,4 +119,176 @@ describe("redactSecrets", () => {
}),
).toEqual({ method: "session/new", params: { mcpServers: [expected] } });
});
+
+ it.each(headerCases)(
+ "masks a %s in JSON output",
+ (_shape, server, expected) => {
+ expect(JSON.parse(JSON.stringify(server, secretHeaderReplacer))).toEqual(
+ expected,
+ );
+ },
+ );
+
+ it.each([
+ ["an oauth access token", "Bearer pha_abcDEF123_-xyz", "Bearer [REDACTED]"],
+ ["an oauth refresh token", "refresh=phr_abc123", "refresh=[REDACTED]"],
+ [
+ "a gateway session token",
+ "token phe_abc123 used",
+ "token [REDACTED] used",
+ ],
+ [
+ "the auth proxy path token",
+ `base http://127.0.0.1:53211/${"a".repeat(43)}/v1/messages`,
+ "base http://127.0.0.1:53211/[REDACTED]/v1/messages",
+ ],
+ ])("redacts %s in a string", (_label, input, expected) => {
+ expect(redactSecrets(input)).toBe(expected);
+ });
+
+ it("keeps words that only contain a token prefix", () => {
+ expect(redactSecrets("alpha_blend graphe_x morphr_y")).toBe(
+ "alpha_blend graphe_x morphr_y",
+ );
+ expect(streamText(["see alpha_blend here"])).toBe("see alpha_blend here");
+ });
+
+ it("keeps a prefix-bearing word intact across every chunk split", () => {
+ const text = "see alpha_blend graphe_x here";
+ for (let cut = 1; cut < text.length; cut++) {
+ expect(streamText([text.slice(0, cut), text.slice(cut)])).toBe(text);
+ }
+ });
+
+ it.each(TOKEN_RULES.filter((rule) => rule.wordStart).map((r) => r.prefix))(
+ "redacts an escaped %s token split at every point",
+ (prefix) => {
+ for (const text of [
+ `x%3D${prefix}aaaa1111 end`,
+ `x\\n${prefix}aaaa1111 end`,
+ `x\u001b[1;32m${prefix}aaaa1111 end`,
+ `x\\u001b[32m${prefix}aaaa1111 end`,
+ `x\\u00e9${prefix}aaaa1111 end`,
+ `x\\xe9${prefix}aaaa1111 end`,
+ `x\u001b[${"1;".repeat(40)}32m${prefix}aaaa1111 end`,
+ `x\\u001b[${"1;".repeat(40)}32m${prefix}aaaa1111 end`,
+ ]) {
+ for (let cut = 1; cut < text.length; cut++) {
+ const out = streamText([text.slice(0, cut), text.slice(cut)]);
+ expect(out).not.toContain("aaaa1111");
+ }
+ }
+ },
+ );
+
+ it("keeps a long colour code's opener when a partial prefix is held", () => {
+ const colour = `\u001b[${"1;".repeat(40)}32m`;
+ const out = streamText(["x p", `${colour}ph`, "a_aaaa1111 end"]);
+ expect(out).not.toContain("aaaa1111");
+ });
+
+ it("keeps the word check across a held prefix released with new text", () => {
+ expect(streamText(["x p", "ing alp", "ha_blend end"])).toBe(
+ "x ping alpha_blend end",
+ );
+ });
+
+ it("does not carry one chunk kind's text into the next kind's word check", () => {
+ const token = `pha_${"a".repeat(43)}`;
+ expect(
+ streamText([
+ { kind: "agent_message_chunk", text: "see al" },
+ { kind: "agent_thought_chunk", text: `${token} end` },
+ ]),
+ ).toBe("see al[REDACTED] end");
+ });
+
+ it.each(TOKEN_RULES.map((rule) => [rule.prefix, sampleToken(rule)]))(
+ "redacts %s after an escaped newline or a percent code",
+ (_prefix, token) => {
+ expect(redactSecrets(`x\\n${token}`)).toBe("x\\n[REDACTED]");
+ expect(redactSecrets(`Bearer%20${token}`)).toBe("Bearer%20[REDACTED]");
+ },
+ );
+
+ it.each(
+ TOKEN_RULES.map(
+ (rule) => [rule.prefix, sampleToken(rule), !!rule.wordStart] as const,
+ ),
+ )(
+ "applies the word-start guard to %s only when flagged",
+ (_prefix, token, wordStart) => {
+ const input = `x${token}`;
+ expect(redactSecrets(input)).toBe(wordStart ? input : "x[REDACTED]");
+ },
+ );
+
+ it("redacts a loopback URL followed by a multi-megabyte token run", () => {
+ const input = `http://127.0.0.1:53211/${"a".repeat(6_000_000)}`;
+ expect(redactSecrets(input)).toBe("http://127.0.0.1:53211/[REDACTED]");
+ });
+
+ it("redacts the proxy path token in chunks held for a partial prefix", () => {
+ const url = `http://127.0.0.1:53211/${"a".repeat(43)}/v1`;
+ const out = streamText(["first gh", ` ${url} gh`, " end"]);
+ expect(out).not.toContain("a".repeat(43));
+ expect(out).toContain("127.0.0.1:53211/[REDACTED]");
+ });
+
+ it.each(["127.0.0.1", "localhost", "[::1]"])(
+ "redacts a %s proxy URL split at every boundary",
+ (host) => {
+ const token = `${"a".repeat(40)}Z9`;
+ const text = `see http://${host}:53211/${token}/v1 now`;
+ for (let cut = 1; cut < text.length; cut++) {
+ const out = streamText([text.slice(0, cut), text.slice(cut)]);
+ expect(out).toBe(`see http://${host}:53211/[REDACTED]/v1 now`);
+ }
+ },
+ );
+
+ it("redacts a proxy URL spread over many small chunks", () => {
+ const text = `x http://127.0.0.1:53211/${"b".repeat(43)}/v1`;
+ const parts = text.match(/.{1,3}/g) ?? [];
+ expect(streamText(parts)).toBe("x http://127.0.0.1:53211/[REDACTED]/v1");
+ });
+
+ it("keeps short loopback paths such as the MCP proxy ids", () => {
+ expect(redactSecrets("http://127.0.0.1:4000/posthog")).toBe(
+ "http://127.0.0.1:4000/posthog",
+ );
+ });
});
+
+type StreamPart = string | { kind: string; text: string };
+
+function streamText(parts: StreamPart[]): string {
+ const redactor = new SecretEventRedactor();
+ const events = parts.flatMap((part) =>
+ redactor.redact({
+ type: "notification",
+ notification: {
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate:
+ typeof part === "string" ? "agent_message_chunk" : part.kind,
+ content: {
+ type: "text",
+ text: typeof part === "string" ? part : part.text,
+ },
+ },
+ },
+ },
+ }),
+ );
+ events.push(...redactor.redact({ type: "done" }));
+ return events
+ .map((event) => {
+ const notification = event.notification as
+ | { params: { update: { content: { text: string } } } }
+ | undefined;
+ return notification?.params.update.content.text ?? "";
+ })
+ .join("");
+}
diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.ts b/products/desktop/packages/agent/src/utils/redact-secrets.ts
index e2b3c7b55b20..5f52609d3d1d 100644
--- a/products/desktop/packages/agent/src/utils/redact-secrets.ts
+++ b/products/desktop/packages/agent/src/utils/redact-secrets.ts
@@ -1,4 +1,9 @@
-import { SECRET_HEADERS, TOKEN_RULES, type TokenRule } from "./secret-rules";
+import {
+ LOOPBACK_PROXY_TOKEN,
+ SECRET_HEADERS,
+ TOKEN_RULES,
+ type TokenRule,
+} from "./secret-rules";
const REDACTED = "[REDACTED]";
@@ -11,8 +16,16 @@ function escapeLiteral(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+// Opens an ANSI colour code such as ESC[32m, raw or JSON-escaped.
+const ANSI_OPEN = String.raw`(?:\x1b|\\u001[bB]|\\x1[bB]|\\033|\\e)\[`;
+
+// Not after a letter or digit, unless it ends an escape: "\n", "%20", "\u00e9",
+// "\xe9", or an ANSI colour code.
+const WORD_START = String.raw`(?<!(?<!\\|%[0-9A-Fa-f]?|\\[ux][0-9A-Fa-f]{0,3}|${ANSI_OPEN}[0-9;]*)[A-Za-z0-9])`;
+
function tokenSource(rule: TokenRule, repeat: "+" | "*"): string {
- return `${escapeLiteral(rule.prefix)}${rule.body.source}${repeat}`;
+ const start = rule.wordStart ? WORD_START : "";
+ return `${start}${escapeLiteral(rule.prefix)}${rule.body.source}${repeat}`;
}
const RULES: CompiledRule[] = TOKEN_RULES.map((rule) => ({
@@ -29,9 +42,11 @@ function trailingDots(match: string): string {
}
const TOKEN = new RegExp(
- TOKEN_RULES.map((rule) => rule.shape?.source ?? tokenSource(rule, "+")).join(
- "|",
- ),
+ TOKEN_RULES.map((rule) =>
+ rule.shape
+ ? `${rule.wordStart ? WORD_START : ""}${rule.shape.source}`
+ : tokenSource(rule, "+"),
+ ).join("|"),
"g",
);
@@ -45,6 +60,37 @@ const PARTIAL_PREFIXES = [
),
].sort((left, right) => right.length - left.length);
+const LOOPBACK_TAIL: CompiledRule = {
+ head: LOOPBACK_PROXY_TOKEN,
+ tail: /^[A-Za-z0-9_-]*/,
+};
+const LOOPBACK_HOSTS = ["127.0.0.1", "localhost", "[::1]"];
+const LOOPBACK_AFTER_HOST = /^:(?:\d{0,5}|\d{1,5}\/[A-Za-z0-9_-]{0,31})$/;
+const LOOPBACK_HOLD_MAX = 2 + 9 + 6 + 1 + 31;
+
+/** Whether `text` could still grow into a loopback URL with a full path token. */
+function isLoopbackPrefix(text: string): boolean {
+ if (text.length <= 2) return "//".startsWith(text);
+ if (!text.startsWith("//")) return false;
+ const rest = text.slice(2);
+ return LOOPBACK_HOSTS.some(
+ (host) =>
+ host.startsWith(rest) ||
+ (rest.startsWith(host) &&
+ LOOPBACK_AFTER_HOST.test(rest.slice(host.length))),
+ );
+}
+
+function loopbackPrefixLength(text: string): number {
+ const from = Math.max(0, text.length - LOOPBACK_HOLD_MAX);
+ for (let start = from; start < text.length; start++) {
+ if (text[start] === "/" && isLoopbackPrefix(text.slice(start))) {
+ return text.length - start;
+ }
+ }
+ return 0;
+}
+
const SECRET_HEADER_NAMES = new Set(SECRET_HEADERS);
function isSecretHeader(name: unknown): boolean {
@@ -64,8 +110,11 @@ export function redactSecrets(value: string): string;
export function redactSecrets(value: string | undefined): string | undefined;
export function redactSecrets(value: unknown): unknown;
export function redactSecrets(value: unknown): unknown {
- if (typeof value === "string")
- return value.replace(TOKEN, (match) => REDACTED + trailingDots(match));
+ if (typeof value === "string") {
+ return value
+ .replace(TOKEN, (match) => REDACTED + trailingDots(match))
+ .replace(LOOPBACK_PROXY_TOKEN, `$1${REDACTED}`);
+ }
if (Array.isArray(value)) return value.map(redactSecrets);
if (value instanceof Error)
return {
@@ -84,13 +133,29 @@ export function redactSecrets(value: unknown): unknown {
return Object.fromEntries(
Object.entries(record).map(([key, nested]) => [
key,
- isSecretHeader(key) && typeof nested === "string"
- ? REDACTED
- : redactSecrets(nested),
+ isSecretHeader(key) && nested != null ? REDACTED : redactSecrets(nested),
]),
);
}
+/**
+ * `JSON.stringify` replacer that masks secret headers without a recursive
+ * walk, so cycles fail fast. Run `redactSecrets` over the output for tokens.
+ */
+export function secretHeaderReplacer(key: string, value: unknown): unknown {
+ if (isSecretHeader(key) && value != null) return REDACTED;
+ if (value instanceof Error) {
+ return { name: value.name, message: value.message, stack: value.stack };
+ }
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
+ const record = value as Record<string, unknown>;
+ if (isSecretHeader(record.name) && "value" in record) {
+ return { ...record, value: REDACTED };
+ }
+ }
+ return value;
+}
+
type TextEvent = Record<string, unknown> & {
notification: {
method: "session/update";
@@ -133,11 +198,26 @@ function withText(event: TextEvent, text: string): TextEvent {
};
}
+// Emitted text kept for WORD_START's lookbehind: the character before a prefix
+// plus the escape or colour code ahead of it.
+const CONTEXT_LENGTH = 32;
+const OPEN_ANSI_TAIL = new RegExp(`(${ANSI_OPEN})([0-9;]*[A-Za-z0-9]?)$`);
+
+// A colour code longer than the window keeps its opener, so the lookbehind
+// still reads it as an escape.
+function nextContext(text: string): string {
+ const tail = text.slice(-CONTEXT_LENGTH);
+ const open = OPEN_ANSI_TAIL.exec(text);
+ if (!open || open[0].length <= tail.length) return tail;
+ return open[1] + open[2].slice(-CONTEXT_LENGTH);
+}
+
export class SecretEventRedactor {
private pending: TextEvent | null = null;
private active: CompiledRule | null = null;
private chunkKind: string | null = null;
private heldDots = 0;
+ private context = "";
redact(event: Record<string, unknown>): Record<string, unknown>[] {
const events: Record<string, unknown>[] = [];
@@ -147,6 +227,7 @@ export class SecretEventRedactor {
if (this.pending) events.push(this.pending);
this.pending = null;
this.active = null;
+ this.context = "";
}
this.chunkKind = kind;
if (!chunk) {
@@ -170,25 +251,44 @@ export class SecretEventRedactor {
if (remainder === dots) heldDots = dots.length;
else if (remainder.length > 0) this.active = null;
}
+ const context = this.context;
for (const rule of RULES) {
- text = text.replace(
- rule.head,
- (match, offset: number, source: string) => {
+ text = (context + text)
+ .replace(rule.head, (match, offset: number, source: string) => {
+ if (offset < context.length) return match;
const dots = trailingDots(match);
if (offset + match.length === source.length) {
this.active = rule;
heldDots = dots.length;
}
return REDACTED + dots;
- },
- );
+ })
+ .slice(context.length);
}
- const redacted = redactSecrets(withText(event, text)) as TextEvent;
- const held = this.active ? heldDots : partialPrefixLength(text);
+ text = text.replace(
+ LOOPBACK_PROXY_TOKEN,
+ (match, host: string, offset: number, source: string) => {
+ if (offset + match.length === source.length) {
+ this.active = LOOPBACK_TAIL;
+ heldDots = 0;
+ }
+ return host + REDACTED;
+ },
+ );
+ // The rule loop has already redacted the text; this covers the other fields.
+ const redacted = withText(
+ redactSecrets(withText(event, "")) as TextEvent,
+ text,
+ );
+ const held = this.active
+ ? heldDots
+ : Math.max(partialPrefixLength(text), loopbackPrefixLength(text));
this.heldDots = this.active ? heldDots : 0;
if (held > 0) {
if (previous) {
- events.push(withText(previous, text.slice(0, -held)));
+ const emitted = text.slice(0, -held);
+ events.push(withText(previous, emitted));
+ this.context = nextContext(context + emitted);
this.pending = withText(redacted, text.slice(-held));
} else {
this.pending = redacted;
@@ -196,6 +296,9 @@ export class SecretEventRedactor {
return events;
}
events.push(redacted);
+ this.context = nextContext(
+ context + redacted.notification.params.update.content.text,
+ );
return events;
}
}
diff --git a/products/desktop/packages/agent/src/utils/secret-rules.ts b/products/desktop/packages/agent/src/utils/secret-rules.ts
index a87063ee667f..c30cd81dfc1f 100644
--- a/products/desktop/packages/agent/src/utils/secret-rules.ts
+++ b/products/desktop/packages/agent/src/utils/secret-rules.ts
@@ -5,6 +5,8 @@ export interface TokenRule {
// Replaces prefix and body for a complete string. Streamed chunks keep the prefix,
// because a chunk can end before the part of the token that the shape requires.
shape?: RegExp;
+ /** The prefix also ends ordinary words ("alpha_"), so it must start one. */
+ wordStart?: boolean;
}
const URL_SAFE_BODY = /[A-Za-z0-9_-]/;
@@ -49,8 +51,29 @@ export const TOKEN_RULES: TokenRule[] = [
// does not, and a JWT always has one after its header.
shape: /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-][A-Za-z0-9_.-]*/,
},
+ {
+ label: "posthog oauth access token",
+ prefix: "pha_",
+ body: URL_SAFE_BODY,
+ wordStart: true,
+ },
+ {
+ label: "posthog oauth refresh token",
+ prefix: "phr_",
+ body: URL_SAFE_BODY,
+ wordStart: true,
+ },
+ {
+ label: "posthog ai gateway session token",
+ prefix: "phe_",
+ body: URL_SAFE_BODY,
+ wordStart: true,
+ },
];
+export const LOOPBACK_PROXY_TOKEN =
+ /(\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+\/)[A-Za-z0-9_-]{32}[A-Za-z0-9_-]*/g;
+
export const SECRET_HEADERS: string[] = [
"authorization",
"proxy-authorization",
diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.ts
index 1056c9ff947b..68db3de48bb8 100644
--- a/products/desktop/packages/agent/tsup.config.ts
+++ b/products/desktop/packages/agent/tsup.config.ts
@@ -182,6 +182,7 @@ export default defineConfig([
"src/pi/conversation/translatePiConversation.ts",
"src/resume.ts",
"src/types.ts",
+ "src/utils/redact-secrets.ts",
"src/adapters/claude/questions/utils.ts",
"src/adapters/claude/permissions/permission-options.ts",
"src/adapters/claude/tools.ts",
@@ -194,6 +195,7 @@ export default defineConfig([
"src/adapters/codex-app-server/subscription-login.ts",
"src/adapters/claude/subscription-login.ts",
"src/adapters/claude/machine-auth.ts",
+ "src/adapters/claude/session/pinned-settings.ts",
"src/adapters/claude/mcp/tool-metadata.ts",
"src/adapters/reasoning-effort.ts",
"src/execution-mode.ts",
diff --git a/products/desktop/packages/agent/vitest.config.ts b/products/desktop/packages/agent/vitest.config.ts
index d4f20521acfc..13707cc41927 100644
--- a/products/desktop/packages/agent/vitest.config.ts
+++ b/products/desktop/packages/agent/vitest.config.ts
@@ -1,3 +1,4 @@
+import { tmpdir } from "node:os";
import { resolve } from "node:path";
import { defineConfig } from "vitest/config";
import { trunkTestOptions } from "../../vitest.config.base";
@@ -16,6 +17,8 @@ export default defineConfig({
exclude: ["**/node_modules/**", "**/dist/**"],
isolate: true,
fileParallelism: false,
+ // Session options write a settings file under the Claude config dir.
+ env: { CLAUDE_CONFIG_DIR: resolve(tmpdir(), "posthog-agent-test-claude") },
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.ts
index 487eee19a8a4..93f5ba465cbd 100644
--- a/products/desktop/packages/core/src/auth/auth.test.ts
+++ b/products/desktop/packages/core/src/auth/auth.test.ts
@@ -220,7 +220,7 @@ describe("AuthService", () => {
);
};
- function createService(): AuthService {
+ function createService(extraFetchOrigins: string[] = []): AuthService {
return new AuthService(
preferencePort,
sessionPort,
@@ -230,6 +230,7 @@ describe("AuthService", () => {
mockPowerManager as unknown as IPowerManager,
mockLogger,
null,
+ extraFetchOrigins,
);
}
@@ -452,6 +453,77 @@ describe("AuthService", () => {
},
);
+ it("sends the bearer to an extra origin the host binds", async () => {
+ service.shutdown();
+ service = createService(["http://127.0.0.1:8787"]);
+ service.init();
+ seedStoredSession({ selectedProjectId: 42 });
+ stubAuthFetch();
+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());
+ await service.initialize();
+ vi.mocked(fetch).mockResolvedValueOnce(new Response("ok"));
+
+ const response = await service.authenticatedFetch(
+ fetch,
+ "http://127.0.0.1:8787/mcp",
+ );
+
+ expect(response.status).toBe(200);
+ });
+
+ it("refuses to attach the bearer to an origin outside the allowlist", async () => {
+ seedStoredSession({ selectedProjectId: 42 });
+ stubAuthFetch();
+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());
+ await service.initialize();
+ vi.mocked(fetch).mockClear();
+
+ await expect(
+ service.authenticatedFetch(fetch, "https://evil.example/steal?q=1"),
+ ).rejects.toThrow(
+ /^Refusing to send PostHog credentials to https:\/\/evil\.example$/,
+ );
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("checks the origin of a Request input", async () => {
+ seedStoredSession({ selectedProjectId: 42 });
+ stubAuthFetch();
+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());
+ await service.initialize();
+ vi.mocked(fetch).mockClear();
+
+ await expect(
+ service.authenticatedFetch(
+ fetch,
+ new Request("https://evil.example/steal"),
+ ),
+ ).rejects.toThrow(/^Refusing to send PostHog credentials/);
+ expect(fetch).not.toHaveBeenCalled();
+
+ vi.mocked(fetch).mockResolvedValueOnce(new Response("ok"));
+ const response = await service.authenticatedFetch(
+ fetch,
+ new Request("https://mcp.posthog.com/mcp"),
+ );
+ expect(response.status).toBe(200);
+ });
+
+ it.each([
+ "https://gateway.us.posthog.com/posthog_code/v1/messages",
+ "https://mcp.posthog.com/mcp",
+ ])("still sends the bearer to %s", async (url) => {
+ seedStoredSession({ selectedProjectId: 42 });
+ stubAuthFetch();
+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());
+ await service.initialize();
+ vi.mocked(fetch).mockResolvedValueOnce(new Response("ok"));
+
+ const response = await service.authenticatedFetch(fetch, url);
+
+ expect(response.status).toBe(200);
+ });
+
it("requires scope reauthentication when the stored scope version is stale", async () => {
seedStoredSession({
refreshToken: "refresh-token",
diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.ts
index d12af94e5793..d996a3d3efc9 100644
--- a/products/desktop/packages/core/src/auth/auth.ts
+++ b/products/desktop/packages/core/src/auth/auth.ts
@@ -8,16 +8,24 @@ import {
type BackoffOptions,
type CloudRegion,
getCloudUrlFromRegion,
+ isCredentialOriginAllowed,
NotAuthenticatedError,
OAUTH_SCOPE_VERSION,
sleepWithBackoff,
TypedEventEmitter,
withTimeout,
} from "@posthog/shared";
-import { inject, injectable, postConstruct, preDestroy } from "inversify";
+import {
+ inject,
+ injectable,
+ optional,
+ postConstruct,
+ preDestroy,
+} from "inversify";
import { z } from "zod";
import {
AUTH_CONNECTIVITY,
+ AUTH_FETCH_EXTRA_ORIGINS,
AUTH_OAUTH_FLOW_SERVICE,
AUTH_PREFERENCE_STORE,
AUTH_SESSION_STORE,
@@ -130,6 +138,9 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
private readonly logger: RootLogger,
@inject(AUTH_TOKEN_OVERRIDE)
private readonly tokenOverride: string | null,
+ @inject(AUTH_FETCH_EXTRA_ORIGINS)
+ @optional()
+ private readonly extraFetchOrigins: readonly string[] | undefined = [],
) {
super();
}
@@ -265,6 +276,18 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
init: RequestInit = {},
): Promise<Response> {
const initialAuth = await this.getValidAccessToken();
+ const url = typeof input === "string" ? input : input.url;
+ if (
+ !isCredentialOriginAllowed(
+ url,
+ initialAuth.apiHost,
+ this.extraFetchOrigins ?? [],
+ )
+ ) {
+ throw new Error(
+ `Refusing to send PostHog credentials to ${safeOrigin(url)}`,
+ );
+ }
let response = await this.executeAuthenticatedFetch(
fetchImpl,
input,
@@ -1681,3 +1704,11 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
this.emit(AuthServiceEvent.StateChanged, this.getState());
}
}
+
+function safeOrigin(url: string): string {
+ try {
+ return new URL(url).origin;
+ } catch {
+ return "an invalid URL";
+ }
+}
diff --git a/products/desktop/packages/core/src/auth/identifiers.ts b/products/desktop/packages/core/src/auth/identifiers.ts
index 40f46e736793..540305f6cb2e 100644
--- a/products/desktop/packages/core/src/auth/identifiers.ts
+++ b/products/desktop/packages/core/src/auth/identifiers.ts
@@ -122,3 +122,7 @@ export const AUTH_CONNECTIVITY = Symbol.for("posthog.core.auth.connectivity");
export const AUTH_TOKEN_OVERRIDE = Symbol.for(
"posthog.core.auth.tokenOverride",
);
+
+export const AUTH_FETCH_EXTRA_ORIGINS = Symbol.for(
+ "posthog.core.auth.fetchExtraOrigins",
+);
diff --git a/products/desktop/packages/shared/src/custom-cloud.test.ts b/products/desktop/packages/shared/src/custom-cloud.test.ts
index 058b6123d98c..ab6dcac02c0c 100644
--- a/products/desktop/packages/shared/src/custom-cloud.test.ts
+++ b/products/desktop/packages/shared/src/custom-cloud.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
configureCustomCloud,
getCustomCloud,
+ isCredentialOriginAllowed,
isCustomCloudHost,
normalizeCustomCloud,
} from "./custom-cloud";
@@ -68,6 +69,15 @@ describe("custom cloud", () => {
).toBeNull();
});
+ it("accepts an http IPv6 loopback URL", () => {
+ expect(
+ normalizeCustomCloud({
+ url: "http://[::1]:8000",
+ oauthClientId: "client-id",
+ })?.url,
+ ).toBe("http://[::1]:8000");
+ });
+
it("refuses a built-in host written with a trailing dot", () => {
expect(
normalizeCustomCloud({
@@ -133,3 +143,109 @@ describe("custom cloud", () => {
});
});
});
+
+describe("isCredentialOriginAllowed", () => {
+ afterEach(() => configureCustomCloud(null));
+
+ it.each([
+ ["https://us.posthog.com/api/users/@me/", "https://us.posthog.com"],
+ [
+ "https://gateway.us.posthog.com/posthog_code/v1/messages",
+ "https://us.posthog.com",
+ ],
+ ["https://mcp.posthog.com/mcp", "https://eu.posthog.com"],
+ ["https://gateway.dev.posthog.dev/x", "https://app.dev.posthog.dev"],
+ ["http://localhost:8787/mcp", "http://localhost:8010"],
+ ["http://[::1]:8787/mcp", "http://localhost:8010"],
+ ["http://localhost:8787/mcp", "http://[::1]:8010"],
+ ])("allows %s for %s", (url, apiHost) => {
+ expect(isCredentialOriginAllowed(url, apiHost)).toBe(true);
+ });
+
+ it.each([
+ ["https://evil.example/steal", "https://us.posthog.com"],
+ ["http://us.posthog.com/api", "https://us.posthog.com"],
+ ["http://localhost:8787/mcp", "https://us.posthog.com"],
+ ["https://posthog.com.evil.example/", "https://us.posthog.com"],
+ ["https://evilposthog.com/", "https://us.posthog.com"],
+ ["https://1.2.3.4/", "https://us.posthog.com"],
+ ["https://evilexample.com/", "https://posthog.example.com"],
+ ["https://other.example/", "https://posthog.example.com"],
+ ["https://1.2.3.4/", "https://10.0.0.5"],
+ ["https://evil/", "https://posthog"],
+ ["https://attacker.github.io/", "https://customer.github.io"],
+ ["https://mcp.example.com/mcp", "https://posthog.example.com"],
+ ["https://llm.acme.co.uk/", "https://posthog.acme.co.uk"],
+ ["https://us.posthog.com/api", "https://posthog.example.com"],
+ ["https://mcp.posthog.com/mcp", "https://app.dev.posthog.dev"],
+ ["https://gateway.dev.posthog.dev/x", "https://us.posthog.com"],
+ ["http://[::1]:8787/mcp", "https://us.posthog.com"],
+ ["https://mcp.posthog.com:8443/mcp", "https://us.posthog.com"],
+ ["http://posthog.internal:8000/api/x", "http://posthog.internal:8000"],
+ ])("refuses %s for %s", (url, apiHost) => {
+ expect(isCredentialOriginAllowed(url, apiHost)).toBe(false);
+ });
+
+ it("allows a root-relative path and refuses a protocol-relative one", () => {
+ expect(
+ isCredentialOriginAllowed("/api/users/@me/", "https://us.posthog.com"),
+ ).toBe(true);
+ expect(
+ isCredentialOriginAllowed("//evil.example/x", "https://us.posthog.com"),
+ ).toBe(false);
+ });
+
+ it.each(["/\\evil.example/x", "/\\/evil.example/x", "/\t/evil.example/x"])(
+ "refuses %j, which the URL parser reads as protocol-relative",
+ (url) => {
+ expect(isCredentialOriginAllowed(url, "https://us.posthog.com")).toBe(
+ false,
+ );
+ },
+ );
+
+ it("allows explicit extra origins and the custom cloud gateway", () => {
+ expect(
+ isCredentialOriginAllowed(
+ "http://127.0.0.1:9000/mcp",
+ "https://us.posthog.com",
+ ["http://127.0.0.1:9000"],
+ ),
+ ).toBe(true);
+ configureCustomCloud({
+ url: "https://posthog.acme.internal",
+ oauthClientId: "id",
+ gatewayUrl: "https://llm.other-domain.io",
+ });
+ expect(
+ isCredentialOriginAllowed(
+ "https://llm.other-domain.io/posthog_code/v1/messages",
+ "https://posthog.acme.internal",
+ ),
+ ).toBe(true);
+ });
+
+ it("refuses a plain-http extra origin off loopback", () => {
+ expect(
+ isCredentialOriginAllowed(
+ "http://mcp.example.com/mcp",
+ "https://us.posthog.com",
+ ["http://mcp.example.com"],
+ ),
+ ).toBe(false);
+ });
+
+ it("refuses the custom cloud gateway while signed in to another host", () => {
+ configureCustomCloud({
+ url: "https://posthog.acme.internal",
+ oauthClientId: "id",
+ gatewayUrl: "https://llm.other-domain.io",
+ });
+ expect(
+ isCredentialOriginAllowed(
+ "https://llm.other-domain.io/posthog_code/v1/messages",
+ "https://us.posthog.com",
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/products/desktop/packages/shared/src/custom-cloud.ts b/products/desktop/packages/shared/src/custom-cloud.ts
index 13c987189fd1..d37940e8c0d6 100644
--- a/products/desktop/packages/shared/src/custom-cloud.ts
+++ b/products/desktop/packages/shared/src/custom-cloud.ts
@@ -45,8 +45,12 @@ function httpUrl(value: string | undefined): string | undefined {
return `${parsed.protocol}//${canonicalHost(parsed)}`;
}
+// URL.hostname keeps the brackets on an IPv6 literal.
function isLoopbackHost(hostname: string): boolean {
- const host = hostname.replace(/\.+$/, "").toLowerCase();
+ const host = hostname
+ .replace(/\.+$/, "")
+ .replace(/^\[(.*)\]$/, "$1")
+ .toLowerCase();
return host === "localhost" || host === "127.0.0.1" || host === "::1";
}
@@ -105,3 +109,64 @@ export function configureCustomCloud(target: CustomCloud | null): void {
export function getCustomCloud(): CustomCloud | null {
return configured ?? fromEnv();
}
+
+const POSTHOG_DOMAINS = ["posthog.com", "posthog.dev"];
+
+function postHogDomain(host: string): string | undefined {
+ return POSTHOG_DOMAINS.find(
+ (domain) => host === domain || host.endsWith(`.${domain}`),
+ );
+}
+
+function safeUrl(value: string, base?: string): URL | null {
+ try {
+ return new URL(value, base);
+ } catch {
+ return null;
+ }
+}
+
+export function isCredentialOriginAllowed(
+ url: string,
+ apiHost: string,
+ extraOrigins: readonly string[] = [],
+): boolean {
+ // A root-relative path stays on the page's own origin (browser hosts).
+ // Resolved with the fetch's parser, which reads "/\host" as "//host".
+ if (url.startsWith("/")) {
+ const probe = "https://relative.invalid";
+ return safeUrl(url, probe)?.origin === probe;
+ }
+ const target = safeUrl(url);
+ const api = safeUrl(apiHost);
+ if (!target || !api) return false;
+ const targetHost = target.hostname.replace(/\.+$/, "").toLowerCase();
+ const apiHostname = api.hostname.replace(/\.+$/, "").toLowerCase();
+ // The bearer never travels in cleartext, whichever branch admits the origin.
+ if (
+ target.protocol !== "https:" &&
+ !(target.protocol === "http:" && isLoopbackHost(targetHost))
+ ) {
+ return false;
+ }
+ if (target.origin === api.origin) return true;
+ if (extraOrigins.some((extra) => safeUrl(extra)?.origin === target.origin)) {
+ return true;
+ }
+ const customGateway = isCustomCloudHost(apiHost)
+ ? getCustomCloud()?.gatewayUrl
+ : undefined;
+ if (customGateway && safeUrl(customGateway)?.origin === target.origin) {
+ return true;
+ }
+ if (isLoopbackHost(targetHost)) return isLoopbackHost(apiHostname);
+ // Only PostHog's own domains on the default port are trusted by name, and
+ // only the API host's own one, so a prod token never reaches a dev host.
+ const domain = postHogDomain(apiHostname);
+ return (
+ target.protocol === "https:" &&
+ target.port === "" &&
+ domain !== undefined &&
+ postHogDomain(targetHost) === domain
+ );
+}
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 3c4bc617ea5b..60fd17bd0ded 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -106,6 +106,7 @@ export {
configureCustomCloud,
customCloudSchema,
getCustomCloud,
+ isCredentialOriginAllowed,
isCustomCloudHost,
normalizeCustomCloud,
} from "./custom-cloud";
@@ -390,6 +391,7 @@ export {
getRelativeDateGroup,
} from "./time";
export { singleLineTitle } from "./title-text";
+export { tomlBasicString } from "./toml";
export {
mcpToolKey,
parseMcpToolName,
diff --git a/products/desktop/packages/shared/src/toml.test.ts b/products/desktop/packages/shared/src/toml.test.ts
new file mode 100644
index 000000000000..35f00bf40435
--- /dev/null
+++ b/products/desktop/packages/shared/src/toml.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { tomlBasicString } from "./toml";
+
+describe("tomlBasicString", () => {
+ it.each([
+ ["http://127.0.0.1:1/tok", '"http://127.0.0.1:1/tok"'],
+ ['a"b\\c', '"a\\"b\\\\c"'],
+ ["line\nbreak", '"line\\nbreak"'],
+ ["x\r\ty", '"x\\r\\ty"'],
+ ["nul\u0000del\u007f", '"nul\\u0000del\\u007f"'],
+ ])("escapes %j", (raw, quoted) => {
+ expect(tomlBasicString(raw)).toBe(quoted);
+ });
+
+ it("keeps an injected table header inside the string", () => {
+ expect(tomlBasicString('x"\n[evil]\nk = "v')).not.toMatch(/\n/);
+ });
+});
diff --git a/products/desktop/packages/shared/src/toml.ts b/products/desktop/packages/shared/src/toml.ts
new file mode 100644
index 000000000000..24e7654709a1
--- /dev/null
+++ b/products/desktop/packages/shared/src/toml.ts
@@ -0,0 +1,21 @@
+const TOML_ESCAPES: Record<string, string> = {
+ "\b": "\\b",
+ "\t": "\\t",
+ "\n": "\\n",
+ "\f": "\\f",
+ "\r": "\\r",
+ '"': '\\"',
+ "\\": "\\\\",
+};
+
+/** A TOML basic string, quoted, with every character TOML requires escaped. */
+export function tomlBasicString(value: string): string {
+ const escaped = value.replace(
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: TOML requires escaping control characters
+ /[\u0000-\u001f"\\\u007f]/g,
+ (ch) =>
+ TOML_ESCAPES[ch] ??
+ `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`,
+ );
+ return `"${escaped}"`;
+}
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index 461df61c7663..309d87a66041 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
@@ -167,6 +167,7 @@ vi.mock("./codex-home", () => ({
cleanupCodexHome: vi.fn().mockResolvedValue(undefined),
getCodexHomeDir: vi.fn(() => "/mock/codex-home"),
prepareCodexHome: vi.fn().mockResolvedValue("/mock/codex-home"),
+ writeCodexGatewayProvider: vi.fn().mockResolvedValue(true),
}));
vi.mock("node:fs", async (importOriginal) => {
@@ -194,6 +195,7 @@ import {
buildAutoApproveOutcome,
shouldAutoApprovePermissionRequest,
} from "./agent";
+import { cleanupCodexHome, writeCodexGatewayProvider } from "./codex-home";
import { AgentServiceEvent } from "./schemas";
// --- Test helpers ---
@@ -885,6 +887,56 @@ describe("AgentService", () => {
expect(codexMcp).toEqual(claudeMcp);
});
+ it("hands the CLIs the proxy placeholder, never the OAuth token", async () => {
+ await service.startSession(baseSessionParams);
+
+ expect(mockAgentRun).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ expect.objectContaining({
+ gatewayUrl: "http://127.0.0.1:9999",
+ gatewayApiKey: "posthog-code-auth-proxy",
+ }),
+ );
+ });
+
+ it("names the Codex base URL in its home config instead of argv", async () => {
+ await service.startSession({ ...baseSessionParams, adapter: "codex" });
+
+ expect(writeCodexGatewayProvider).toHaveBeenCalledWith(
+ "/mock/codex-home",
+ "http://127.0.0.1:9999/v1",
+ expect.anything(),
+ );
+ expect(mockAgentRun).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ expect.objectContaining({ codexBaseUrlInConfig: true }),
+ );
+ });
+
+ it("refuses to start Codex when the gateway config write fails", async () => {
+ vi.mocked(writeCodexGatewayProvider).mockResolvedValueOnce(false);
+
+ await expect(
+ service.startSession({ ...baseSessionParams, adapter: "codex" }),
+ ).rejects.toThrow(/Codex gateway config/);
+ expect(mockAgentRun).not.toHaveBeenCalled();
+ });
+
+ it("removes the Codex home when a Codex session fails to start", async () => {
+ vi.mocked(cleanupCodexHome).mockClear();
+ mockAgentRun.mockRejectedValueOnce(new Error("spawn failed"));
+
+ await expect(
+ service.startSession({ ...baseSessionParams, adapter: "codex" }),
+ ).rejects.toThrow("spawn failed");
+ expect(cleanupCodexHome).toHaveBeenCalledWith(
+ expect.any(String),
+ "run-1",
+ );
+ });
+
it("passes reasoning effort to local Codex startup options", async () => {
await service.startSession({
...baseSessionParams,
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
index 2ab8d248b2f3..2eea179e78e1 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -99,6 +99,7 @@ import { appendRichOutputPrompt } from "@posthog/shared/rich-output-prompt";
import { inject, injectable, preDestroy } from "inversify";
import { WORKSPACE_REPOSITORY } from "../../db/identifiers";
import type { IWorkspaceRepository } from "../../db/repositories/workspace-repository";
+import { AUTH_PROXY_PLACEHOLDER_CREDENTIAL } from "../auth-proxy/ports";
import { POSTHOG_PLUGIN_SERVICE } from "../posthog-plugin/identifiers";
import type { PosthogPluginService } from "../posthog-plugin/posthog-plugin";
import { PROCESS_TRACKING_SERVICE } from "../process-tracking/identifiers";
@@ -112,6 +113,7 @@ import {
getCodexCloudHomeDir,
getCodexHomeDir,
prepareCodexHome,
+ writeCodexGatewayProvider,
} from "./codex-home";
import { prepareContextWiki } from "./context-wiki";
import { discoverExternalPlugins } from "./discover-plugins";
@@ -1111,6 +1113,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
const claudeAuthGeneration = this.claudeAuthGeneration;
let codexHome: string | undefined;
+ let codexBaseUrlInConfig = false;
if (adapter === "codex") {
if (codexSubscription) {
codexHome = getCodexHomeDir(this.storagePaths.appDataPath, taskRunId);
@@ -1122,6 +1125,19 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
bundledSkillsDir,
log: this.log,
});
+ // The proxy URL carries a secret, so it never falls back to argv.
+ if (
+ !(await writeCodexGatewayProvider(
+ codexHome,
+ `${proxyUrl}/v1`,
+ this.log,
+ ))
+ ) {
+ throw new Error(
+ "Could not write the Codex gateway config; not starting the session.",
+ );
+ }
+ codexBaseUrlInConfig = true;
}
}
@@ -1130,6 +1146,8 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
codexModelAccess: codexSubscription ? "own-subscription" : undefined,
claudeModelAccess: claudeSubscription ? "own-subscription" : undefined,
gatewayUrl: proxyUrl,
+ gatewayApiKey: AUTH_PROXY_PLACEHOLDER_CREDENTIAL,
+ codexBaseUrlInConfig,
contextWiki: contextWiki ?? undefined,
codexBinaryPath:
adapter === "codex" ? this.getCodexBinaryPath() : undefined,
@@ -1485,6 +1503,12 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
taskRunId,
});
}
+ // The run's config.toml names the proxy URL and its path token.
+ if (adapter === "codex") {
+ await cleanupCodexHome(this.storagePaths.appDataPath, taskRunId).catch(
+ () => this.log.debug("Codex home cleanup failed", { taskRunId }),
+ );
+ }
if (!isRetry && isAuthError(err)) {
this.log.warn(
diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts
index 7db91eb132f9..7ce03933856e 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts
@@ -130,6 +130,18 @@ describe("AgentAuthAdapter", () => {
);
});
+ it.each(["https://app.dev.posthog.dev", "https://app.dev.posthog.dev."])(
+ "routes %s to the dev PostHog MCP",
+ async (apiHost) => {
+ await adapter.buildMcpServers({ ...baseCredentials, apiHost });
+
+ expect(deps.mcpProxy.register).toHaveBeenCalledWith(
+ "posthog",
+ "https://mcp.dev.posthog.dev/mcp",
+ );
+ },
+ );
+
it("gives a custom instance no PostHog MCP server", async () => {
configureCustomCloud({
url: "https://posthog.example.com",
diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts
index 24d984b71b55..4d0e5415fa24 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts
@@ -19,6 +19,15 @@ import { AGENT_AUTH, AGENT_LOGGER } from "./identifiers";
import type { AgentAuth, AgentLogger, AgentScopedLogger } from "./ports";
import type { Credentials } from "./schemas";
+function isPostHogDevHost(apiHost: string): boolean {
+ try {
+ const host = new URL(apiHost).hostname.replace(/\.+$/, "").toLowerCase();
+ return host === "posthog.dev" || host.endsWith(".posthog.dev");
+ } catch {
+ return false;
+ }
+}
+
/**
* Names capabilities rather than describing the server, because the agent's tool search
* reads this before the PostHog MCP has ever connected. Mirrors POSTHOG_MCP_DESCRIPTION
@@ -303,6 +312,10 @@ export class AgentAuthAdapter {
if (apiHost.includes("localhost") || apiHost.includes("127.0.0.1")) {
return "http://localhost:8787/mcp";
}
+ // The credential guard sends a posthog.dev token only to posthog.dev hosts.
+ if (isPostHogDevHost(apiHost)) {
+ return "https://mcp.dev.posthog.dev/mcp";
+ }
return "https://mcp.posthog.com/mcp";
}
diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
index 5282ebec6767..5a7a78038b75 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
@@ -25,6 +25,7 @@ import {
getCodexHomeDir,
prepareCodexHome,
stripMcpServers,
+ writeCodexGatewayProvider,
} from "./codex-home";
const noopLog = { debug() {}, info() {}, warn() {}, error() {} };
@@ -415,3 +416,146 @@ describe("stripMcpServers", () => {
expect(stripMcpServers(toml.join("\n"))).toBe(expected.join("\n"));
});
});
+
+describe("stripMcpServers quoted keys", () => {
+ it("drops quoted mcp_servers tables and keys", () => {
+ const toml = [
+ 'model = "x"',
+ '"mcp_servers".a = { command = "a" }',
+ '["mcp_servers".b]',
+ 'command = "b"',
+ "[ 'mcp_servers' . c ]",
+ 'command = "c"',
+ ].join("\n");
+
+ expect(stripMcpServers(toml)).toBe('model = "x"');
+ });
+});
+
+describe("writeCodexGatewayProvider", () => {
+ let home: string;
+
+ beforeEach(async () => {
+ home = await mkdtemp(path.join(tmpdir(), "codex-provider-"));
+ });
+
+ afterEach(async () => {
+ await rm(home, { recursive: true, force: true });
+ });
+
+ it("writes the base URL into an owner-only config", async () => {
+ const ok = await writeCodexGatewayProvider(
+ home,
+ "http://127.0.0.1:5000/secret/v1",
+ noopLog,
+ );
+
+ const configPath = path.join(home, "config.toml");
+ expect(ok).toBe(true);
+ expect(readFileSync(configPath, "utf-8")).toBe(
+ '[model_providers.posthog]\nbase_url = "http://127.0.0.1:5000/secret/v1"\n',
+ );
+ if (process.platform !== "win32") {
+ expect(statSync(configPath).mode & 0o777).toBe(0o600);
+ }
+ });
+
+ it("keeps a base URL with a newline inside one TOML string", async () => {
+ await writeCodexGatewayProvider(
+ home,
+ 'http://127.0.0.1:5000/x"\n[evil]',
+ noopLog,
+ );
+
+ expect(readFileSync(path.join(home, "config.toml"), "utf-8")).toBe(
+ '[model_providers.posthog]\nbase_url = "http://127.0.0.1:5000/x\\"\\n[evil]"\n',
+ );
+ });
+
+ it("replaces the user's provider tables and keeps everything else", async () => {
+ await writeFile(
+ path.join(home, "config.toml"),
+ [
+ 'model = "gpt-6-sol"',
+ 'model_providers.local = { base_url = "http://x" }',
+ "",
+ "[model_providers.posthog]",
+ 'base_url = "https://attacker.example/v1"',
+ "",
+ "[profiles.fast]",
+ 'model = "gpt-6-luna"',
+ ].join("\n"),
+ );
+
+ await writeCodexGatewayProvider(
+ home,
+ "http://127.0.0.1:5000/t/v1",
+ noopLog,
+ );
+
+ const config = readFileSync(path.join(home, "config.toml"), "utf-8");
+ expect(config).not.toContain("attacker");
+ expect(config).not.toContain("model_providers.local");
+ expect(config).toContain('model = "gpt-6-sol"');
+ expect(config).toContain("[profiles.fast]");
+ expect(
+ config.trimEnd().endsWith('base_url = "http://127.0.0.1:5000/t/v1"'),
+ ).toBe(true);
+ expect(config.match(/\[model_providers\.posthog\]/g)).toHaveLength(1);
+ });
+
+ it.each([
+ '["model_providers".posthog]',
+ '[model_providers."posthog"]',
+ "['model_providers'.'posthog']",
+ "[ model_providers . posthog ]",
+ ])("replaces a quoted or spaced provider header %s", async (header) => {
+ await writeFile(
+ path.join(home, "config.toml"),
+ [header, 'base_url = "https://attacker.example/v1"'].join("\n"),
+ );
+
+ await writeCodexGatewayProvider(
+ home,
+ "http://127.0.0.1:5000/t/v1",
+ noopLog,
+ );
+
+ const config = readFileSync(path.join(home, "config.toml"), "utf-8");
+ expect(config).toBe(
+ '[model_providers.posthog]\nbase_url = "http://127.0.0.1:5000/t/v1"\n',
+ );
+ });
+
+ it("drops quoted top-level provider keys", async () => {
+ await writeFile(
+ path.join(home, "config.toml"),
+ [
+ '"model_providers".posthog = { base_url = "https://a.example" }',
+ "'model_providers' = {}",
+ '"model_providers.posthog" = "kept"',
+ ].join("\n"),
+ );
+
+ await writeCodexGatewayProvider(
+ home,
+ "http://127.0.0.1:5000/t/v1",
+ noopLog,
+ );
+
+ const config = readFileSync(path.join(home, "config.toml"), "utf-8");
+ expect(config).not.toContain("a.example");
+ expect(config).not.toContain("'model_providers' =");
+ expect(config).toContain('"model_providers.posthog" = "kept"');
+ });
+
+ it("reports failure so the caller can refuse to start", async () => {
+ const ok = await writeCodexGatewayProvider(
+ path.join(home, "missing", "dir"),
+ "http://127.0.0.1:5000/t/v1",
+ noopLog,
+ );
+
+ expect(ok).toBe(false);
+ });
+});
diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
index 0fac0c19a8b0..0096b53a8d46 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
@@ -1,6 +1,7 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
+import { tomlBasicString } from "@posthog/shared";
import {
findSkillDirs,
getUserSkillsDir,
@@ -145,8 +146,16 @@ export async function prepareCodexHome(options: {
return codexHome;
}
-const MCP_SERVERS_HEADER = /^\[\[?\s*mcp_servers\s*(?:[.\]])/;
-const MCP_SERVERS_KEY = /^mcp_servers\s*[.=]/;
+/** Matches a table header and a top-level key rooted at `name`, bare or quoted. */
+function rootPatterns(name: string): { header: RegExp; key: RegExp } {
+ const root = `(?:${name}|"${name}"|'${name}')`;
+ return {
+ header: new RegExp(String.raw`^\[\[?\s*${root}\s*[.\]]`),
+ key: new RegExp(String.raw`^${root}\s*[.=]`),
+ };
+}
+
+const MCP_SERVERS = rootPatterns("mcp_servers");
/**
* Drops every `mcp_servers` definition from a codex config.toml: `[mcp_servers]`
@@ -162,6 +171,47 @@ const MCP_SERVERS_KEY = /^mcp_servers\s*[.=]/;
* rejects at startup.
*/
export function stripMcpServers(toml: string): string {
+ return stripTomlRoot(toml, MCP_SERVERS.header, MCP_SERVERS.key);
+}
+
+const MODEL_PROVIDERS = rootPatterns("model_providers");
+
+export async function writeCodexGatewayProvider(
+ codexHome: string,
+ baseUrl: string,
+ log: AgentScopedLogger,
+): Promise<boolean> {
+ const configPath = path.join(codexHome, "config.toml");
+ try {
+ const existing = await fs.promises
+ .readFile(configPath, "utf-8")
+ .catch(() => "");
+ const stripped = stripTomlRoot(
+ existing,
+ MODEL_PROVIDERS.header,
+ MODEL_PROVIDERS.key,
+ ).replace(/\s*$/, "");
+ const table = `[model_providers.posthog]\nbase_url = ${tomlBasicString(baseUrl)}\n`;
+ await fs.promises.writeFile(
+ configPath,
+ stripped ? `${stripped}\n\n${table}` : table,
+ { mode: 0o600 },
+ );
+ await fs.promises.chmod(configPath, 0o600);
+ return true;
+ } catch (err) {
+ log.warn("Failed to write the codex gateway provider", {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return false;
+ }
+}
+
+function stripTomlRoot(
+ toml: string,
+ headerPattern: RegExp,
+ keyPattern: RegExp,
+): string {
const kept: string[] = [];
let inMcpTable = false;
let inTable = false;
@@ -176,10 +226,10 @@ export function stripMcpServers(toml: string): string {
const trimmed = line.trim();
if (structural && trimmed.startsWith("[")) {
inTable = true;
- inMcpTable = MCP_SERVERS_HEADER.test(trimmed);
+ inMcpTable = headerPattern.test(trimmed);
}
const drop: boolean = structural
- ? inMcpTable || (!inTable && MCP_SERVERS_KEY.test(trimmed))
+ ? inMcpTable || (!inTable && keyPattern.test(trimmed))
: inMcpTable || dropRestOfValue;
value = scanLine(line, value);
diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts
index c2c14071a000..31b73a41b144 100644
--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts
@@ -1,6 +1,7 @@
+import http from "node:http";
import type { RootLogger } from "@posthog/di/logger";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { AuthProxyService } from "./auth-proxy";
+import { AuthProxyService, MAX_BODY_BYTES, PROXY_TIMEOUTS } from "./auth-proxy";
import type { AuthProxyAuth } from "./ports";
type AuthMock = {
@@ -163,3 +164,283 @@ describe("AuthProxyService", () => {
expect(await res.text()).toBe("data: one\n\ndata: two\n\n");
});
});
+
+describe("AuthProxyService legacy hardening", () => {
+ let authFetch: ReturnType<typeof vi.fn>;
+ let logs: unknown[][];
+ let service: AuthProxyService;
+
+ beforeEach(() => {
+ authFetch = vi.fn();
+ logs = [];
+ const record =
+ (level: string) =>
+ (...args: unknown[]) =>
+ logs.push([level, ...args]);
+ const scoped = {
+ debug: record("debug"),
+ info: record("info"),
+ warn: record("warn"),
+ error: record("error"),
+ };
+ const logger = { ...scoped, scope: () => scoped } as unknown as RootLogger;
+ service = new AuthProxyService(
+ { authenticatedFetch: authFetch } as AuthProxyAuth,
+ logger,
+ );
+ });
+
+ afterEach(async () => {
+ await service.stop();
+ });
+
+ it("strips inbound credentials and cookies and refuses redirects", async () => {
+ authFetch.mockResolvedValue(new Response("ok"));
+ const proxyUrl = await service.start("https://gateway.example");
+
+ await fetch(`${proxyUrl}/v1/messages`, {
+ method: "POST",
+ headers: {
+ authorization: "Bearer posthog-code-auth-proxy",
+ "x-api-key": "posthog-code-auth-proxy",
+ cookie: "session=abc",
+ },
+ body: "{}",
+ });
+
+ const [, init] = authFetch.mock.calls[0];
+ expect(init.redirect).toBe("manual");
+ expect(init.headers).not.toHaveProperty("authorization");
+ expect(init.headers).not.toHaveProperty("x-api-key");
+ expect(init.headers).not.toHaveProperty("cookie");
+ });
+
+ it("strips cookies and auth challenges from the response", async () => {
+ authFetch.mockResolvedValue(
+ new Response("ok", {
+ headers: {
+ "set-cookie": "a=b",
+ "www-authenticate": "Bearer",
+ "x-posthog-trace-id": "trace",
+ },
+ }),
+ );
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const res = await fetch(`${proxyUrl}/v1/messages`);
+
+ expect(res.headers.get("set-cookie")).toBeNull();
+ expect(res.headers.get("www-authenticate")).toBeNull();
+ expect(res.headers.get("x-posthog-trace-id")).toBe("trace");
+ });
+
+ function hopRequest(
+ url: string,
+ headers: http.OutgoingHttpHeaders,
+ ): Promise<http.IncomingMessage> {
+ return new Promise((resolve, reject) => {
+ const req = http.request(url, { headers, agent: false }, (res) => {
+ res.resume();
+ res.on("end", () => resolve(res));
+ });
+ req.on("error", reject);
+ req.end();
+ });
+ }
+
+ it("strips hop-by-hop request headers and any the Connection value names", async () => {
+ authFetch.mockResolvedValue(new Response("ok"));
+ const proxyUrl = await service.start("https://gateway.example");
+
+ await hopRequest(`${proxyUrl}/v1/models`, {
+ connection: "close, x-hop",
+ "keep-alive": "timeout=5",
+ "proxy-connection": "keep-alive",
+ te: "trailers",
+ upgrade: "websocket",
+ "x-hop": "1",
+ "x-kept": "1",
+ });
+
+ const headers = Object.keys(authFetch.mock.calls[0][1].headers);
+ for (const name of [
+ "connection",
+ "keep-alive",
+ "proxy-connection",
+ "te",
+ "upgrade",
+ "x-hop",
+ ]) {
+ expect(headers).not.toContain(name);
+ }
+ expect(headers).toContain("x-kept");
+ });
+
+ it("strips hop-by-hop response headers and any the Connection value names", async () => {
+ authFetch.mockResolvedValue(
+ new Response("ok", {
+ headers: {
+ connection: "x-hop",
+ "keep-alive": "timeout=999",
+ "proxy-connection": "keep-alive",
+ "proxy-authenticate": "Basic",
+ trailer: "x-sum",
+ upgrade: "websocket",
+ "x-hop": "1",
+ "x-kept": "1",
+ },
+ }),
+ );
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const res = await hopRequest(`${proxyUrl}/v1/models`, {});
+
+ expect(res.headers["keep-alive"]).toBeUndefined();
+ for (const name of [
+ "proxy-connection",
+ "proxy-authenticate",
+ "trailer",
+ "upgrade",
+ "x-hop",
+ ]) {
+ expect(res.headers[name]).toBeUndefined();
+ }
+ expect(res.headers["x-kept"]).toBe("1");
+ });
+
+ it("turns an upstream redirect into a 502", async () => {
+ authFetch.mockResolvedValue(
+ new Response(null, {
+ status: 302,
+ headers: { location: "https://evil.example" },
+ }),
+ );
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const res = await fetch(`${proxyUrl}/v1/messages`, { redirect: "manual" });
+
+ expect(res.status).toBe(502);
+ expect(res.headers.get("location")).toBeNull();
+ });
+
+ it("refuses a body over the cap with a size error the classifier knows", async () => {
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const res = await fetch(`${proxyUrl}/v1/messages`, {
+ method: "POST",
+ body: Buffer.alloc(MAX_BODY_BYTES + 1, 97),
+ });
+
+ expect(res.status).toBe(413);
+ expect(await res.text()).toContain("request body too large");
+ expect(authFetch).not.toHaveBeenCalled();
+ });
+
+ it("never logs the path token or the upstream query string", async () => {
+ authFetch.mockResolvedValue(new Response("ok"));
+ const proxyUrl = await service.start("https://gateway.example");
+ const token = new URL(proxyUrl).pathname.slice(1);
+ const origin = new URL(proxyUrl).origin;
+
+ await fetch(`${proxyUrl}/v1/messages?secret=q`);
+ const traversal = await rawRequest(`${origin}/${token}/..%2f..%2fx`);
+ expect(traversal).toBe(403);
+ authFetch.mockRejectedValueOnce(new Error("boom"));
+ await fetch(`${proxyUrl}/v1/messages?secret=q`);
+
+ const text = JSON.stringify(logs);
+ expect(logs.length).toBeGreaterThan(0);
+ expect(text).not.toContain(token);
+ expect(text).not.toContain("secret=q");
+ });
+
+ describe("timeouts", () => {
+ const saved = { ...PROXY_TIMEOUTS };
+ afterEach(() => Object.assign(PROXY_TIMEOUTS, saved));
+
+ it("answers 408 when the request body stalls", async () => {
+ PROXY_TIMEOUTS.bodyMs = 50;
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const status = await new Promise<number>((resolve, reject) => {
+ const req = http.request(`${proxyUrl}/v1/messages`, {
+ method: "POST",
+ headers: { "content-length": "100" },
+ });
+ req.on("response", (res) => {
+ res.resume();
+ resolve(res.statusCode ?? 0);
+ });
+ req.on("error", reject);
+ req.write("partial");
+ });
+
+ expect(status).toBe(408);
+ expect(authFetch).not.toHaveBeenCalled();
+ });
+
+ it("keeps streaming past the headers timeout once headers arrive", async () => {
+ PROXY_TIMEOUTS.headersMs = 50;
+ authFetch.mockImplementation(async (_url: string, init: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ init.signal?.addEventListener("abort", () =>
+ controller.error(new DOMException("aborted", "AbortError")),
+ );
+ controller.enqueue(new TextEncoder().encode("a"));
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ controller.enqueue(new TextEncoder().encode("b"));
+ controller.close();
+ },
+ });
+ return new Response(body);
+ });
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const res = await fetch(`${proxyUrl}/v1/messages`);
+
+ expect(await res.text()).toBe("ab");
+ });
+
+ it("answers 504 and logs a warning when the upstream sends no headers", async () => {
+ PROXY_TIMEOUTS.headersMs = 50;
+ authFetch.mockImplementation(
+ (_url: string, init: RequestInit) =>
+ new Promise((_resolve, reject) => {
+ init.signal?.addEventListener("abort", () =>
+ reject(new DOMException("aborted", "AbortError")),
+ );
+ }),
+ );
+ const proxyUrl = await service.start("https://gateway.example");
+
+ const res = await fetch(`${proxyUrl}/v1/messages`);
+
+ expect(res.status).toBe(504);
+ expect(
+ logs.some(
+ ([level, message]) =>
+ level === "warn" &&
+ message === "Auth proxy upstream sent no response headers in time",
+ ),
+ ).toBe(true);
+ });
+ });
+});
+
+function rawRequest(url: string): Promise<number> {
+ const parsed = new URL(url);
+ return new Promise((resolve, reject) => {
+ const req = http.request({
+ host: parsed.hostname,
+ port: parsed.port,
+ path: url.slice(parsed.origin.length),
+ });
+ req.on("response", (res) => {
+ res.resume();
+ resolve(res.statusCode ?? 0);
+ });
+ req.on("error", reject);
+ req.end();
+ });
+}
diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts
index 0de28ca01f32..c42260fd314c 100644
--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts
+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts
@@ -7,6 +7,7 @@ import {
} from "@posthog/di/logger";
import { serializeError } from "@posthog/shared";
import { inject, injectable } from "inversify";
+import { hopByHop } from "../proxy-stream/hop-by-hop";
import {
type StreamProgress,
streamBodyToResponse,
@@ -14,6 +15,35 @@ import {
import { AUTH_PROXY_AUTH } from "./identifiers";
import type { AuthProxyAuth } from "./ports";
+type Body = Buffer<ArrayBuffer>;
+
+const STRIPPED_REQUEST_HEADERS = new Set([
+ "authorization",
+ "x-api-key",
+ "api-key",
+ "anthropic-auth-token",
+ "proxy-authorization",
+ "content-length",
+ "transfer-encoding",
+ "cookie",
+]);
+
+const STRIPPED_RESPONSE_HEADERS = new Set([
+ "transfer-encoding",
+ "content-encoding",
+ "content-length",
+ "set-cookie",
+ "www-authenticate",
+]);
+
+export const MAX_BODY_BYTES = 16 * 1024 * 1024;
+export const PROXY_TIMEOUTS = {
+ bodyMs: 60_000,
+ // Non-streaming calls can run for minutes before the first byte, so this
+ // only catches a wedged connection.
+ headersMs: 10 * 60_000,
+};
+
@injectable()
export class AuthProxyService {
private server: http.Server | null = null;
@@ -156,29 +186,20 @@ export class AuthProxyService {
if (!sameOrigin || hasPathTraversal) {
this.log.warn("Rejected proxy request with invalid target URL", {
method: req.method,
- incoming: req.url,
- target: targetUrl.toString(),
});
res.writeHead(403);
res.end("Forbidden");
return;
}
- const strippedHeaders = new Set([
- "authorization",
- "x-api-key",
- "api-key",
- "anthropic-auth-token",
- "proxy-authorization",
- "content-length",
- "transfer-encoding",
- ]);
const headers: Record<string, string> = {};
+ const requestHopByHop = hopByHop(req.headers.connection);
for (const [key, value] of Object.entries(req.headers)) {
+ const name = key.toLowerCase();
if (
- key === "host" ||
- key === "connection" ||
- strippedHeaders.has(key.toLowerCase())
+ name === "host" ||
+ requestHopByHop.has(name) ||
+ STRIPPED_REQUEST_HEADERS.has(name)
) {
continue;
}
@@ -211,37 +232,89 @@ export class AuthProxyService {
};
if (req.method !== "GET" && req.method !== "HEAD") {
- const chunks: Buffer[] = [];
- req.on("data", (chunk: Buffer) => chunks.push(chunk));
- req.on("end", () => {
- fetchOptions.body = Buffer.concat(chunks);
- this.forwardRequest(targetUrl.toString(), fetchOptions, res);
+ void readBody(req).then((body) => {
+ if (typeof body === "string") {
+ this.log.warn("Auth proxy refused a request body", {
+ method: req.method,
+ reason: body,
+ });
+ }
+ if (body === "too_large") {
+ // Worded to match the "request body too large" size-error pattern.
+ jsonError(
+ res,
+ 413,
+ { type: "request_too_large", message: "request body too large" },
+ { connection: "close" },
+ );
+ return;
+ }
+ if (body === "timeout" || body === "aborted") {
+ jsonError(
+ res,
+ 408,
+ { type: "timeout_error", message: "request body not received" },
+ { connection: "close" },
+ );
+ return;
+ }
+ fetchOptions.body = body;
+ void this.forwardRequest(targetUrl, fetchOptions, res, abort);
});
} else {
- this.forwardRequest(targetUrl.toString(), fetchOptions, res);
+ void this.forwardRequest(targetUrl, fetchOptions, res, abort);
}
}
private async forwardRequest(
- url: string,
+ target: URL,
options: RequestInit,
res: http.ServerResponse,
+ abort: AbortController,
): Promise<void> {
+ if (abort.signal.aborted) return;
const startedAt = Date.now();
const progress: StreamProgress = { bytesWritten: 0 };
+ // Logged without the query string, which may carry request detail.
+ const url = `${target.origin}${target.pathname}`;
let status = 0;
+ let timedOut = false;
try {
- const response = await this.auth.authenticatedFetch(url, options);
+ const timer = setTimeout(() => {
+ timedOut = true;
+ abort.abort();
+ }, PROXY_TIMEOUTS.headersMs);
+ let response: Response;
+ try {
+ response = await this.auth.authenticatedFetch(target.toString(), {
+ ...options,
+ redirect: "manual",
+ });
+ } finally {
+ clearTimeout(timer);
+ }
status = response.status;
+ if (status >= 300 && status < 400) {
+ void response.body?.cancel().catch(() => {});
+ this.log.warn("Auth proxy refused an upstream redirect", {
+ url,
+ method: options.method,
+ status,
+ });
+ jsonError(res, 502, {
+ type: "api_error",
+ message: "Unexpected redirect from the PostHog gateway",
+ });
+ return;
+ }
+
const responseHeaders: Record<string, string> = {};
- const stripHeaders = new Set([
- "transfer-encoding",
- "content-encoding",
- "content-length",
- ]);
+ const responseHopByHop = hopByHop(response.headers.get("connection"));
response.headers.forEach((value: string, key: string) => {
- if (stripHeaders.has(key)) return;
+ const name = key.toLowerCase();
+ if (STRIPPED_RESPONSE_HEADERS.has(name) || responseHopByHop.has(name))
+ return;
responseHeaders[key] = value;
});
@@ -257,6 +330,18 @@ export class AuthProxyService {
bytesStreamed: progress.bytesWritten,
});
} catch (err) {
+ if (timedOut) {
+ this.log.warn("Auth proxy upstream sent no response headers in time", {
+ url,
+ method: options.method,
+ durationMs: Date.now() - startedAt,
+ });
+ jsonError(res, 504, {
+ type: "timeout_error",
+ message: "PostHog gateway did not respond",
+ });
+ return;
+ }
if (options.signal?.aborted) {
this.log.debug("Upstream fetch aborted after client disconnect", {
url,
@@ -282,3 +367,52 @@ export class AuthProxyService {
}
}
}
+
+function jsonError(
+ res: http.ServerResponse,
+ status: number,
+ error: Record<string, string>,
+ extraHeaders: Record<string, string> = {},
+): void {
+ if (res.headersSent) {
+ res.end();
+ return;
+ }
+ res.writeHead(status, {
+ "content-type": "application/json",
+ ...extraHeaders,
+ });
+ res.end(JSON.stringify({ error }));
+}
+
+function readBody(
+ req: http.IncomingMessage,
+): Promise<Body | "too_large" | "timeout" | "aborted"> {
+ return new Promise((resolve) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ let settled = false;
+ const finish = (result: Body | "too_large" | "timeout" | "aborted") => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ req.off("data", onData);
+ // Drain the rest so the socket can carry the error response.
+ if (typeof result === "string") req.resume();
+ resolve(result);
+ };
+ const timer = setTimeout(() => finish("timeout"), PROXY_TIMEOUTS.bodyMs);
+ const onData = (chunk: Buffer) => {
+ size += chunk.byteLength;
+ if (size > MAX_BODY_BYTES) {
+ finish("too_large");
+ return;
+ }
+ chunks.push(chunk);
+ };
+ req.on("data", onData);
+ req.on("end", () => finish(Buffer.concat(chunks)));
+ req.on("error", () => finish("aborted"));
+ req.on("aborted", () => finish("aborted"));
+ });
+}
diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts
index 1897069f6c87..6c60c084bcd6 100644
--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts
+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts
@@ -1,3 +1,5 @@
export interface AuthProxyAuth {
authenticatedFetch(url: string, init?: RequestInit): Promise<Response>;
}
+
+export const AUTH_PROXY_PLACEHOLDER_CREDENTIAL = "posthog-code-auth-proxy";
diff --git a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts
index aaf23a6e6a41..d598d422a8cc 100644
--- a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts
@@ -56,7 +56,9 @@ describe("McpProxyService", () => {
it("starts on a loopback port and returns a URL for register()", async () => {
await service.start();
const url = service.register("alpha", "https://upstream.example/path");
- expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/alpha$/);
+ expect(url).toMatch(
+ /^http:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9_-]{43}\/alpha$/,
+ );
});
it("throws from register() before start()", () => {
@@ -68,7 +70,9 @@ describe("McpProxyService", () => {
it("handles concurrent start() calls without races", async () => {
await Promise.all([service.start(), service.start(), service.start()]);
const url = service.register("alpha", "https://upstream.example");
- expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/alpha$/);
+ expect(url).toMatch(
+ /^http:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9_-]{43}\/alpha$/,
+ );
});
it("stop() closes the server and clears registered targets", async () => {
@@ -82,6 +86,103 @@ describe("McpProxyService", () => {
});
describe("request forwarding", () => {
+ it.each([
+ [
+ "a wrong secret",
+ (url: string) =>
+ url.replace(/\/[^/]+\/alpha$/, `/${"x".repeat(43)}/alpha`),
+ ],
+ ["no secret", (url: string) => url.replace(/\/[^/]+\/alpha$/, "/alpha")],
+ [
+ "a truncated secret",
+ (url: string) => url.replace(/[A-Za-z0-9_-]\/alpha$/, "/alpha"),
+ ],
+ ])("refuses a request with %s", async (_label, mangle) => {
+ await service.start();
+ const proxyUrl = service.register("alpha", "https://upstream.example");
+
+ const res = await fetch(mangle(proxyUrl));
+
+ expect(res.status).toBe(404);
+ expect(await res.text()).toBe("Unknown target");
+ expect(authServiceMock.authenticatedFetch).not.toHaveBeenCalled();
+ });
+
+ it("issues a new secret after a restart", async () => {
+ await service.start();
+ const before = service.register("alpha", "https://upstream.example");
+ await service.stop();
+ await service.start();
+ const after = service.register("alpha", "https://upstream.example");
+
+ expect(new URL(after).pathname).not.toBe(new URL(before).pathname);
+ });
+
+ it("strips hop-by-hop headers in both directions", async () => {
+ authServiceMock.authenticatedFetch.mockResolvedValue(
+ new Response("{}", {
+ status: 200,
+ headers: {
+ "content-type": "application/json",
+ "keep-alive": "timeout=5",
+ "proxy-connection": "keep-alive",
+ "proxy-authenticate": "Basic",
+ upgrade: "h2c",
+ "x-hop": "1",
+ connection: "x-hop",
+ "x-kept": "yes",
+ },
+ }),
+ );
+ await service.start();
+ const proxyUrl = service.register("alpha", "https://upstream.example");
+ const { request } = await import("node:http");
+
+ const res = await new Promise<import("node:http").IncomingMessage>(
+ (resolve, reject) => {
+ const req = request(proxyUrl, {
+ headers: {
+ connection: "keep-alive, x-drop",
+ "keep-alive": "timeout=5",
+ "proxy-connection": "keep-alive",
+ "proxy-authorization": "Basic abc",
+ te: "trailers",
+ "x-drop": "1",
+ "x-keep": "1",
+ },
+ });
+ req.on("response", resolve);
+ req.on("error", reject);
+ req.end();
+ },
+ );
+ res.resume();
+
+ const init = authServiceMock.authenticatedFetch.mock
+ .calls[0]?.[1] as RequestInit;
+ const sent = Object.keys(init.headers as Record<string, string>);
+ for (const name of [
+ "connection",
+ "keep-alive",
+ "proxy-connection",
+ "proxy-authorization",
+ "te",
+ "x-drop",
+ ]) {
+ expect(sent).not.toContain(name);
+ }
+ expect(sent).toContain("x-keep");
+ for (const name of [
+ "proxy-connection",
+ "proxy-authenticate",
+ "upgrade",
+ "x-hop",
+ ]) {
+ expect(res.headers[name]).toBeUndefined();
+ }
+ expect(res.headers["x-kept"]).toBe("yes");
+ });
+
it("returns 404 for unknown targets", async () => {
await service.start();
const proxyUrl = service.register("alpha", "https://upstream.example");
@@ -201,11 +302,12 @@ describe("McpProxyService", () => {
await service.start();
service.register("alpha", "https://upstream.example/inst-2/");
- const port = new URL(
- service.register("alpha", "https://upstream.example/inst-2/"),
- ).port;
+ const proxyUrl = service.register(
+ "alpha",
+ "https://upstream.example/inst-2/",
+ );
- await fetch(`http://127.0.0.1:${port}/alpha/tools/list`);
+ await fetch(`${proxyUrl}/tools/list`);
const [url] = authServiceMock.authenticatedFetch.mock.calls.at(-1) ?? [];
expect(url).toBe("https://upstream.example/inst-2/tools/list");
diff --git a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts
index 662c97b74200..d66a07bf5561 100644
--- a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts
+++ b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts
@@ -1,3 +1,4 @@
+import { randomBytes, timingSafeEqual } from "node:crypto";
import http from "node:http";
import {
ROOT_LOGGER,
@@ -5,6 +6,7 @@ import {
type ScopedLogger,
} from "@posthog/di/logger";
import { inject, injectable, preDestroy } from "inversify";
+import { hopByHop } from "../proxy-stream/hop-by-hop";
import { streamBodyToResponse } from "../proxy-stream/proxy-stream";
import { MCP_PROXY_AUTH } from "./identifiers";
import type { McpProxyAuth } from "./ports";
@@ -26,9 +28,8 @@ function truncateRequestBody(body: RequestInit["body"]): string | undefined {
* this proxy we would either need to tear the transport down on every token
* rotation (expensive, racy) or leave it serving stale tokens.
*
- * The proxy only listens on 127.0.0.1 and strips inbound Authorization headers
- * before forwarding, but any local process can still use it to issue requests
- * on the user's behalf — acceptable for a single-user desktop app.
+ * The proxy listens on 127.0.0.1 and serves a path only under a per-start
+ * secret, so another local process cannot reach a target without the URL.
*/
/**
* Whose credential an auth failure from a target is about.
@@ -49,6 +50,7 @@ interface McpProxyTarget {
export class McpProxyService {
private server: http.Server | null = null;
private port: number | null = null;
+ private secret: Buffer | null = null;
private startPromise: Promise<void> | null = null;
private targets = new Map<string, McpProxyTarget>();
@@ -78,6 +80,7 @@ export class McpProxyService {
this.handleRequest(req, res);
});
this.server = server;
+ this.secret = Buffer.from(randomBytes(32).toString("base64url"));
await new Promise<void>((resolve, reject) => {
server.listen(0, "127.0.0.1", () => {
@@ -115,7 +118,7 @@ export class McpProxyService {
url: targetUrl,
credentialOwner: options.credentialOwner ?? "posthog",
});
- return `http://127.0.0.1:${this.port}/${encodeURIComponent(id)}`;
+ return `http://127.0.0.1:${this.port}/${this.secret}/${encodeURIComponent(id)}`;
}
@preDestroy()
@@ -130,6 +133,7 @@ export class McpProxyService {
});
this.server = null;
this.port = null;
+ this.secret = null;
this.startPromise = null;
this.targets.clear();
}
@@ -140,17 +144,18 @@ export class McpProxyService {
): void {
const incoming = new URL(req.url ?? "/", "http://placeholder");
const segments = incoming.pathname.split("/").filter(Boolean);
- const [rawId, ...rest] = segments;
+ const [rawSecret, rawId, ...rest] = segments;
const id = rawId ? decodeURIComponent(rawId) : "";
- const target = this.targets.get(id);
+ const target = this.hasSecret(rawSecret) ? this.targets.get(id) : undefined;
if (!target) {
- // MCP clients probe RFC 8414 OAuth discovery at the proxy root before
- // falling back to direct auth; a quiet 404 is the expected answer.
- if (id === ".well-known") {
- this.log.debug("MCP proxy OAuth discovery probe", { url: req.url });
+ // MCP clients probe RFC 8414 OAuth discovery at the origin root, outside
+ // the secret, so a quiet 404 is the expected answer. The URL is not
+ // logged because it can carry the secret.
+ if (rawSecret === ".well-known") {
+ this.log.debug("MCP proxy OAuth discovery probe");
} else {
- this.log.warn("Unknown MCP proxy target", { id, url: req.url });
+ this.log.warn("Unknown MCP proxy target");
}
res.writeHead(404);
res.end("Unknown target");
@@ -163,18 +168,15 @@ export class McpProxyService {
(suffix ? `${targetBase}/${suffix}` : targetBase) + incoming.search;
const strippedHeaders = new Set([
+ "host",
"authorization",
"proxy-authorization",
"content-length",
- "transfer-encoding",
+ ...hopByHop(req.headers.connection),
]);
const headers: Record<string, string> = {};
for (const [key, value] of Object.entries(req.headers)) {
- if (
- key === "host" ||
- key === "connection" ||
- strippedHeaders.has(key.toLowerCase())
- ) {
+ if (strippedHeaders.has(key.toLowerCase())) {
continue;
}
if (typeof value === "string") {
@@ -323,6 +325,14 @@ export class McpProxyService {
}
}
+ private hasSecret(candidate: string | undefined): boolean {
+ if (!this.secret || !candidate) return false;
+ const given = Buffer.from(candidate);
+ return (
+ given.length === this.secret.length && timingSafeEqual(given, this.secret)
+ );
+ }
+
private isAuthErrorBody(bodyText: string, status: number): boolean {
// Only a rejected token carries `authentication_failed`. A permission denial
// shares `type: "authentication_error"` but carries `code: "permission_denied"`,
@@ -343,9 +353,9 @@ export class McpProxyService {
private buildResponseHeaders(response: Response): Record<string, string> {
const stripHeaders = new Set([
- "transfer-encoding",
"content-encoding",
"content-length",
+ ...hopByHop(response.headers.get("connection")),
]);
const headers: Record<string, string> = {};
response.headers.forEach((value: string, key: string) => {
diff --git a/products/desktop/packages/workspace-server/src/services/proxy-stream/hop-by-hop.ts b/products/desktop/packages/workspace-server/src/services/proxy-stream/hop-by-hop.ts
new file mode 100644
index 000000000000..39571bb08dac
--- /dev/null
+++ b/products/desktop/packages/workspace-server/src/services/proxy-stream/hop-by-hop.ts
@@ -0,0 +1,23 @@
+const HOP_BY_HOP_HEADERS = [
+ "connection",
+ "keep-alive",
+ "proxy-connection",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailer",
+ "upgrade",
+ "transfer-encoding",
+];
+
+/** Hop-by-hop names plus any header the Connection value lists. */
+export function hopByHop(
+ connection: string | string[] | null | undefined,
+): Set<string> {
+ const listed = [connection ?? []]
+ .flat()
+ .flatMap((value) => value.split(","))
+ .map((name) => name.trim().toLowerCase())
+ .filter(Boolean);
+ return new Set([...HOP_BY_HOP_HEADERS, ...listed]);
+}