import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, toolUseBlock, turn, type FakeAnthropic } from "../../testing/llm/fakeAnthropic.mjs"; import { jsonReply, reply, startFakeOllama, type FakeOllama } from "../../testing/llm/fakeOllama.mjs"; import { runAgent } from "./agent"; import { SCRUB_MARGIN_CHARS, scrubBounded, scrubText } from "./callLog"; import { ModelLogWriter, modelLogFilesIn, recordSessionAnswer, runWithModelLog } from "./callLog-server"; import { Meter } from "./meter"; import { structuredAnswer } from "./structured"; import { plainAnswer } from "../report/draft/tasks/llmText"; // Run with: pnpm -C common exec tsx --test lib/llm/callLogPrivacy.test.ts // // THE MODEL LOG KEEPS THE TEXT SENT TO THE MODEL, AND NOTHING ELSE (demo epic // D3, item 4): on every route a record holds no API key, no WORKER_TOKEN, no // Authorization header's secret and no host path — even when the prompt // itself carries them (a transcript can say anything). The secrets below are // recognisable and injected into each prompt and answer to prove it. const TOKEN = "worker-token-0000-TEST-never-real"; const HOST_PATH = path.join(os.homedir(), "Projects", "yt-dlp-transcript-browser", "transcripts", "reports", "a", "iteration.json"); const POISON = `see ${HOST_PATH} and /home/someone/secret/file.txt; Authorization: Bearer ${TOKEN}; x-api-key: ${FAKE_KEY}`; const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } } }, required: ["terms"] }; let ol: FakeOllama; let api: FakeAnthropic; let saved: string | undefined; before(async () => { saved = process.env.WORKER_TOKEN; process.env.WORKER_TOKEN = TOKEN; ol = await startFakeOllama({ turns: [jsonReply({ terms: [POISON] }), reply(POISON), reply("done")] }); api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: [POISON] })]), textTurn(POISON), toolTurn("lookup", { q: POISON }), textTurn(`read: ${POISON}`)], }); }); after(async () => { if (saved === undefined) delete process.env.WORKER_TOKEN; else process.env.WORKER_TOKEN = saved; await ol.close(); await api.close(); }); function assertClean(text: string, where: string) { assert.ok(text.length > 0, `${where}: something was recorded`); assert.ok(!text.includes(FAKE_KEY), `${where}: the API key`); assert.ok(!text.includes(FAKE_KEY.slice(0, 16)), `${where}: a run of the API key`); assert.ok(!text.includes(TOKEN), `${where}: the WORKER_TOKEN`); assert.ok(!text.includes(os.homedir()), `${where}: the home directory`); assert.ok(!text.includes("/home/someone"), `${where}: a host path`); assert.ok(!text.includes(api.url) && !text.includes(ol.url), `${where}: the model host's URL`); } test("every route's record holds no key, no WORKER_TOKEN and no host path", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-privacy-")); try { // An API config whose key is the fake's, read from the config's own env // (never process.env): the client's redaction is what keeps it out. const llm = { ollama: { baseUrl: ol.url }, anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY } } }; const meter = new Meter(); const routes: [string, () => Promise][] = [ ["local structured", () => structuredAnswer({ llm, model: "qwen3:8b", system: `System ${POISON}`, user: `User ${POISON}`, schema, meter })], ["local extractor", () => plainAnswer({ llm, model: "qwen3:8b", system: "S", user: POISON, meter })], ["local agent", () => runAgent({ llm, model: "qwen3:8b", system: POISON, user: POISON, meter, tools: [] })], ["api structured", () => structuredAnswer({ llm, model: "claude-haiku-4-5", system: POISON, user: POISON, schema, meter })], ["api extractor", () => plainAnswer({ llm, model: "claude-haiku-4-5", system: "S", user: POISON, meter })], [ "api agent", () => runAgent({ llm, model: "claude-haiku-4-5", system: POISON, user: POISON, meter, tools: [{ name: "lookup", description: "look", inputSchema: { type: "object", properties: { q: { type: "string" } } }, run: async () => `result ${POISON}` }], }), ], ["claude-code", async () => recordSessionAnswer({ system: POISON, prompt: POISON, answer: { ops: [POISON] }, llm })], ]; for (const [name, call] of routes) { const files = modelLogFilesIn(path.join(dir, name.replace(/\s+/g, "-"))); // The process's scrub (WORKER_TOKEN from the environment, the home // directory, the checkout), as every run's writer has it. const w = new ModelLogWriter({ files, task: "sweep" }); await runWithModelLog(w, call); await w.flush(); assertClean(await readFile(files.calls, "utf8"), `${name}: calls.jsonl`); assertClean(await readFile(files.text, "utf8"), `${name}: calls-text.jsonl`); // What was scrubbed is said, never dropped silently. assert.match(await readFile(files.text, "utf8"), /\[secret\]|\[redacted\]/, `${name}: the secret is marked`); assert.match(await readFile(files.text, "utf8"), //, `${name}: the path is marked`); } } finally { await rm(dir, { recursive: true, force: true }); } }); test("scrubText: secrets and roots out, words of a transcript untouched", () => { const s = { secrets: ["abcdefgh-secret"], roots: ["/srv/archive"] }; assert.equal(scrubText("he said abcdefgh-secret at /srv/archive/x.json today", s), "he said [secret] at today"); assert.equal(scrubText("a short one: abc", { secrets: ["abc"] }), "a short one: abc", "a secret under 8 characters is not a secret"); 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 "); }); 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); }); // ─── Review round (12 Nov): linear patterns, links that survive, more shapes ─── test("every scrub pattern is linear: 160,000 characters of each rule's trigger scrub in well under 250 ms", () => { const N = 160_000; const rep = (unit: string) => unit.repeat(Math.ceil(N / unit.length)).slice(0, N); const inputs: Record = { "a.": rep("a."), "a-": rep("a-"), "& then a.": `&${rep("a.")}`, "Bearer + letters": `Bearer ${"a".repeat(N)} `, "Basic + letters": `Basic ${"a".repeat(N)}`, "Bearer repeated": rep("Bearer "), "cookie: repeated": rep("cookie: "), "a cookie line of pairs": `cookie: ${rep("a=b; ")}`, "scheme then colons": `a://${rep("b:")}`, "://": rep("://"), "/home/": rep("/home/"), "/": rep("/"), "eyJ + letters": `eyJ${"a".repeat(N)}`, "eyJ. repeated": rep("eyJaaaaaaaa."), "api_key=": rep("api_key="), "? then a_": `?${rep("a_")}x`, "?a_": rep("?a_"), "A_": rep("A_"), "A": "A".repeat(N), "password:": rep("password: "), "auth_token": rep("auth_token "), "sk-": rep("sk-"), "sk- + letters": `sk-${"a".repeat(N)}`, "@": rep("@"), ":": rep(":"), "=": rep("="), "authorization:": rep("authorization: "), "one long word": "a".repeat(N), // The second review's (12 Nov): a brace before a cookie name, and the rest of its list. "{cookie:a=x": rep("{cookie:a=xxxxxxxxxx"), ",cookie:a=b;c": rep(",cookie:a=b;c=d;e"), "&a": rep("&a"), "&a-": rep("&a-"), "?a_b.": rep("?a_b."), ";access_": rep(";access_"), "a://b:c": rep("a://b:cccccc"), "a://b:c:": rep("a://b:c:c:c:"), "Bearer short": rep("Bearer aaaaaaaaaaaaaaa "), "token:word": rep("token:aaaaaaa "), "token=long": rep(`token=${"a".repeat(300)} `), "eyJ.eyJ.": rep("eyJaaaaaaaa.eyJaaaaaaaa."), "auth_token tab": rep("auth_token\taaaaaaa "), "AB_KEY=short": rep("AB_KEY=short "), " /home/x": rep(" /home/x"), "authorization: Bearer": rep("authorization: Bearer "), "authorization: word": rep("authorization: word "), "x-api-key:": rep("x-api-key:aaaa "), "__Secure-": rep("__Secure-a"), "sk-short": rep("sk-aaaaaaaaaaaaaaaaaaa "), "set-cookie lines": rep("\nset-cookie: a=b; c"), "\\u0026": rep("\\u0026a"), "%26": rep("%26a%3D"), "&": rep("&a"), }; const scrub = { secrets: ["abcdefFAKE-TEST-VALUE"], roots: ["/srv/archive", "/home/someone"] }; scrubText("warm up https://u:p@h/x?token=abc Bearer abcdefghijklmnop0123", scrub); const slow: string[] = []; for (const [name, text] of Object.entries(inputs)) { const t0 = performance.now(); scrubText(text, scrub); const ms = performance.now() - t0; if (ms >= 250) slow.push(`${name}: ${Math.round(ms)} ms`); } assert.deepEqual(slow, []); }); test("scrubText: a link is not a host path — X image links and /home/ in a URL survive; a real path still goes", () => { for (const link of [ "https://pbs.twimg.com/media/Fxyz.jpg", "see https://pbs.twimg.com/media/GabC-12_x?format=jpg&name=large here", "https://example.com/home/page and https://rumble.com/user/media/x", "https://x.com/home/user", "example.com/mnt/data", "see /media/ and /mnt/ in prose", ]) assert.equal(scrubText(link, { roots: ["/home/user"] }), link); assert.equal(scrubText("read /home/user/Projects/x.json and (/mnt/media/a.mp4)", { roots: ["/home/user"] }), "read and ()"); assert.equal(scrubText('cwd="/home/ann/.config/x"', {}), 'cwd=""'); assert.equal(scrubText("file=/media/drive/v.mkv", {}), "file="); }); test("scrubText: the shapes the first pass missed — JSON-quoted, a cookie-jar line, a written-out password, an environment assignment", () => { const cases: [string, string][] = [ ['{"auth_token":"deadbeefdeadbeefdeadbeef","ct0": "0123abcd"}', '{"auth_token":"[secret]","ct0": "[secret]"}'], ["auth_token deadbeefdeadbeefdeadbeef", "auth_token [secret]"], [".x.com\tTRUE\t/\tTRUE\t1799\tauth_token\tdeadbeefdeadbeefdeadbeef", ".x.com\tTRUE\t/\tTRUE\t1799\tauth_token\t[secret]"], [".rumble.com\tTRUE\t/\tTRUE\t1799\tcf_clearance\tZx9.yQ-77_abcdefghij", ".rumble.com\tTRUE\t/\tTRUE\t1799\tcf_clearance\t[secret]"], ["password: hunter2hunter2hunter2", "password: [secret]"], ['"password":"hunter2hunter2"', '"password":"[secret]"'], ["WORKER_TOKEN=abcd1234abcd1234abcd", "WORKER_TOKEN=[secret]"], ["export NAME_TOKEN=abcd1234abcd1234 && run", "export NAME_TOKEN=[secret] && run"], ["AWS_SECRET_ACCESS_KEY=FAKE-TEST-VALUE", "AWS_SECRET_ACCESS_KEY=[secret]"], ['"authorization":"Bearer abcdefghijklmnopqrstuvwxyz"', '"authorization":"Bearer [secret]"'], ["Authorization: Bearer abcdefghijklmnopqrstuvwxyz", "Authorization: Bearer [secret]"], ["HTTPS://U:PASS@HOST/x and https://u:p%40ss@host/x", "HTTPS://[secret]@HOST/x and https://[secret]@host/x"], ['{"cookie": "auth_token=aaaa; ct0=bbbb"}', '{"cookie": "[secret]"}'], ["Set-Cookie: sid=abc123; Path=/; HttpOnly", "Set-Cookie: [secret]"], ]; for (const [text, want] of cases) assert.equal(scrubText(text, {}), want); // Not credentials: an assignment that is not named like one, a short value, words. for (const plain of ["NODE_ENV=production-like-value", "PATH_LIKE=abcdefghijkl", "TOKEN=short", "password: none, she said", "the token: congratulations everyone", "at 12:30 he said t=5 and ip=dynamic"]) assert.equal(scrubText(plain, {}), plain); }); test("scrubText: words are not credentials — `Basic counterintelligence`, `bearer of bad news`, a sentence about a cookie", () => { for (const plain of [ "Basic counterintelligence is hard. Bearer of bad news-and-other-things.", "Basic Counterintelligence, he called it", "He said: cookie: chocolate=best ever, really", "cookie: chocolate=best ever, really", "my cookie: oatmeal", ]) assert.equal(scrubText(plain, {}), plain); assert.equal(scrubText("Basic dXNlcjpodW50ZXIyaHVudGVyMg==", {}), "Basic [secret]"); assert.equal(scrubText("sent Bearer abcdefgh1jklmnopqrst to it", {}), "sent Bearer [secret] to it"); }); test("scrubBounded: a text is cut to its cap and a margin before the scrub — a secret across the cap is still whole, a token the cut fell in is dropped", () => { const clean = (s: string) => scrubText(s, { secrets: ["SECRET-0123456789"] }); // Short: scrubbed whole. assert.equal(scrubBounded("say SECRET-0123456789 now", 10, clean), "say [secret] now"); // Long, with white space in the margin: cut there; the secret straddling the cap is scrubbed whole. const cap = 1_000; const long = `${"word ".repeat(198)}xx SECRET-0123456789 ${"tail ".repeat(5_000)}`; assert.ok(long.indexOf("SECRET") < cap && long.indexOf("SECRET") + 17 > cap, "the secret straddles the cap"); const out = scrubBounded(long, cap, clean); assert.ok(!out.includes("SECRET") && out.includes("[secret]")); assert.ok(out.length <= cap + SCRUB_MARGIN_CHARS && out.length >= cap); // One unbroken token far longer than cap + margin, a secret cut in half at the end of what is scrubbed: no half of it is kept. const cutAt = cap + SCRUB_MARGIN_CHARS; const token = `start ${"x".repeat(cutAt - 6 - 8)}SECRET-0123456789${"y".repeat(50_000)}`; const hard = scrubBounded(token, cap, clean); assert.ok(!hard.includes("SECRET-"), "no half of a credential"); assert.equal(hard, "start "); // And it is fast whatever the size. const t0 = performance.now(); scrubBounded("a.".repeat(2_000_000), 40_000, clean); assert.ok(performance.now() - t0 < 250); }); test("scrubText (second review): an ampersand however it is written, an encoded `=`, any Authorization scheme", () => { const cases: [string, string][] = [ ['"url":"https://rr1.googlevideo.com/videoplayback?expire=1\\u0026token=FAKE-TEST-VALUE\\u0026ip=203.0.113.9\\u0026itag=18"', '"url":"https://rr1.googlevideo.com/videoplayback?expire=1\\u0026token=[secret]\\u0026ip=[secret]\\u0026itag=18"'], ["a href=?v=1&sig=AAAA.BBBB&t=4", "a href=?v=1&sig=[secret]&t=4"], ["api_key%3DFAKE-TEST-VALUE", "api_key%3D[secret]"], ["next=%2Fcb%3Fx%3D1%26access_token%3DFAKE-TEST-VALUE", "next=%2Fcb%3Fx%3D1%26access_token%3D[secret]"], ['Authorization: "Token FAKE-TEST-VALUEabcdef"', 'Authorization: "Token [secret]"'], ["authorization: Digest dXNlcjpwYXNz", "authorization: Digest [secret]"], ["Proxy-Authorization: Basic dXNlcjpwYXNz", "Proxy-Authorization: Basic [secret]"], ["Authorization: SharedKey acct:FAKE-TEST-VALUE", "Authorization: SharedKey [secret]"], ["\\u0026token=FAKE-TEST-VALUE", "\\u0026token=[secret]"], ["?a=1&token=FAKE-TEST-VALUE&b=2", "?a=1&token=[secret]&b=2"], ]; for (const [text, want] of cases) assert.equal(scrubText(text, {}), want); // An authorization that is a sentence stays one. for (const plain of ["authorization: pending approval tomorrow", "Authorization: granted by the committee", "Authorization: expires 2026-11-07T10:00."]) assert.equal(scrubText(plain, {}), plain); }); test("scrubText (second review): what follows secret: / token: / password: is a credential, not a date, a time or a link", () => { for (const plain of [ "Secret: 2026-11-07T10:00 meeting", "password: 2026-11-07, as agreed", "token: 10:30-11:45", "token: 10:30am-11:45am, then lunch", "Secret: 2026-11-07T10:00Z.", "secret: (2026-11-07)", "SECRET=2026-11-07T10:00", "Token: https://example.com/watch?v=abc123", "the key to this is basic economics, a token gesture; his secret: he ate 400 calories", "my password is hunter2 and the session was great", "He said: key=value pairs are simple", ]) assert.equal(scrubText(plain, {}), plain); assert.equal(scrubText("Secret: 2026hunter2hunter", {}), "Secret: [secret]"); assert.equal(scrubText("password: 12345678", {}), "password: [secret]"); assert.equal(scrubText("PASSWORD=hunter2!", {}), "PASSWORD=[secret]"); assert.equal(scrubText("export ANTHROPIC_API_KEY='sk-ant-abcdefghijklmnopqrstuvwx'", {}), "export ANTHROPIC_API_KEY='[secret]'"); });