commit e1894fc174de1e4decc9bd7f1c5231b3bde16e5e
parent bba16c629dfb6e8c9ba5007a11f07a1f02af7851
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 00:39:33 -0500
common: the model log scrubs a credential by its shape, whoever's it is -- a URL's user:password, a query parameter named like a token (and a signed URL's ip), a Bearer value, a Cookie line, the platforms' login cookies, keys that say what they are
The record was scrubbed of the secrets this process holds, by value. A
transcript, a tool result or an error can carry one it never held (a signed
media URL, a pasted header, a cookie jar's line): scrubText now takes those by
shape, keeping the name and replacing the value. Three more holes closed:
what code says about an answer (a decision's why, an item's text) goes through
the call's own redaction, so an API key read from a key file is out of it as
it is out of the call; a failed call's error loses addresses (an IP and port)
and URLs of any scheme; and a variable named ...COOKIE or ...AUTH counts as a
credential. Tests for each; words a transcript says and public links are left
as they are.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
4 files changed, 109 insertions(+), 11 deletions(-)
diff --git a/common/lib/llm/callLog-server.ts b/common/lib/llm/callLog-server.ts
@@ -88,9 +88,10 @@ const compactJson = (v: unknown) => {
// The secrets and roots every record of this process is scrubbed of: the
// editor's WORKER_TOKEN, an API key and every other variable of the
-// environment named like a credential (…TOKEN, …KEY, …SECRET, …PASSWORD), the
+// environment named like a credential (…TOKEN, …KEY, …SECRET, …PASSWORD,
+// …COOKIE, …AUTH), the
// home directory, the checkout.
-const SECRET_ENV_NAME = /(?:^|_)(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?)$/i;
+const SECRET_ENV_NAME = /(?:^|_)(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|COOKIES?|AUTH)$/i;
export function processScrub(extraRoots: readonly string[] = []): Scrub {
const env = process.env;
// A credential by its name only when it reads like one (16 characters, no
@@ -108,8 +109,10 @@ export function processScrub(extraRoots: readonly string[] = []): Scrub {
// A failed call's message may name the host it was sent to (ollama's base
// URL): an error keeps its words, never an address.
-const URL_IN_ERROR = /\bhttps?:\/\/[^\s"'`<>()]+/g;
-const scrubErrorUrls = (s: string) => s.replace(URL_IN_ERROR, "<url>");
+const URL_IN_ERROR = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>()]+/gi;
+// … nor the address a connection was refused at (ECONNREFUSED 10.0.0.5:11434).
+const ADDRESS_IN_ERROR = /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b|\[[0-9a-f:]*:[0-9a-f:]+\](?::\d+)?|(?<![0-9a-f:])::1(?::\d+)?\b/gi;
+const scrubErrorUrls = (s: string) => s.replace(URL_IN_ERROR, "<url>").replace(ADDRESS_IN_ERROR, "<host>");
export type ModelCallEntry = {
phase?: string;
@@ -136,9 +139,13 @@ export type ModelCallEntry = {
export class CallSlot {
#writer: ModelLogWriter | null = null;
#id: Promise<string | null> | null = null;
- bind(writer: ModelLogWriter, id: Promise<string | null>): void {
+ // The call's own redaction (the API client's key): what code says about the
+ // answer afterwards is scrubbed of it as the call was.
+ #redact: ((s: string) => string) | undefined;
+ bind(writer: ModelLogWriter, id: Promise<string | null>, redact?: (s: string) => string): void {
this.#writer = writer;
this.#id = id;
+ this.#redact = redact;
}
get recorded(): boolean {
return !!this.#writer;
@@ -147,11 +154,11 @@ export class CallSlot {
// they add up to.
decide(outcome: CallOutcome, why: string, items?: CallItem[]): void {
if (!this.#writer || !this.#id) return;
- this.#writer.decide(this.#id, { outcome, why }, items);
+ this.#writer.decide(this.#id, { outcome, why }, items, this.#redact);
}
items(items: CallItem[]): void {
if (!this.#writer || !this.#id || !items.length) return;
- this.#writer.decide(this.#id, null, items);
+ this.#writer.decide(this.#id, null, items, this.#redact);
}
}
@@ -282,12 +289,12 @@ export class ModelLogWriter {
});
}
- decide(id: Promise<string | null>, decision: CallDecision | null, items?: CallItem[]): void {
+ decide(id: Promise<string | null>, decision: CallDecision | null, items?: CallItem[], redact?: (s: string) => string): void {
const at = this.now().toISOString();
void this.queue(async () => {
const call = await id;
if (!call) return;
- const clean = (s: string) => scrubText(s, this.scrub);
+ const clean = (s: string) => scrubText(redact ? redact(s) : s, this.scrub);
const b = boundItems(items?.map((i) => ({ ...i, text: clean(i.text), why: clean(i.why) })));
const row: ModelDecisionRow = {
v: MODEL_LOG_VERSION,
@@ -363,7 +370,7 @@ export function recordModelCall(e: ModelCallEntry, slot?: CallSlot): void {
}
try {
const id = w.record(e);
- slot?.bind(w, id);
+ slot?.bind(w, id, e.redact);
} catch {
// a record never stops the run
}
diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts
@@ -273,3 +273,35 @@ test("terminalSafeJson: printed JSON carries no DEL, C1 or bidi control, and par
assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202e]/.test(out), out);
assert.deepEqual(JSON.parse(out), v);
});
+
+test("what code says about an answer is scrubbed as the call was: the call's own redaction covers its decision and items", async () => {
+ const t = await tmpLog();
+ try {
+ const KEY = "file-held-key-0123456789";
+ const slot = new CallSlot();
+ await runWithModelLog(t.writer, async () => {
+ recordModelCall({ model: "claude-haiku-4-5", route: "api", prompt: "p", answer: "a", seconds: 1, redact: (s) => s.split(KEY).join("[redacted]") }, slot);
+ slot.decide("dropped", `refused: echoed ${KEY}`, [{ text: `op ${KEY}`, outcome: "dropped", why: `why ${KEY}` }]);
+ });
+ await t.writer.flush();
+ const raw = await readFile(t.files.calls, "utf8");
+ assert.ok(!raw.includes(KEY), raw);
+ assert.match(raw, /refused: echoed \[redacted\]/);
+ } finally {
+ await t.done();
+ }
+});
+
+test("a failed call's error names no address: an IP and port, and a URL of any scheme, are taken out", async () => {
+ const t = await tmpLog();
+ try {
+ await runWithModelLog(t.writer, async () => {
+ recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: null, seconds: 1, error: "connect ECONNREFUSED 192.168.1.44:11434 (also [fe80::1]:11434, ::1:11434, ws://gpu.lan:8080/x) after 3 tries" });
+ });
+ await t.writer.flush();
+ const [c] = (await readModelLog(t.files)).calls;
+ assert.equal(c!.error, "connect ECONNREFUSED <host> (also <host>, <host>, <url>) after 3 tries");
+ } finally {
+ await t.done();
+ }
+});
diff --git a/common/lib/llm/callLog.ts b/common/lib/llm/callLog.ts
@@ -29,7 +29,10 @@
// else (no header, no key, no URL of the model's host); every text is scrubbed
// of the run's secrets (the API key, the editor's WORKER_TOKEN, every variable
// of the environment named like a credential) and of host paths before it is
-// written (`scrubText`); a failed call's message is scrubbed of URLs too.
+// written (`scrubText`) — and of anything shaped like a credential, whoever's
+// it is: a URL's user:password, a query parameter named like a token (and a
+// signed URL's `ip`), a Bearer value, a Cookie line, a key that says what it
+// is. A failed call's message is scrubbed of URLs and addresses too.
//
// A reader skips a line that does not parse and a row of an unknown version;
// a later version adds fields, never renames one.
@@ -121,11 +124,36 @@ const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// A home directory on any of the usual systems, even when it is not ours.
const HOME_PATH = /(?:\/home\/|\/Users\/|\/root\/|\/run\/media\/|\/mnt\/|\/media\/)[^\s"'`<>()[\]{},;]*/g;
+// A credential by its SHAPE, whoever's it is: a transcript, a tool result or
+// an error can carry one this process never held (a signed media URL, a pasted
+// header, a cookie line). Each keeps its name and loses its value.
+const CREDENTIAL_PARAM = "(?:[\\w.-]*[_.-])?(?:access|api|auth|session)?_?(?:token|key|secret|password|passwd|pwd|signature|sig|lsig|auth|session|sessionid|sid|clearance|cookie|credentials?)";
+const CREDENTIAL_SHAPES: readonly (readonly [RegExp, string])[] = [
+ // user:password@ in a URL
+ [/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:"'<>]*:[^\s/@"'<>]+@/gi, "$1[secret]@"],
+ // a query parameter named like a credential — and `ip`, the fetcher's public
+ // address in a signed media URL
+ [new RegExp(`([?&;](?:${CREDENTIAL_PARAM}|ip|ipbits))=[^&\\s"'\`<>#;)\\]}]+`, "gi"), "$1=[secret]"],
+ // an Authorization value, a Cookie line, a key header
+ [/\b(Bearer|Basic)[ \t]+[A-Za-z0-9._~+/=-]{16,}/g, "$1 [secret]"],
+ [/\b((?:set-)?cookie[ \t]*:[ \t]*)[^\s=;:]+=[^\n]*/gi, "$1[secret]"],
+ [/\b((?:x-api-key|api[-_]?key|authorization|proxy-authorization)[ \t]*[:=][ \t]*)["']?[A-Za-z0-9._~+/-]{16,}["']?/gi, "$1[secret]"],
+ // the login cookies of the platforms this archive fetches, wherever they are quoted
+ [/\b(auth_token|ct0|cf_clearance|sessionid|SAPISID|__Secure-[\w-]+)=[^;\s"'&]+/g, "$1=[secret]"],
+ // keys that say what they are
+ [/\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}/g, "[secret]"],
+ [/\bgh[pousr]_[A-Za-z0-9]{30,}/g, "[secret]"],
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "[secret]"],
+ [/\bAKIA[0-9A-Z]{16}\b/g, "[secret]"],
+ [/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, "[secret]"],
+];
+
export function scrubText(text: string, s: Scrub = {}): string {
let out = text;
for (const secret of s.secrets ?? []) {
if (secret && secret.length >= 8) out = out.split(secret).join("[secret]");
}
+ for (const [re, to] of CREDENTIAL_SHAPES) out = out.replace(re, to);
const roots = [...new Set((s.roots ?? []).filter((r) => r && r.length > 1 && r.startsWith("/")).map((r) => r.replace(/\/+$/, "")))].sort((a, b) => b.length - a.length);
for (const r of roots) out = out.replace(new RegExp(`${escapeRe(r)}(?:/[^\\s"'\`<>()[\\]{},;]*)?`, "g"), "<path>");
return out.replace(HOME_PATH, "<path>");
diff --git a/common/lib/llm/callLogPrivacy.test.ts b/common/lib/llm/callLogPrivacy.test.ts
@@ -107,3 +107,34 @@ test("scrubText: secrets and roots out, words of a transcript untouched", () =>
assert.equal(scrubText("the 5/10 split and and/or rules", s), "the 5/10 split and and/or rules");
assert.equal(scrubText("files in /home/ann/.config/x", {}), "files in <path>");
});
+
+test("scrubText: a credential by its shape, whoever's it is -- the name stays, the value goes", () => {
+ const cases: [string, string, string[]][] = [
+ ["fetch https://user:hunter2hunter2@ollama.lan:11434/api/chat now", "fetch https://[secret]@ollama.lan:11434/api/chat now", ["hunter2"]],
+ [
+ "https://rr3.googlevideo.com/videoplayback?expire=1794&ei=abc&ip=203.0.113.77&id=o-AB&sig=AOq0QJ8wRgIhAJ&lsig=ZZtop99 end",
+ "https://rr3.googlevideo.com/videoplayback?expire=1794&ei=abc&ip=[secret]&id=o-AB&sig=[secret]&lsig=[secret] end",
+ ["203.0.113.77", "AOq0QJ8wRgIhAJ", "ZZtop99"],
+ ],
+ ["GET /clip?v=dQw4w9WgXcQ&t=42&access_token=abc123def456&api_key=k-998877&X-Amz-Signature=deadbeef", "GET /clip?v=dQw4w9WgXcQ&t=42&access_token=[secret]&api_key=[secret]&X-Amz-Signature=[secret]", ["abc123def456", "k-998877", "deadbeef"]],
+ ["Authorization: Bearer abcdefghijklmnop0123456789", "Authorization: Bearer [secret]", ["abcdefghijklmnop"]],
+ ["Cookie: auth_token=aaaabbbbccccdddd; ct0=eeeeffff0000\nnext line stays", "Cookie: [secret]\nnext line stays", ["aaaabbbbccccdddd", "eeeeffff0000"]],
+ ["the jar had cf_clearance=Zx9.yQ-77_abc and ct0=0f0f0f0f in it", "the jar had cf_clearance=[secret] and ct0=[secret] in it", ["Zx9.yQ-77_abc", "0f0f0f0f"]],
+ ["x-api-key: FAKE-TEST-VALUE", "x-api-key: [secret]", ["FAKE-TEST-VALUE"]],
+ ["key sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv and ghp_FAKE-TEST-VALUEghijklmnopqrstuvwxyz", "key [secret] and [secret]", ["AbCdEfGh", "ghp_0123"]],
+ ["jwt FAKE-TEST-VALUE", "jwt [secret]", ["eyJhbGci", "dBjftJeZ"]],
+ ];
+ for (const [text, want, gone] of cases) {
+ const out = scrubText(text, {});
+ assert.equal(out, want);
+ for (const g of gone) assert.ok(!out.includes(g), `${g} in ${out}`);
+ }
+ // Words a transcript says, and a public link, are left as they are.
+ for (const plain of [
+ "the key to the token economy is a secret; password: none, she said",
+ "watch https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=42s and https://x.com/a/status/1?s=20",
+ "cookie: chocolate chip. Basic income, bearer of bad news; the monkey=banana joke",
+ "[12:04] my ip is whatever, the signature move",
+ ])
+ assert.equal(scrubText(plain, {}), plain);
+});