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): redact authorization headers on the agent event stream (#97450)

Shy Alter4035bb5ccdc8
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 620319121470..b47e4c91abc9 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -2579,6 +2579,39 @@ describe("AgentServer HTTP Mode", () => {
expect(testServer.pendingEvents).toEqual([event]);
});
+
+ it("redacts authorization headers before an event leaves the sandbox", () => {
+ const testServer = exposeBroadcastEvent(createServer());
+ testServer.eventStreamSender = {
+ enqueue: vi.fn(),
+ stop: vi.fn(async () => {}),
+ };
+ testServer.session = null;
+
+ testServer.broadcastEvent({
+ type: "notification",
+ notification: {
+ method: "session/new",
+ params: {
+ mcpServers: [
+ {
+ name: "posthog",
+ headers: [
+ { name: "Authorization", value: "Bearer mcp-secret" },
+ { name: "x-posthog-mcp-consumer", value: "cloud" },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ const [broadcast] = testServer.eventStreamSender.enqueue.mock.calls[0];
+ const serialized = JSON.stringify(broadcast);
+ expect(serialized).not.toContain("mcp-secret");
+ expect(serialized).toContain("x-posthog-mcp-consumer");
+ expect(testServer.pendingEvents).toEqual([broadcast]);
+ });
});
describe("relayed MCP server tool permissions", () => {
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 0242f00308a1..96de00f64be0 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -124,10 +124,7 @@ import { createEventIdSource } from "../utils/event-id";
import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";
import { resolveGithubToken } from "../utils/github-token";
import { Logger } from "../utils/logger";
-import {
- ClaudeTokenEventRedactor,
- redactClaudeTokens,
-} from "../utils/redact-claude-tokens";
+import { redactSecrets, SecretEventRedactor } from "../utils/redact-secrets";
import { logAgentshRuntimeInfo } from "./agentsh-runtime";
import { AgentBootTracker } from "./boot-phases";
import {
@@ -517,7 +514,7 @@ export class AgentServer {
private initializingSseController: SseController | null = null;
private initializingTelemetry: OtelRunTelemetry | undefined;
private pendingEvents: Record<string, unknown>[] = [];
- private tokenEventRedactor = new ClaudeTokenEventRedactor();
+ private eventRedactor = new SecretEventRedactor();
/** ACP notifications emitted by newSession/resumeSession before this.session is assigned. */
private preSessionEvents: Record<string, unknown>[] = [];
private deliveredMessageIds = new Set<string>();
@@ -1119,7 +1116,7 @@ export class AgentServer {
async reportFatalError(error: unknown): Promise<void> {
if (error instanceof CredentialRelayError && error.code === "cancelled")
return;
- const errorMessage = redactClaudeTokens(
+ const errorMessage = redactSecrets(
error instanceof CredentialRelayError
? CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE
: error instanceof Error
@@ -4970,7 +4967,7 @@ ${commonInstructions}
errorMessage?: string,
options?: { errorCategory?: AgentErrorClassification },
): Promise<void> {
- errorMessage = redactClaudeTokens(errorMessage);
+ errorMessage = redactSecrets(errorMessage);
const currentSession = this.session;
const sessionMatchesRun = currentSession?.payload.run_id === payload.run_id;
const terminalErrorMessage = errorMessage ?? "Agent error";
@@ -5993,7 +5990,7 @@ ${commonInstructions}
}
private broadcastEvent(event: Record<string, unknown>): void {
- for (const redacted of this.tokenEventRedactor.redact(event)) {
+ for (const redacted of this.eventRedactor.redact(event)) {
this.deliverEvent(redacted);
}
}
diff --git a/products/desktop/packages/agent/src/session-log-writer.ts b/products/desktop/packages/agent/src/session-log-writer.ts
index a5583332dde7..f148ae40c3ac 100644
--- a/products/desktop/packages/agent/src/session-log-writer.ts
+++ b/products/desktop/packages/agent/src/session-log-writer.ts
@@ -6,7 +6,7 @@ import type { PostHogAPIClient } from "./posthog-api";
import type { StoredNotification } from "./types";
import { isEmptyContentBlock } from "./utils/acp-content";
import { Logger } from "./utils/logger";
-import { redactClaudeTokens } from "./utils/redact-claude-tokens";
+import { redactSecrets } from "./utils/redact-secrets";
/**
* Session context for a registered session.
@@ -76,31 +76,6 @@ interface SessionState {
pendingRawInputSnapshots: Map<string, StoredNotification>;
}
-function redactAuthorizationHeaders(value: unknown): unknown {
- if (Array.isArray(value)) {
- return value.map(redactAuthorizationHeaders);
- }
- if (value === null || typeof value !== "object") {
- return redactClaudeTokens(value);
- }
-
- const record = value as Record<string, unknown>;
- if (
- typeof record.name === "string" &&
- record.name.toLowerCase() === "authorization" &&
- "value" in record
- ) {
- return { ...record, value: "[REDACTED]" };
- }
-
- return Object.fromEntries(
- Object.entries(record).map(([key, nestedValue]) => [
- key,
- redactAuthorizationHeaders(nestedValue),
- ]),
- );
-}
-
export class SessionLogWriter {
/**
* When consecutive in-progress tool updates for one call span more than this
@@ -269,7 +244,7 @@ export class SessionLogWriter {
this.emitCoalescedMessage(sessionId, session);
}
- message = redactAuthorizationHeaders(message) as Record<string, unknown>;
+ message = redactSecrets(message) as Record<string, unknown>;
const nonChunkAgentText = this.extractAgentMessageText(message);
if (nonChunkAgentText) {
session.lastAgentMessage = nonChunkAgentText;
@@ -593,7 +568,7 @@ export class SessionLogWriter {
if (!session.chunkBuffer) return;
const { firstTimestamp, firstEventId, lastEventId } = session.chunkBuffer;
- const text = redactClaudeTokens(session.chunkBuffer.text);
+ const text = redactSecrets(session.chunkBuffer.text);
session.chunkBuffer = undefined;
session.lastAgentMessage = text;
session.currentTurnMessages.push(text);
diff --git a/products/desktop/packages/agent/src/utils/logger.ts b/products/desktop/packages/agent/src/utils/logger.ts
index 1c5677813ad0..653eb3091939 100644
--- a/products/desktop/packages/agent/src/utils/logger.ts
+++ b/products/desktop/packages/agent/src/utils/logger.ts
@@ -1,5 +1,5 @@
import type { LogLevel as LogLevelType, OnLogCallback } from "../types";
-import { redactClaudeTokens } from "./redact-claude-tokens";
+import { redactSecrets } from "./redact-secrets";
export interface LoggerConfig {
debug?: boolean;
@@ -37,8 +37,8 @@ export class Logger {
}
private emitLog(level: LogLevelType, message: string, data?: unknown) {
- message = redactClaudeTokens(message) as string;
- data = redactClaudeTokens(data);
+ message = redactSecrets(message) as string;
+ data = redactSecrets(data);
if (this.onLog) {
this.onLog(level, this.scope, message, data);
return;
diff --git a/products/desktop/packages/agent/src/utils/redact-claude-tokens.test.ts b/products/desktop/packages/agent/src/utils/redact-claude-tokens.test.ts
deleted file mode 100644
index fc8fc1b64138..000000000000
--- a/products/desktop/packages/agent/src/utils/redact-claude-tokens.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { ClaudeTokenEventRedactor } from "./redact-claude-tokens";
-
-describe("ClaudeTokenEventRedactor", () => {
- it.each(["agent_message_chunk", "agent_thought_chunk"])(
- "protects tokens at every split in %s and preserves other text",
- (sessionUpdate) => {
- const token = "sk-ant-oat01-fake-test-token";
- for (const text of [
- `Token: ${token}. Next.`,
- `${token} ${token}`,
- "Plain text with s, sk-ant-, and sk-ant-oat01.",
- ]) {
- for (let split = 1; split < text.length; split++) {
- const redactor = new ClaudeTokenEventRedactor();
- const events = [text.slice(0, split), text.slice(split)].flatMap(
- (part) =>
- redactor.redact({
- type: "notification",
- notification: {
- method: "session/update",
- params: {
- update: {
- sessionUpdate,
- content: { type: "text", text: part },
- },
- },
- },
- }),
- );
- events.push(...redactor.redact({ type: "done" }));
- const result = events
- .map((event) => {
- const notification = event.notification as
- | { params: { update: { content: { text: string } } } }
- | undefined;
- return notification?.params.update.content.text ?? "";
- })
- .join("");
- expect(result).toBe(text.replaceAll(token, "[REDACTED]"));
- expect(JSON.stringify(events)).not.toContain("fake-test-token");
- }
- }
- },
- );
-});
diff --git a/products/desktop/packages/agent/src/utils/redact-claude-tokens.ts b/products/desktop/packages/agent/src/utils/redact-claude-tokens.ts
deleted file mode 100644
index 81ba92956afe..000000000000
--- a/products/desktop/packages/agent/src/utils/redact-claude-tokens.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-export function redactClaudeTokens(value: string): string;
-export function redactClaudeTokens(
- value: string | undefined,
-): string | undefined;
-export function redactClaudeTokens(value: unknown): unknown;
-export function redactClaudeTokens(value: unknown): unknown {
- if (typeof value === "string")
- return value.replace(/sk-ant-oat01-[A-Za-z0-9_-]+/g, "[REDACTED]");
- if (Array.isArray(value)) return value.map(redactClaudeTokens);
- if (value instanceof Error)
- return {
- name: value.name,
- message: redactClaudeTokens(value.message),
- stack: redactClaudeTokens(value.stack),
- };
- if (value instanceof Date) return value;
- if (value !== null && typeof value === "object") {
- return Object.fromEntries(
- Object.entries(value).map(([key, nested]) => [
- key,
- redactClaudeTokens(nested),
- ]),
- );
- }
- return value;
-}
-
-type TextEvent = Record<string, unknown> & {
- notification: {
- method: "session/update";
- params: {
- update: {
- sessionUpdate: string;
- content: { type: "text"; text: string };
- };
- };
- };
-};
-
-function isTextChunk(event: Record<string, unknown>): event is TextEvent {
- const notification = event.notification as
- | TextEvent["notification"]
- | undefined;
- const update = notification?.params?.update;
- return (
- notification?.method === "session/update" &&
- (update?.sessionUpdate === "agent_message_chunk" ||
- update?.sessionUpdate === "agent_thought_chunk") &&
- update.content?.type === "text" &&
- typeof update.content.text === "string"
- );
-}
-
-function withText(event: TextEvent, text: string): TextEvent {
- return {
- ...event,
- notification: {
- ...event.notification,
- params: {
- ...event.notification.params,
- update: {
- ...event.notification.params.update,
- content: { ...event.notification.params.update.content, text },
- },
- },
- },
- };
-}
-
-export class ClaudeTokenEventRedactor {
- private pending: TextEvent | null = null;
- private redacting = false;
- private chunkKind: string | null = null;
-
- redact(event: Record<string, unknown>): Record<string, unknown>[] {
- const events: Record<string, unknown>[] = [];
- const chunk = isTextChunk(event);
- const kind = chunk ? event.notification.params.update.sessionUpdate : null;
- if (!chunk || kind !== this.chunkKind) {
- if (this.pending) events.push(this.pending);
- this.pending = null;
- this.redacting = false;
- }
- this.chunkKind = kind;
- if (!chunk) {
- events.push(redactClaudeTokens(event) as Record<string, unknown>);
- return events;
- }
- const previous = this.pending;
- let text =
- (previous?.notification.params.update.content.text ?? "") +
- event.notification.params.update.content.text;
- this.pending = null;
- if (this.redacting) {
- text = text.replace(/^[A-Za-z0-9_-]+/, "");
- if (text.length > 0) this.redacting = false;
- }
- const prefix = "sk-ant-oat01-";
- text = text.replace(
- /sk-ant-oat01-[A-Za-z0-9_-]*/g,
- (match, offset: number, source: string) => {
- this.redacting = offset + match.length === source.length;
- return "[REDACTED]";
- },
- );
- const redacted = redactClaudeTokens(withText(event, text)) as TextEvent;
- if (!this.redacting) {
- for (let length = prefix.length - 1; length > 0; length--) {
- if (text.endsWith(prefix.slice(0, length))) {
- if (previous) {
- events.push(withText(previous, text.slice(0, -length)));
- this.pending = withText(redacted, text.slice(-length));
- } else {
- this.pending = redacted;
- }
- return events;
- }
- }
- }
- events.push(redacted);
- return events;
- }
-}
diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
new file mode 100644
index 000000000000..a9c1758776d9
--- /dev/null
+++ b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+import { redactSecrets, SecretEventRedactor } from "./redact-secrets";
+import { SECRET_HEADERS, TOKEN_RULES } from "./secret-rules";
+
+const CHUNK_KINDS = ["agent_message_chunk", "agent_thought_chunk"];
+
+const chunkCases: [string, string, string, string][] = TOKEN_RULES.flatMap(
+ (rule) =>
+ CHUNK_KINDS.map((sessionUpdate): [string, string, string, string] => [
+ rule.label,
+ sessionUpdate,
+ `${rule.prefix}aaaa1111`,
+ rule.prefix,
+ ]),
+);
+
+const headerCases: [
+ string,
+ Record<string, unknown>,
+ Record<string, unknown>,
+][] = SECRET_HEADERS.flatMap((header) => [
+ [
+ `${header} name/value pair`,
+ {
+ headers: [
+ { name: header, value: "Bearer leaked-value" },
+ { name: "x-posthog-mcp-consumer", value: "cloud" },
+ ],
+ },
+ {
+ headers: [
+ { name: header, value: "[REDACTED]" },
+ { name: "x-posthog-mcp-consumer", value: "cloud" },
+ ],
+ },
+ ],
+ [
+ `${header} map entry`,
+ { headers: { [header]: "Bearer leaked-value", "x-id": "123" } },
+ { headers: { [header]: "[REDACTED]", "x-id": "123" } },
+ ],
+]);
+
+describe("redactSecrets", () => {
+ it.each(chunkCases)(
+ "protects a %s at every split in %s",
+ (_label, sessionUpdate, token, prefix) => {
+ for (const text of [
+ `Token: ${token}. Next.`,
+ `${token} ${token}`,
+ `Plain text with ${prefix.slice(0, 1)}, and ${prefix.slice(0, -1)}.`,
+ ]) {
+ for (let split = 1; split < text.length; split++) {
+ const redactor = new SecretEventRedactor();
+ const events = [text.slice(0, split), text.slice(split)].flatMap(
+ (part) =>
+ redactor.redact({
+ type: "notification",
+ notification: {
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate,
+ content: { type: "text", text: part },
+ },
+ },
+ },
+ }),
+ );
+ events.push(...redactor.redact({ type: "done" }));
+ const result = events
+ .map((event) => {
+ const notification = event.notification as
+ | { params: { update: { content: { text: string } } } }
+ | undefined;
+ return notification?.params.update.content.text ?? "";
+ })
+ .join("");
+ expect(result).toBe(text.replaceAll(token, "[REDACTED]"));
+ expect(JSON.stringify(events)).not.toContain("aaaa1111");
+ }
+ }
+ },
+ );
+
+ it.each(headerCases)("redacts a %s", (_shape, server, expected) => {
+ expect(
+ redactSecrets({
+ method: "session/new",
+ params: { mcpServers: [server] },
+ }),
+ ).toEqual({ method: "session/new", params: { mcpServers: [expected] } });
+ });
+});
diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.ts b/products/desktop/packages/agent/src/utils/redact-secrets.ts
new file mode 100644
index 000000000000..a70b4008b3ff
--- /dev/null
+++ b/products/desktop/packages/agent/src/utils/redact-secrets.ts
@@ -0,0 +1,176 @@
+import { SECRET_HEADERS, TOKEN_RULES, type TokenRule } from "./secret-rules";
+
+const REDACTED = "[REDACTED]";
+
+interface CompiledRule {
+ head: RegExp;
+ tail: RegExp;
+}
+
+function escapeLiteral(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function tokenSource(rule: TokenRule, repeat: "+" | "*"): string {
+ return `${escapeLiteral(rule.prefix)}${rule.body.source}${repeat}`;
+}
+
+const RULES: CompiledRule[] = TOKEN_RULES.map((rule) => ({
+ head: new RegExp(tokenSource(rule, "*"), "g"),
+ tail: new RegExp(`^${rule.body.source}+`),
+}));
+
+const TOKEN = new RegExp(
+ TOKEN_RULES.map((rule) => tokenSource(rule, "+")).join("|"),
+ "g",
+);
+
+const PARTIAL_PREFIXES = [
+ ...new Set(
+ TOKEN_RULES.flatMap((rule) =>
+ Array.from({ length: rule.prefix.length - 1 }, (_, index) =>
+ rule.prefix.slice(0, index + 1),
+ ),
+ ),
+ ),
+].sort((left, right) => right.length - left.length);
+
+const SECRET_HEADER_NAMES = new Set(SECRET_HEADERS);
+
+function isSecretHeader(name: unknown): boolean {
+ return (
+ typeof name === "string" && SECRET_HEADER_NAMES.has(name.toLowerCase())
+ );
+}
+
+function partialPrefixLength(text: string): number {
+ for (const prefix of PARTIAL_PREFIXES) {
+ if (text.endsWith(prefix)) return prefix.length;
+ }
+ return 0;
+}
+
+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, REDACTED);
+ if (Array.isArray(value)) return value.map(redactSecrets);
+ if (value instanceof Error)
+ return {
+ name: value.name,
+ message: redactSecrets(value.message),
+ stack: redactSecrets(value.stack),
+ };
+ if (value instanceof Date) return value;
+ if (value === null || typeof value !== "object") return value;
+
+ const record = value as Record<string, unknown>;
+ if (isSecretHeader(record.name) && "value" in record) {
+ return { ...record, value: REDACTED };
+ }
+
+ return Object.fromEntries(
+ Object.entries(record).map(([key, nested]) => [
+ key,
+ isSecretHeader(key) && typeof nested === "string"
+ ? REDACTED
+ : redactSecrets(nested),
+ ]),
+ );
+}
+
+type TextEvent = Record<string, unknown> & {
+ notification: {
+ method: "session/update";
+ params: {
+ update: {
+ sessionUpdate: string;
+ content: { type: "text"; text: string };
+ };
+ };
+ };
+};
+
+function isTextChunk(event: Record<string, unknown>): event is TextEvent {
+ const notification = event.notification as
+ | TextEvent["notification"]
+ | undefined;
+ const update = notification?.params?.update;
+ return (
+ notification?.method === "session/update" &&
+ (update?.sessionUpdate === "agent_message_chunk" ||
+ update?.sessionUpdate === "agent_thought_chunk") &&
+ update.content?.type === "text" &&
+ typeof update.content.text === "string"
+ );
+}
+
+function withText(event: TextEvent, text: string): TextEvent {
+ return {
+ ...event,
+ notification: {
+ ...event.notification,
+ params: {
+ ...event.notification.params,
+ update: {
+ ...event.notification.params.update,
+ content: { ...event.notification.params.update.content, text },
+ },
+ },
+ },
+ };
+}
+
+export class SecretEventRedactor {
+ private pending: TextEvent | null = null;
+ private active: CompiledRule | null = null;
+ private chunkKind: string | null = null;
+
+ redact(event: Record<string, unknown>): Record<string, unknown>[] {
+ const events: Record<string, unknown>[] = [];
+ const chunk = isTextChunk(event);
+ const kind = chunk ? event.notification.params.update.sessionUpdate : null;
+ if (!chunk || kind !== this.chunkKind) {
+ if (this.pending) events.push(this.pending);
+ this.pending = null;
+ this.active = null;
+ }
+ this.chunkKind = kind;
+ if (!chunk) {
+ events.push(redactSecrets(event) as Record<string, unknown>);
+ return events;
+ }
+ const previous = this.pending;
+ let text =
+ (previous?.notification.params.update.content.text ?? "") +
+ event.notification.params.update.content.text;
+ this.pending = null;
+ if (this.active) {
+ text = text.replace(this.active.tail, "");
+ if (text.length > 0) this.active = null;
+ }
+ for (const rule of RULES) {
+ text = text.replace(
+ rule.head,
+ (match, offset: number, source: string) => {
+ if (offset + match.length === source.length) this.active = rule;
+ return REDACTED;
+ },
+ );
+ }
+ const redacted = redactSecrets(withText(event, text)) as TextEvent;
+ const held = this.active ? 0 : partialPrefixLength(text);
+ if (held > 0) {
+ if (previous) {
+ events.push(withText(previous, text.slice(0, -held)));
+ this.pending = withText(redacted, text.slice(-held));
+ } else {
+ this.pending = redacted;
+ }
+ return events;
+ }
+ events.push(redacted);
+ return events;
+ }
+}
diff --git a/products/desktop/packages/agent/src/utils/secret-rules.ts b/products/desktop/packages/agent/src/utils/secret-rules.ts
new file mode 100644
index 000000000000..9794f5b5ce38
--- /dev/null
+++ b/products/desktop/packages/agent/src/utils/secret-rules.ts
@@ -0,0 +1,46 @@
+export interface TokenRule {
+ label: string;
+ prefix: string;
+ body: RegExp;
+}
+
+const URL_SAFE_BODY = /[A-Za-z0-9_-]/;
+
+export const TOKEN_RULES: TokenRule[] = [
+ {
+ label: "claude oauth token",
+ prefix: "sk-ant-oat01-",
+ body: URL_SAFE_BODY,
+ },
+ {
+ label: "anthropic api key",
+ prefix: "sk-ant-api",
+ body: URL_SAFE_BODY,
+ },
+ {
+ label: "github installation token",
+ prefix: "ghs_",
+ body: URL_SAFE_BODY,
+ },
+ {
+ label: "github personal access token",
+ prefix: "ghp_",
+ body: URL_SAFE_BODY,
+ },
+ {
+ label: "github fine-grained token",
+ prefix: "github_pat_",
+ body: URL_SAFE_BODY,
+ },
+ {
+ label: "posthog personal api key",
+ prefix: "phx_",
+ body: URL_SAFE_BODY,
+ },
+];
+
+export const SECRET_HEADERS: string[] = [
+ "authorization",
+ "proxy-authorization",
+ "x-api-key",
+];