Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(logging): redact registered signing values in every log sink
Jack Rudenko3ea38dae2624
diff --git a/packages/cli/src/logger.ts b/packages/cli/src/logger.tsindex 5895188e..29fe4a51 100644--- a/packages/cli/src/logger.ts+++ b/packages/cli/src/logger.ts@@ -2,6 +2,7 @@ import { appendFile, existsSync, mkdirSync, readdirSync, unlinkSync, writeFileSyimport { homedir } from "node:os";import { join } from "node:path";import type { DiagOutput } from "./diag-output.js";+import { redactSigningValues } from "./redact.js";let logFilePath: string | null = null;let logLevel: "debug" | "info" | "minimal" = "info"; // Default to structured logging@@ -273,7 +274,12 @@ export function initLogger(* Log a message (to file only in debug mode, silent otherwise)* Uses async buffered writes to avoid blocking event loop*/-export function log(message: string, forceConsole = false): void {+export function log(rawMessage: string, forceConsole = false): void {+ // Before any buffer, file or console write: `log` is the only writer of the+ // debug file and of the always-on log, so this one pass covers every line+ // either receives (an echoed credential in a queue 429, a parser frame, an+ // auth exception). A no-op when no request holds a signing value.+ const message = redactSigningValues(rawMessage);const timestamp = new Date().toISOString();const logLine = `[${timestamp}] ${message}\n`;@@ -309,7 +315,9 @@ export function log(message: string, forceConsole = false): void {* to avoid corrupting Claude Code's TUI display.* When a DiagOutput is set, stderr messages are routed there instead.*/-export function logStderr(message: string): void {+export function logStderr(rawMessage: string): void {+ // Same pass as `log`, before stderr or DiagOutput sees the line.+ const message = redactSigningValues(rawMessage);if (diagOutput) {// Route to DiagOutput (log file) instead of polluting stderrdiagOutput.write(message);diff --git a/packages/cli/src/redact.ts b/packages/cli/src/redact.tsindex 3aada11d..e31ef1cf 100644--- a/packages/cli/src/redact.ts+++ b/packages/cli/src/redact.ts@@ -84,6 +84,128 @@ const TOKEN_PATTERNS: Array<{ name: string; re: RegExp }> = [{ name: "bearer", re: /\b(?:Bearer|Basic|Token)\s+[A-Za-z0-9_.\-+/=]{12,}/g },];+// ─── Signing-value registry ──────────────────────────────────────────────────+//+// Shape rules (below) catch a credential by what it LOOKS like. A provider's+// opaque token, a Devin body credential or an OAuth access token has no shape+// to match, and an upstream error that echoes it back would reach the debug+// log, the always-on log, stderr and the error capture verbatim. The registry+// catches those by exact VALUE instead: every request registers the values it+// signs with, and every sink that redacts reads the union of the values of all+// requests in flight.+//+// Process-wide on purpose, not per request: a provider queue's loop runs in the+// async context of whichever request started it, so a line it logs for request+// B would be checked against request A's scope. Redacting B's line against A's+// values as well is harmless.+//+// A lease lives exactly as long as the work it protects: the holder releases it+// when that work has ended (a response body fully read, cancelled or errored).+// There is deliberately NO timer here. A fixed TTL can expire while a stream is+// still producing frames, and a later frame echoing the credential would then+// be logged in the clear. A lease nobody releases costs retained strings and+// extra redaction, never exposure.++/** What a registered signing value is replaced with. */+const SIGNING_MASK = "[redacted]";++/** Shorter values are ignored: they would mask ordinary words. */+const SIGNING_VALUE_MIN_LENGTH = 8;++/** Every live form of every live value -> how many leases hold it. */+const liveSigningValues = new Map<string, number>();++/** Live forms, longest first; rebuilt lazily after any change. */+let sortedSigningValues: string[] | null = null;++/** A set of signing values held for the duration of one piece of work. */+export interface SigningLease {+ /** Register values; ignored once released, and below the minimum length. */+ add(values: Iterable<string>): void;+ /** Drop this lease's hold on every value it added. Idempotent. */+ release(): void;+ /** True once `release()` has run. */+ readonly released: boolean;+}++/**+ * The forms one value can take in text a sink receives: verbatim, JSON-escaped+ * (an error body quoting it inside a JSON string), JSON-escaped twice (that body+ * embedded in another JSON string, as a log of a JSON envelope does), and+ * URL-encoded (a query parameter echoed back). Escaping only adds characters,+ * so a form differs from the value only when the value needs escaping.+ */+function signingValueForms(value: string): string[] {+ const forms = new Set<string>([value]);+ let escaped = value;+ for (let depth = 0; depth < 2; depth++) {+ escaped = JSON.stringify(escaped).slice(1, -1);+ forms.add(escaped);+ }+ try {+ forms.add(encodeURIComponent(value));+ } catch {+ // A lone surrogate cannot be URL-encoded; the other forms still apply.+ }+ return [...forms];+}++/** Hold every form of `value` for one lease: counted once per lease, not per call. */+function holdSigningValue(held: Set<string>, value: unknown): void {+ if (typeof value !== "string" || value.length < SIGNING_VALUE_MIN_LENGTH) return;+ for (const form of signingValueForms(value)) {+ if (held.has(form)) continue;+ held.add(form);+ liveSigningValues.set(form, (liveSigningValues.get(form) ?? 0) + 1);+ sortedSigningValues = null;+ }+}++/** Acquire a lease. The holder must call `release()` when its work has ended. */+export function acquireSigningLease(): SigningLease {+ const held = new Set<string>();+ let released = false;+ return {+ add(values: Iterable<string>): void {+ if (released) return;+ for (const value of values) holdSigningValue(held, value);+ },+ release(): void {+ if (released) return;+ released = true;+ for (const form of held) {+ const count = (liveSigningValues.get(form) ?? 0) - 1;+ if (count > 0) liveSigningValues.set(form, count);+ else liveSigningValues.delete(form);+ }+ held.clear();+ sortedSigningValues = null;+ },+ get released(): boolean {+ return released;+ },+ };+}++/**+ * Replace every live signing value in `text` with `[redacted]`, longest first.+ * Returns `text` untouched when no request holds a value (the common case).+ * Exact substring matching, no regular expression: a value is data, not a+ * pattern, and a shared global regex would carry `lastIndex` between calls.+ * Replacements only shorten, so JSON stays JSON.+ */+export function redactSigningValues(text: string): string {+ if (liveSigningValues.size === 0 || !text) return text;+ if (!sortedSigningValues) {+ sortedSigningValues = [...liveSigningValues.keys()].sort((a, b) => b.length - a.length);+ }+ let out = text;+ for (const value of sortedSigningValues) {+ if (out.includes(value)) out = out.split(value).join(SIGNING_MASK);+ }+ return out;+}+/*** Strip credentials from text. Safe to run on anything; never throws.*@@ -93,7 +215,9 @@ const TOKEN_PATTERNS: Array<{ name: string; re: RegExp }> = [*/export function redactSecrets(text: string | undefined | null): string {if (!text) return "";- let out = text;+ // Exact values first: a registered opaque token has no shape the rules below+ // could match.+ let out = redactSigningValues(text);// Named assignments first, so `FOO_API_KEY=sk-abc…` is masked once as a whole// rather than leaving a dangling `FOO_API_KEY=` next to a separate mask.