diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 4df06188b..55cb71288 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -88,6 +88,11 @@ import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts"; import { GitWorkflowService } from "../src/git/GitWorkflowService.ts"; import * as VcsProcess from "../src/vcs/VcsProcess.ts"; import { ThreadSessionAdmissionPermissive } from "../src/provider/Services/ThreadSessionAdmission.ts"; +import { + SecretScrubber, + type SecretScrubberShape, + makeSecretScrubber, +} from "../src/secrets/SecretScrubber.ts"; const decodeCodexSettings = Schema.decodeEffect(CodexSettings); @@ -249,6 +254,8 @@ interface MakeOrchestrationIntegrationHarnessOptions { readonly workspaceDir: string; }) => RealProviderAdapter; readonly serverSettings?: Parameters[0]; + /** One registry of watched keys shared by the provider hook and ingestion. Absent: an empty one. */ + readonly secretScrubber?: SecretScrubberShape; } const realCodexAdapter: RealProviderAdapter = { @@ -267,6 +274,12 @@ export const makeOrchestrationIntegrationHarness = ( const fileSystem = yield* FileSystem.FileSystem; const provider = options?.provider ?? ProviderDriverKind.make("codex"); + const secretScrubberLayer = Layer.succeed( + SecretScrubber, + options?.secretScrubber ?? makeSecretScrubber(), + ); + const makeProviderServiceWithScrubber = () => + makeProviderServiceLive().pipe(Layer.provide(secretScrubberLayer)); const useRealAdapter = options?.realCodex === true || options?.realAdapter !== undefined; const adapterHarness = useRealAdapter ? null @@ -315,14 +328,14 @@ export const makeOrchestrationIntegrationHarness = ( ); const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers); const providerLayer = useRealAdapter - ? makeProviderServiceLive().pipe( + ? makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(providerSessionDirectoryLayer), Layer.provide(realAdapterRegistry), Layer.provide(AnalyticsService.layerTest), Layer.provide(providerEventLoggersLayer), ) - : makeProviderServiceLive().pipe( + : makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(providerSessionDirectoryLayer), Layer.provide(fakeRegistry!), @@ -343,6 +356,7 @@ export const makeOrchestrationIntegrationHarness = ( ); const serverSettingsLayer = ServerSettingsService.layerTest(options?.serverSettings); const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( + Layer.provide(secretScrubberLayer), // No provider publishes a page in these tests. Layer.provideMerge(Layer.mock(AgentPages)({ assetsDirOf: () => null })), Layer.provideMerge(Layer.mock(McpApps)({ recordCall: () => Effect.void })), diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts index a5072f6c5..4039295f2 100644 --- a/apps/server/integration/providerService.integration.test.ts +++ b/apps/server/integration/providerService.integration.test.ts @@ -38,6 +38,11 @@ import { codexTurnTextFixture, } from "./fixtures/providerRuntime.ts"; import { ThreadSessionAdmissionPermissive } from "../src/provider/Services/ThreadSessionAdmission.ts"; +import { layerTest as SecretScrubberTest } from "../src/secrets/SecretScrubber.ts"; + +/** The provider service with an empty registry of watched keys (SecretScrubber). */ +const makeProviderServiceWithScrubber = (...args: Parameters) => + makeProviderServiceLive(...args).pipe(Layer.provide(SecretScrubberTest)); const codexInstanceId = ProviderInstanceId.make("codex"); @@ -75,7 +80,7 @@ const makeIntegrationFixture = Effect.gen(function* () { Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), ).pipe(Layer.provide(SqlitePersistenceMemory)); - const layer = makeProviderServiceLive().pipe( + const layer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(shared), ); diff --git a/apps/server/integration/replay/replay.integration.test.ts b/apps/server/integration/replay/replay.integration.test.ts index 4574173b3..20824118e 100644 --- a/apps/server/integration/replay/replay.integration.test.ts +++ b/apps/server/integration/replay/replay.integration.test.ts @@ -11,6 +11,7 @@ import { makeRecorder, privateDataIn } from "./recorder.ts"; import { runReplayScenario } from "./runReplay.ts"; import { FIXTURES_DIR, fixturePath, REPLAY_SCENARIOS } from "./scenarios.ts"; import { readTranscript } from "./transcript.ts"; +import { makeSecretScrubber } from "../../src/secrets/SecretScrubber.ts"; // A recording no scenario plays would rot unnoticed. const scenarioNames = new Set(REPLAY_SCENARIOS.map((scenario) => scenario.name)); @@ -41,6 +42,47 @@ describe("provider replays", () => { } } + // Hiding a printed key (docs/design/secret-scrubbing.md), end to end through + // the real Codex adapter and ingestion: a phrase the recording streams in + // pieces, and a child's answer that ingestion joins from pieces, are + // watched. No stored event and nothing in the final thread may hold them, + // and a notice says so. + for (const [scenarioName, watched] of [ + ["command-approval", "run the command"], + ["subagent", "ANSWER: 42"], + ] as const) { + it.live(`hides a watched phrase split across stream pieces (${scenarioName}, codex)`, () => + Effect.gen(function* () { + const scenario = REPLAY_SCENARIOS.find((entry) => entry.name === scenarioName)!; + const secretScrubber = makeSecretScrubber(); + assert.isTrue(secretScrubber.watch("WATCHED_KEY", watched)); + let checked = false; + yield* runReplayScenario({ + provider: "codex", + scenario, + mode: { kind: "replay", transcript: readTranscript(fixturePath(scenarioName, "codex")) }, + timeoutMs: 20_000, + secretScrubber, + inspect: ({ events, thread }) => { + checked = true; + for (const event of events) assert.notInclude(JSON.stringify(event), watched); + assert.notInclude(JSON.stringify(thread), watched); + assert.include(JSON.stringify(thread), "[WATCHED_KEY hidden]"); + assert.isTrue( + thread.activities.some( + (activity) => + (activity.payload as { warningKind?: string } | null)?.warningKind === + "secret-hidden", + ), + "a notice says the key was hidden", + ); + }, + }); + assert.isTrue(checked); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + } + // The repository is public: a hand-edited or older recording must not // carry anything the recorder would have refused. it("committed recordings hold no private data", () => { diff --git a/apps/server/integration/replay/runReplay.ts b/apps/server/integration/replay/runReplay.ts index 06bae1f10..21d227b41 100644 --- a/apps/server/integration/replay/runReplay.ts +++ b/apps/server/integration/replay/runReplay.ts @@ -2,6 +2,8 @@ * Runs a replay scenario on the integration harness, against a recorded * transcript (replay) or the real provider with a recorder attached (record). */ +import * as Stream from "effect/Stream"; +import type { SecretScrubberShape } from "../../src/secrets/SecretScrubber.ts"; import { ClaudeSettings, CodexSettings, @@ -114,6 +116,13 @@ export const runReplayScenario = (input: { readonly scenario: ReplayScenario; readonly mode: ProviderMode; readonly timeoutMs: number; + /** Keys to watch from the start (docs/design/secret-scrubbing.md); the scenario's own check is skipped, since hiding changes its text. */ + readonly secretScrubber?: SecretScrubberShape; + /** Runs on every stored event and the final thread instead of the scenario's check. */ + readonly inspect?: (stored: { + readonly events: ReadonlyArray; + readonly thread: OrchestrationThread; + }) => void; }) => Effect.gen(function* () { let cursor: ReplayCursor | null = null; @@ -121,6 +130,7 @@ export const runReplayScenario = (input: { const harness = yield* makeOrchestrationIntegrationHarness({ provider: ProviderDriverKind.make(input.provider), serverSettings: REPLAY_SERVER_SETTINGS, + ...(input.secretScrubber !== undefined ? { secretScrubber: input.secretScrubber } : {}), realAdapter: (paths) => (input.provider === "codex" ? codexAdapter : claudeAdapter)( input.mode, @@ -143,7 +153,12 @@ export const runReplayScenario = (input: { const thread = snapshot.threads.find((entry) => entry.id === THREAD_ID); if (thread === undefined) return yield* Effect.die(new Error("The scenario's thread is gone.")); - input.scenario.check(thread, context); + if (input.inspect !== undefined) { + const events = yield* Stream.runCollect(harness.engine.readEvents(0)).pipe(Effect.orDie); + input.inspect({ events: [...events], thread }); + } else { + input.scenario.check(thread, context); + } (cursor as ReplayCursor | null)?.assertComplete(); return { thread, cursor, recorder } satisfies ScenarioOutcome; }).pipe(Effect.ensuring(harness.dispose)); diff --git a/apps/server/scripts/bench-secret-scrubber.ts b/apps/server/scripts/bench-secret-scrubber.ts new file mode 100644 index 000000000..7f8df7df0 --- /dev/null +++ b/apps/server/scripts/bench-secret-scrubber.ts @@ -0,0 +1,92 @@ +/** + * The throughput check for hiding a printed key (docs/design/secret-scrubbing.md, "Cost"). + * Runs provider events through `scrubRuntimeEvent` with 0, 1, 50 and 200 watched values + * and prints the time per event. A report for the PR, not a CI gate. + * + * node scripts/bench-secret-scrubber.ts + */ +import { performance } from "node:perf_hooks"; + +import { makeSecretScrubber } from "../src/secrets/SecretScrubber.ts"; + +const reply = (index: number, text: string) => ({ + eventId: `e${index}`, + provider: "codex", + threadId: "session", + createdAt: "2026-11-19T00:00:00.000Z", + turnId: "turn", + itemId: "item", + type: "content.delta", + payload: { streamKind: "assistant_text", delta: text }, + raw: { + source: "codex.app-server.notification", + method: "item/agentMessage/delta", + payload: { delta: text }, + }, +}); + +const words = "the quick brown fox jumps over a lazy dog while compiling the project ".split(" "); +const tokens = Array.from({ length: 100_000 }, (_, index) => ` ${words[index % words.length]}`); +const big = "x".repeat(64 * 1024 - 20) + " build ok, 12 passed"; +const pem = `-----BEGIN KEY-----\n${"Ab9+".repeat(16 * 1024 - 10)}\n-----END KEY-----`; + +function scrubberWith(count: number) { + const scrubber = makeSecretScrubber(); + for (let index = 0; index < count; index += 1) { + scrubber.watch( + `KEY_${index}`, + index === 0 && count === 200 ? pem : `sk_test_${index}_Qa9Zr7Lm2Xc4`, + ); + } + return scrubber; +} + +function time(label: string, run: () => number) { + const started = performance.now(); + const events = run(); + const ms = performance.now() - started; + console.log( + `${label.padEnd(44)} ${((ms * 1000) / events).toFixed(2).padStart(9)} µs/event (${events} events, ${ms.toFixed(0)} ms)`, + ); +} + +for (const count of [0, 1, 50, 200]) { + console.log(`\n${count} watched`); + time("100,000 token-sized reply pieces", () => { + const scrubber = scrubberWith(count); + tokens.forEach((token, index) => scrubber.scrubRuntimeEvent(reply(index, token) as never)); + return tokens.length; + }); + time("2,000 command-output events of 64 KB", () => { + const scrubber = scrubberWith(count); + for (let index = 0; index < 2000; index += 1) { + scrubber.scrubRuntimeEvent({ + ...reply(index, big), + payload: { streamKind: "command_output", delta: big }, + } as never); + } + return 2000; + }); + time("holder: 200 buffers at once, 50 pieces each", () => { + const scrubber = scrubberWith(count); + const states = new Map[0]>(); + let pieces = 0; + for (let round = 0; round < 50; round += 1) { + for (let buffer = 0; buffer < 200; buffer += 1) { + const held = scrubber.holdPiece(states.get(buffer), " sk_test_1"); + states.set(buffer, held.state); + pieces += 1; + } + } + return pieces; + }); +} + +console.log("\n64 KB key arriving one character per piece through the holder (200 watched)"); +time("one character per piece", () => { + const scrubber = scrubberWith(200); + let state: Parameters[0]; + const chars = [...pem]; + for (const char of chars) state = scrubber.holdPiece(state, char).state; + return chars.length; +}); diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 735e36fd3..82c2768f3 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -533,7 +533,9 @@ Settings that give agents more reach ({place:threads.agentThreads}, {place:threa ], body: `When an agent needs an API key, token or password, it asks on a card above the message box instead of in chat. The card shows the name, the agent's reason, and, in Threadlines' own words, where the key goes: a NAME=value line in a git-ignored env file in the thread's folder (like .env.local), or a private file for the agent's commands that is removed after 24 hours. Save sends it to the thread's computer; Not now saves nothing. The agent hears the outcome, never the value. -What this promises: Threadlines doesn't put the key in the chat, its stored events, logs or other apps. What it doesn't: the agent runs as you on that computer, so it can still read the file, and if it prints the key, the model sees it. A key pasted into chat is already in the conversation; replace it if that matters. Answering needs an encrypted connection to that computer. Archiving, moving or deleting the thread removes its private files, and a saved row for a private file has Remove now.`, +What this promises: Threadlines doesn't put the key in the chat, its stored events, logs or other apps. What it doesn't: the agent runs as you on that computer, so it can still read the file, and if it prints the key, the model sees it. A key pasted into chat is already in the conversation; replace it if that matters. Answering needs an encrypted connection to that computer. Archiving, moving or deleting the thread removes its private files, and a saved row for a private file has Remove now. + +If the agent later prints a saved key, or a tool reads it, Threadlines replaces it with [NAME hidden] before it stores, logs or shows that text, and a row in the thread says so. The model may still have seen it, and the provider's own transcript keeps it; replace the key if that matters. Keys under 8 characters, or made only of letters or only of digits, aren't hidden. Your terminal, files in the project and voice audio aren't covered, and a key changed by hand in the env file is hidden from the next restart.`, }, { id: "updates", diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index af22e7e08..f006f0fae 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -1,4 +1,10 @@ // @effect-diagnostics nodeBuiltinImport:off +import { + layerTest as SecretScrubberTest, + makeSecretScrubber, + SecretScrubber, + type SecretScrubberShape, +} from "../../secrets/SecretScrubber.ts"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -287,6 +293,8 @@ describe("ProviderRuntimeIngestion", () => { serverSettings?: Partial; /** False: the project's folder has no git (a general chat's, say). */ git?: boolean; + /** Watched keys (SecretScrubber). Absent: none. */ + secretScrubber?: SecretScrubberShape; }) { const workspaceRoot = makeTempDir("t3-provider-project-"); if (options?.git ?? true) { @@ -307,6 +315,11 @@ describe("ProviderRuntimeIngestion", () => { Layer.provide(SqlitePersistenceMemory), ); const layer = ProviderRuntimeIngestionLive.pipe( + Layer.provide( + options?.secretScrubber === undefined + ? SecretScrubberTest + : Layer.succeed(SecretScrubber, options.secretScrubber), + ), Layer.provideMerge( Layer.mock(AgentPages)({ adopt: (input) => @@ -412,6 +425,310 @@ describe("ProviderRuntimeIngestion", () => { }; } + describe("hiding a key split across pieces, in what is stored", () => { + const KEY = "sk_test_51HvQq2abc"; + const now = "2026-01-01T00:00:00.000Z"; + + it("holds a streamed reply's tail per message and releases it as the message completes", async () => { + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", KEY); + const harness = await createHarness({ + serverSettings: { enableAssistantStreaming: true }, + secretScrubber, + }); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-secret"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("message-secret"), + role: "user", + text: "print it", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + await harness.drain(); + const emit = (id: string, event: Record) => + harness.emit({ + eventId: asEventId(id), + provider: ProviderDriverKind.make("codex"), + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-secret"), + ...event, + } as never); + emit("evt-secret-started", { type: "turn.started" }); + await waitForThread( + harness.readModel, + (thread) => thread.session?.activeTurnId === "turn-secret", + ); + for (const [index, piece] of [ + "Your key is s", + "k_test_5", + "1HvQq2abc. Done with the tests", + ].entries()) { + emit(`evt-secret-delta-${index}`, { + type: "content.delta", + itemId: asItemId("item-secret"), + payload: { streamKind: "assistant_text", delta: piece }, + }); + } + emit("evt-secret-completed", { + type: "item.completed", + itemId: asItemId("item-secret"), + payload: { itemType: "assistant_message", status: "completed" }, + }); + const thread = await waitForThread(harness.readModel, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-secret" && !message.streaming, + ), + ); + const message = thread.messages.find( + (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-secret", + ); + expect(message?.text).toBe("Your key is [STRIPE_SECRET_KEY hidden]. Done with the tests"); + expect(JSON.stringify(thread)).not.toContain(KEY); + expect( + thread.activities.some( + (activity) => + (activity.payload as { warningKind?: string } | null)?.warningKind === "secret-hidden", + ), + ).toBe(true); + }); + + /** A harness watching `abcd1234`, with a running turn on thread-1. */ + async function watchingHarness(streaming = true) { + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("TOKEN", "abcd1234"); + const harness = await createHarness({ + serverSettings: { enableAssistantStreaming: streaming }, + secretScrubber, + }); + const emit = (id: string, event: Record) => + harness.emit({ + eventId: asEventId(id), + provider: ProviderDriverKind.make("codex"), + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-held"), + ...event, + } as never); + return { harness, emit }; + } + const messageText = ( + thread: { messages: ReadonlyArray }, + id: string, + ) => thread.messages.find((entry) => entry.id === id)?.text; + + it("sends a completed reply's only text once, when the completion repeats it", async () => { + const { harness, emit } = await watchingHarness(); + emit("evt-held-only-delta", { + type: "content.delta", + itemId: asItemId("item-held-only"), + payload: { streamKind: "assistant_text", delta: "abc" }, + }); + emit("evt-held-only-done", { + type: "item.completed", + itemId: asItemId("item-held-only"), + payload: { itemType: "assistant_message", status: "completed", detail: "abc" }, + }); + const thread = await waitForThread(harness.readModel, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-held-only" && !message.streaming, + ), + ); + expect(messageText(thread, "assistant:item-held-only")).toBe("abc"); + }); + + it("puts a reply's held tail into its message when the session ends", async () => { + const { harness, emit } = await watchingHarness(); + emit("evt-exit-delta", { + type: "content.delta", + itemId: asItemId("item-exit"), + payload: { streamKind: "assistant_text", delta: "Result: abc" }, + }); + emit("evt-exit", { type: "session.exited", payload: { exitKind: "graceful" } }); + const thread = await waitForThread(harness.readModel, (entry) => + entry.messages.some( + (message: ProviderRuntimeTestMessage) => + message.id === "assistant:item-exit" && message.text === "Result: abc", + ), + ); + expect(messageText(thread, "assistant:item-exit")).toBe("Result: abc"); + }); + + it("puts a command's held tail into its output when the command ends", async () => { + const { harness, emit } = await watchingHarness(); + emit("evt-output-tail", { + type: "content.delta", + itemId: asItemId("item-output-tail"), + payload: { streamKind: "command_output", delta: "Result: abc" }, + }); + emit("evt-output-tail-done", { + type: "item.completed", + itemId: asItemId("item-output-tail"), + payload: { itemType: "command_execution", status: "completed" }, + }); + const thread = await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => + JSON.stringify(activity.payload).includes("Result: abc"), + ), + ); + expect(JSON.stringify(thread)).toContain("Result: abc"); + }); + + it("hides a key a side answer only makes whole by joining two items", async () => { + const secretScrubber = makeSecretScrubber(); + const pem = "ab12\n\ncd34"; + secretScrubber.watch("PEM_KEY", pem); + const harness = await createHarness({ secretScrubber }); + const threadId = asThreadId("thread-1"); + const sideTurnId = SideTurnId.make("0d9e8f7a-6b5c-4d3e-8f1a-2b3c4d5e6f71"); + const astraId = ThreadParticipantId.make("7a0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2e"); + const dispatch = (command: Parameters[0]) => + Effect.runPromise(harness.engine.dispatch(command)); + // A side answer needs a room with another agent at work. + await dispatch({ + type: "thread.participant.add", + commandId: CommandId.make("cmd-secret-side-add-astra"), + threadId, + participant: { + id: astraId, + handle: "GPT-6 Astra", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6-astra" }, + }, + createdAt: now, + }); + await dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-secret-side-astra-working"), + threadId, + session: { + threadId, + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + participantId: astraId, + activeTurnId: asTurnId("turn-astra-secret"), + updatedAt: now, + lastError: null, + }, + createdAt: now, + }); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.side-turn.start", + commandId: CommandId.make("cmd-secret-side-ask"), + threadId, + sideTurnId, + participantId: null, + message: { messageId: asMessageId("secret-side-question"), role: "user", text: "why?" }, + createdAt: now, + }), + ); + const sideEvent = (id: string, event: Record) => + harness.emit({ + eventId: asEventId(id), + provider: ProviderDriverKind.make("claudeAgent"), + threadId, + createdAt: now, + turnId: asTurnId("turn-secret-side"), + sideTurnId, + ...event, + } as never); + sideEvent("evt-secret-side-1", { + type: "content.delta", + itemId: "msg-1", + payload: { streamKind: "assistant_text", delta: "Key: ab12" }, + }); + sideEvent("evt-secret-side-2", { + type: "content.delta", + itemId: "msg-2", + payload: { streamKind: "assistant_text", delta: "cd34 is it." }, + }); + sideEvent("evt-secret-side-done", { + type: "turn.completed", + payload: { state: "completed" }, + }); + await harness.drain(); + const settled = await waitForThread( + harness.readModel, + (thread) => (thread.sideTurn ?? null) === null, + ); + const answer = settled.messages.find((message) => message.id === `side-answer:${sideTurnId}`); + expect(answer?.text).toBe("Key: [PEM_KEY hidden] is it."); + expect(JSON.stringify(settled)).not.toContain("ab12\\n\\ncd34"); + }); + + it("holds command output before its buffer, so no snapshot holds the key", async () => { + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", KEY); + const harness = await createHarness({ secretScrubber }); + const emit = (id: string, event: Record) => + harness.emit({ + eventId: asEventId(id), + provider: ProviderDriverKind.make("codex"), + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-secret-output"), + ...event, + } as never); + const pieces = [ + `env\n${"x".repeat(500)}\nSTRIPE=sk_te`, + "st_51HvQq2abc\n", + `${"y".repeat(2100)}\n`, + ]; + pieces.forEach((piece, index) => + emit(`evt-secret-output-${index}`, { + type: "content.delta", + itemId: asItemId("item-secret-output"), + payload: { streamKind: "command_output", delta: piece }, + }), + ); + await harness.drain(); + const thread = await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => JSON.stringify(activity).includes("yyyy")), + ); + expect(JSON.stringify(thread)).not.toContain(KEY); + expect( + thread.activities.some( + (activity) => + (activity.payload as { warningKind?: string } | null)?.warningKind === "secret-hidden", + ), + ).toBe(true); + }); + }); + + it("hides a watched key that only joining makes whole, in whatever it stores", async () => { + const secretScrubber = makeSecretScrubber(); + expect(secretScrubber.watch("PEM_KEY", "ab12\ncd34-ef")).toBe(true); + const harness = await createHarness({ secretScrubber }); + + harness.emit({ + type: "auth.status", + eventId: asEventId("evt-auth-joined"), + provider: ProviderDriverKind.make("codex"), + threadId: asThreadId("thread-1"), + createdAt: "2026-01-01T00:00:01.000Z", + payload: { isAuthenticating: true, output: ["ab12", "cd34-ef"] }, + }); + + const thread = await waitForThread(harness.readModel, (entry) => + entry.activities.some((activity) => activity.kind === "auth.status"), + ); + const stored = JSON.stringify(thread); + expect(stored).not.toContain("ab12\ncd34-ef"); + expect(stored).not.toContain("ab12\\ncd34-ef"); + expect(stored).toContain("[PEM_KEY hidden]"); + }); + it("drops realtime audio deltas before any orchestration event is persisted", async () => { const harness = await createHarness(); const before = await harness.readModel(); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index f38f6b3a8..dbe3b4490 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -1,4 +1,10 @@ import { liveSideTurn } from "@threadlines/shared/sideTurns"; +import { SecretScrubber } from "../../secrets/SecretScrubber.ts"; +import { + type HeldText, + SECRET_HIDDEN_DETAIL, + SECRET_HIDDEN_WARNING_KIND, +} from "../../secrets/secretScrubberCore.ts"; import { type OrchestrationSessionUsageLimit, CHECKPOINT_FILES_ACTIVITY_ID_PREFIX, @@ -149,6 +155,8 @@ interface BufferedActivityStream { readonly byteCount: number; readonly lineCount: number; readonly truncated: boolean; + /** A tail held back because it could start a watched key (SecretScrubber.holdPiece). */ + readonly held?: HeldText | undefined; } interface PendingStreamingAssistantMessage { @@ -904,6 +912,36 @@ function orchestrationSessionStatusFromRuntimeState( const make = Effect.gen(function* () { const orchestrationEngine = yield* OrchestrationEngineService; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + // Hiding a printed key (docs/design/secret-scrubbing.md, "Streams"): the + // provider hook hides whole values in each event; text ingestion appends + // piece by piece is held here, per buffer, so a key split across pieces is + // hidden where the pieces are joined. Whole snapshots get a whole-value check. + const secretScrubber = yield* SecretScrubber; + /** + * What each assistant message held back (a tail that could start a watched + * key), by thread and message: provider item ids, and so message ids, can + * repeat across threads. After a message completes its released tail stays, + * so a piece that reopens it can't complete the key; the oldest entries go + * past a cap. + */ + const heldAssistantText = new Map(); + const HELD_ASSISTANT_TEXT_CAP = 2_000; + const heldKey = (threadId: ThreadId, messageId: MessageId) => `${threadId}\u0000${messageId}`; + const setHeldAssistantText = (key: string, state: HeldText | undefined) => { + heldAssistantText.delete(key); + if (state === undefined) return; + heldAssistantText.set(key, state); + if (heldAssistantText.size > HELD_ASSISTANT_TEXT_CAP) { + const oldest = heldAssistantText.keys().next().value; + if (oldest !== undefined) heldAssistantText.delete(oldest); + } + }; + /** Commands and thinking streams holding a tail, by stream key: their last piece, for the release. */ + const heldActivityStreams = new Map< + string, + Extract + >(); + const providerService = yield* ProviderService; const projectionTurnRepository = yield* ProjectionTurnRepository; // Computer links, when this server has them: see RemoteRequestTurnEnds. @@ -1390,6 +1428,73 @@ const make = Effect.gen(function* () { return answer; }); + /** + * A row in the thread saying a watched key was hidden, once per name per + * turn (shared with the provider hook's notices). None for a side answer. + */ + const noticeHiddenSecrets = ( + event: ProviderRuntimeEvent, + threadId: ThreadId, + names: ReadonlyArray, + ) => + names.length === 0 || event.sideTurnId !== undefined + ? Effect.void + : Effect.forEach( + secretScrubber.takeNotices(threadId, event.turnId, names), + (name) => + orchestrationEngine + .dispatch({ + type: "thread.activity.append", + commandId: providerCommandId(event, `secret-hidden:${name}`), + threadId, + activity: { + id: EventId.make(`secret-hidden:${event.eventId}:${name}`), + tone: "warning", + kind: "runtime.warning", + summary: "Runtime warning", + payload: { + message: secretScrubber.noticeLine(name), + provider: event.provider, + detail: SECRET_HIDDEN_DETAIL, + warningKind: SECRET_HIDDEN_WARNING_KIND, + }, + turnId: toTurnId(event.turnId) ?? null, + createdAt: event.createdAt, + }, + createdAt: event.createdAt, + }) + .pipe( + Effect.asVoid, + Effect.catch(() => Effect.void), + ), + { discard: true }, + ); + + /** Hides whole watched values in an activity before it is stored. */ + const scrubActivity = (event: ProviderRuntimeEvent, activity: OrchestrationThreadActivity) => { + const summary = secretScrubber.scrubText(activity.summary); + const payload = secretScrubber.scrubDeep(activity.payload); + const hidden = + summary.names.length > 0 || payload !== activity.payload + ? [...summary.names, ...secretScrubber.contains(activity.payload)] + : []; + return { + activity: + summary.text === activity.summary && payload === activity.payload + ? activity + : { ...activity, summary: summary.text, payload }, + names: [...new Set(hidden)], + event, + }; + }; + + /** + * Sends one piece of an assistant message's text. The piece is joined with + * what the message held back, whole watched values in it are hidden, and a + * tail that could start one is held back again until the next piece or the + * message completes (releaseHeldAssistantText). A piece held whole sends + * nothing. + */ const dispatchAssistantDelta = (input: { event: ProviderRuntimeEvent; threadId: ThreadId; @@ -1398,6 +1503,47 @@ const make = Effect.gen(function* () { turnId?: TurnId; createdAt: string; commandTag: string; + }) => + Effect.gen(function* () { + const key = heldKey(input.threadId, input.messageId); + const held = secretScrubber.holdPiece(heldAssistantText.get(key), input.delta); + setHeldAssistantText(key, held.state); + yield* noticeHiddenSecrets(input.event, input.threadId, held.names); + if (held.out.length === 0) return; + yield* sendAssistantDelta({ ...input, delta: held.out }); + }); + + /** What a message held back, sent as its last piece just before it completes. True when there was any. */ + const releaseHeldAssistantText = (input: { + event: ProviderRuntimeEvent; + threadId: ThreadId; + messageId: MessageId; + turnId?: TurnId; + createdAt: string; + commandTag: string; + }) => + Effect.gen(function* () { + const key = heldKey(input.threadId, input.messageId); + const held = heldAssistantText.get(key); + // Released into this message; what it held stays as already-sent text. + setHeldAssistantText(key, secretScrubber.afterRelease(held)); + if (held === undefined || held.held.length === 0) return false; + yield* sendAssistantDelta({ + ...input, + delta: held.held, + commandTag: `${input.commandTag}-held`, + }); + return true; + }); + + const sendAssistantDelta = (input: { + event: ProviderRuntimeEvent; + threadId: ThreadId; + messageId: MessageId; + delta: string; + turnId?: TurnId; + createdAt: string; + commandTag: string; }) => { const dispatch = orchestrationEngine.dispatch({ type: "thread.message.assistant.delta", @@ -1417,7 +1563,7 @@ const make = Effect.gen(function* () { ? dispatch : dispatch.pipe( Effect.asVoid, - Effect.catch(() => clearAssistantMessageState(input.messageId)), + Effect.catch(() => clearAssistantMessageState(input.threadId, input.messageId)), ); }; @@ -1434,7 +1580,8 @@ const make = Effect.gen(function* () { event: input.event, childProviderThreadId: input.childProviderThreadId, parentProviderThreadId: input.parentProviderThreadId, - body: input.body, + // The child's answer so far, joined from its pieces: one whole-value check. + body: secretScrubber.scrubText(input.body).text, status: input.status, createdAt: input.createdAt, }); @@ -1790,6 +1937,9 @@ const make = Effect.gen(function* () { const appendBufferedActivityStream = ( event: ProviderRuntimeEvent, + storedOn: ThreadId, + /** The item ended: what the stream held goes into its buffer, and a snapshot is taken. */ + release = false, ): Effect.Effect => Effect.gen(function* () { if (event.type !== "content.delta") { @@ -1804,12 +1954,24 @@ const make = Effect.gen(function* () { const previous = yield* Cache.getOption(bufferedActivityStreamByKey, streamKey).pipe( Effect.map(Option.getOrUndefined), ); - const next = appendActivityStreamText(previous, event.payload.delta); + // Held before the buffer: its window can cut a key's front, and a + // snapshot of it is dispatched whole. + const held = release + ? { out: previous?.held?.held ?? "", state: undefined, names: [] } + : secretScrubber.holdPiece(previous?.held, event.payload.delta); + yield* noticeHiddenSecrets(event, storedOn, held.names); + if (held.state !== undefined && held.state.held.length > 0) { + heldActivityStreams.set(streamKey, event); + } else { + heldActivityStreams.delete(streamKey); + } + const next = { ...appendActivityStreamText(previous, held.out), held: held.state }; yield* Cache.set(bufferedActivityStreamByKey, streamKey, next); const lastEmitted = yield* Cache.getOption(emittedActivityStreamCursorByKey, streamKey).pipe( Effect.map(Option.getOrUndefined), ); if ( + !(release && held.out.length > 0) && !shouldEmitActivityStreamSnapshot({ streamKind, lastEmitted, @@ -1838,18 +2000,51 @@ const make = Effect.gen(function* () { const projectRuntimeActivities = ( event: ProviderRuntimeEvent, thread: Pick, + /** The thread the activities are stored on, for the notice. */ + storedOn: ThreadId, ) => Effect.gen(function* () { - const stream = yield* appendBufferedActivityStream(event); - const activities = projectRuntimeEventToActivities(event, { stream }); + // An item that ends takes its streams' held tails into their output first. + const released: OrchestrationThreadActivity[] = []; + if (event.type === "item.completed" && event.itemId !== undefined) { + // A copy: the release below deletes from the map. + for (const [streamKey, last] of Array.from(heldActivityStreams)) { + if (last.threadId !== event.threadId || last.itemId !== event.itemId) continue; + heldActivityStreams.delete(streamKey); + const tail = { + ...last, + eventId: EventId.make(`${last.eventId}:held-tail`), + payload: { ...last.payload, delta: "" }, + }; + const snapshot = yield* appendBufferedActivityStream(tail, storedOn, true); + released.push(...projectRuntimeEventToActivities(tail, { stream: snapshot })); + } + } + const stream = yield* appendBufferedActivityStream(event, storedOn); + const projected = [...released, ...projectRuntimeEventToActivities(event, { stream })]; const childProviderThreadId = childProviderThreadIdForEvent(event, thread); - return childProviderThreadId - ? activities.map((activity) => withSourceAgentThreadId(activity, childProviderThreadId)) - : activities; + const activities = childProviderThreadId + ? projected.map((activity) => withSourceAgentThreadId(activity, childProviderThreadId)) + : projected; + // Activities are stored whole; text joined into them (a list's lines, + // a stream's window) gets one more whole-value check. + const scrubbed = activities.map((activity) => scrubActivity(event, activity)); + yield* noticeHiddenSecrets( + event, + storedOn, + scrubbed.flatMap((entry) => entry.names), + ); + return scrubbed.map((entry) => entry.activity); }); - const clearAssistantMessageState = (messageId: MessageId) => - clearPendingStreamingAssistantMessage(messageId).pipe( + const clearAssistantMessageState = (threadId: ThreadId, messageId: MessageId) => + Effect.sync(() => { + // Nothing held is sent from here; what was held counts as sent text, so + // a piece that reopens the message still can't complete a key. + const key = heldKey(threadId, messageId); + setHeldAssistantText(key, secretScrubber.afterRelease(heldAssistantText.get(key))); + }).pipe( + Effect.andThen(clearPendingStreamingAssistantMessage(messageId)), Effect.andThen(clearStreamingMarkdownState(messageId)), Effect.andThen(clearBufferedAssistantText(messageId)), Effect.andThen(Cache.invalidate(streamedAssistantMessageIds, messageId)), @@ -1923,12 +2118,12 @@ const make = Effect.gen(function* () { }) => Effect.gen(function* () { const bufferedText = yield* takeBufferedAssistantText(input.messageId); - const text = - bufferedText.length > 0 - ? bufferedText - : (input.fallbackText?.trim().length ?? 0) > 0 - ? input.fallbackText! - : ""; + const usesFallback = + bufferedText.length === 0 && (input.fallbackText?.trim().length ?? 0) > 0; + const text = usesFallback ? input.fallbackText! : bufferedText; + // The fallback is the message's whole text: what the message held of + // earlier pieces is in it already, so it is not sent twice. + if (usesFallback) heldAssistantText.delete(heldKey(input.threadId, input.messageId)); const hasRenderableText = hasRenderableAssistantText(text); if (hasRenderableText) { @@ -1943,7 +2138,16 @@ const make = Effect.gen(function* () { }); } - if (input.hasProjectedMessage || hasRenderableText) { + const releasedHeld = yield* releaseHeldAssistantText({ + event: input.event, + threadId: input.threadId, + messageId: input.messageId, + ...(input.turnId ? { turnId: input.turnId } : {}), + createdAt: input.createdAt, + commandTag: input.finalDeltaCommandTag, + }); + + if (input.hasProjectedMessage || hasRenderableText || releasedHeld) { yield* orchestrationEngine.dispatch({ type: "thread.message.assistant.complete", commandId: providerCommandId(input.event, input.commandTag), @@ -1955,7 +2159,7 @@ const make = Effect.gen(function* () { createdAt: input.createdAt, }); } - yield* clearAssistantMessageState(input.messageId); + yield* clearAssistantMessageState(input.threadId, input.messageId); }); const finalizeActiveAssistantSegmentForTurn = (input: { @@ -2017,7 +2221,13 @@ const make = Effect.gen(function* () { updatedAt: string; }) => Effect.gen(function* () { - const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); + // The plan is joined from pieces and stored whole: one whole-value check. + const scrubbedPlan = + input.planMarkdown === undefined ? undefined : secretScrubber.scrubText(input.planMarkdown); + if (scrubbedPlan !== undefined) { + yield* noticeHiddenSecrets(input.event, input.threadId, scrubbedPlan.names); + } + const planMarkdown = normalizeProposedPlanMarkdown(scrubbedPlan?.text); if (!planMarkdown) { return; } @@ -2114,9 +2324,11 @@ const make = Effect.gen(function* () { const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); if (Option.isSome(messageIds)) { - yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { - concurrency: 1, - }).pipe(Effect.asVoid); + yield* Effect.forEach( + messageIds.value, + (messageId) => clearAssistantMessageState(threadId, messageId), + { concurrency: 1 }, + ).pipe(Effect.asVoid); } yield* Cache.invalidate(turnMessageIdsByTurnKey, key); @@ -2275,7 +2487,7 @@ const make = Effect.gen(function* () { // late output is dropped, never written over the answer. if (liveSideTurn(thread, sideTurnId) === undefined) { sideAnswersWithText.delete(sideTurnId); - yield* clearAssistantMessageState(sideAnswerMessageId(sideTurnId)); + yield* clearAssistantMessageState(thread.id, sideAnswerMessageId(sideTurnId)); return; } const messageId = sideAnswerMessageId(sideTurnId); @@ -2308,7 +2520,7 @@ const make = Effect.gen(function* () { event.type === "item.completed" || event.type === "content.delta" ) { - const activities = yield* projectRuntimeActivities(event, thread); + const activities = yield* projectRuntimeActivities(event, thread, thread.id); yield* Effect.forEach(activities, (activity) => orchestrationEngine.dispatch({ type: "thread.activity.append", @@ -2346,7 +2558,14 @@ const make = Effect.gen(function* () { createdAt: now, commandTag: "side-answer-flush", }); - yield* clearAssistantMessageState(messageId); + yield* releaseHeldAssistantText({ + event, + threadId: thread.id, + messageId, + createdAt: now, + commandTag: "side-answer-flush", + }); + yield* clearAssistantMessageState(thread.id, messageId); yield* orchestrationEngine .dispatch({ type: "thread.message.assistant.complete", @@ -3574,15 +3793,14 @@ const make = Effect.gen(function* () { assistantDelta, ); if (spillChunk.length > 0) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: providerCommandId(event, "assistant-delta-buffer-spill"), + yield* dispatchAssistantDelta({ + event, threadId: thread.id, messageId: assistantMessageId, - participantId: event.participantId ?? null, delta: spillChunk, ...(turnId ? { turnId } : {}), createdAt: now, + commandTag: "assistant-delta-buffer-spill", }); } } else { @@ -3965,6 +4183,19 @@ const make = Effect.gen(function* () { } if (event.type === "session.exited") { + // Held tails go into their messages before the session's state is cleared. + const prefix = `${thread.id}\u0000`; + // A copy: a release re-inserts its entry, which a live iteration would visit again. + for (const key of Array.from(heldAssistantText.keys())) { + if (!key.startsWith(prefix)) continue; + yield* releaseHeldAssistantText({ + event, + threadId: thread.id, + messageId: MessageId.make(key.slice(prefix.length)), + createdAt: now, + commandTag: "session-exit", + }); + } yield* clearTurnStateForSession(thread.id); } @@ -4106,7 +4337,7 @@ const make = Effect.gen(function* () { yield* recordMcpAppCall(event, thread.id); - const activities = yield* projectRuntimeActivities(event, attributionThread); + const activities = yield* projectRuntimeActivities(event, attributionThread, thread.id); yield* Effect.forEach(activities, (activity) => orchestrationEngine.dispatch({ type: "thread.activity.append", diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index cd58c1ee0..c7fae4b27 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -83,6 +83,11 @@ import { ThreadSessionAdmission, ThreadSessionAdmissionPermissive, } from "../Services/ThreadSessionAdmission.ts"; +import { layerTest as SecretScrubberTest } from "../../secrets/SecretScrubber.ts"; + +/** The provider service with an empty registry of watched keys (SecretScrubber). */ +const makeProviderServiceWithScrubber = (...args: Parameters) => + makeProviderServiceLive(...args).pipe(Layer.provide(SecretScrubberTest)); const defaultServerSettingsLayer = ServerSettingsService.layerTest(); @@ -445,7 +450,7 @@ function makeProviderServiceLayer() { const layer = it.layer( Layer.mergeAll( - makeProviderServiceLive().pipe( + makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), @@ -489,7 +494,7 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () => ); const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); const providerLayer = Layer.mergeAll( - makeProviderServiceLive().pipe( + makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), @@ -564,7 +569,7 @@ it.effect( const directoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), @@ -627,7 +632,7 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance Layer.provide(SqlitePersistenceMemory), ); const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), @@ -668,7 +673,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se Layer.provide(SqlitePersistenceMemory), ); const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive({ + const providerLayer = makeProviderServiceWithScrubber({ canonicalEventLogger: { filePath: "memory://provider-canonical-events", write: (event, threadId) => { @@ -727,7 +732,7 @@ it.effect( const directoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), @@ -827,7 +832,7 @@ it.effect("ProviderServiceLive reports a failure under the category the agent na ProviderSessionRuntimeRepositoryLive.pipe(Layer.provide(SqlitePersistenceMemory)), ), ); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), @@ -920,7 +925,7 @@ it.effect("ProviderServiceLive keeps a turn the provider took when a write after }; }), ).pipe(Layer.provide(realDirectory)); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), @@ -959,7 +964,7 @@ const makeEarlyStartHarness = () => { Layer.provide(SqlitePersistenceMemory), ); const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const layer = makeProviderServiceLive().pipe( + const layer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), @@ -1348,7 +1353,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", ( }); }).pipe(Effect.provide(directoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( + const providerLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), @@ -1408,7 +1413,7 @@ it.effect( const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const firstProviderLayer = makeProviderServiceLive().pipe( + const firstProviderLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)), Layer.provide(firstDirectoryLayer), @@ -1461,7 +1466,7 @@ it.effect( const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const secondProviderLayer = makeProviderServiceLive().pipe( + const secondProviderLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)), Layer.provide(secondDirectoryLayer), @@ -2488,7 +2493,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const firstProviderLayer = makeProviderServiceLive().pipe( + const firstProviderLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)), Layer.provide(firstDirectoryLayer), @@ -2520,7 +2525,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const secondProviderLayer = makeProviderServiceLive().pipe( + const secondProviderLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)), Layer.provide(secondDirectoryLayer), @@ -2633,7 +2638,7 @@ routing.layer("ProviderServiceLive routing", (it) => { }; }; const providerLayerFor = (adapter: ReturnType["adapter"]) => - makeProviderServiceLive().pipe( + makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, accountsRegistry(adapter))), Layer.provide(ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer))), @@ -2696,7 +2701,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const firstProviderLayer = makeProviderServiceLive().pipe( + const firstProviderLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)), Layer.provide(firstDirectoryLayer), @@ -2723,7 +2728,7 @@ routing.layer("ProviderServiceLive routing", (it) => { const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(runtimeRepositoryLayer), ); - const secondProviderLayer = makeProviderServiceLive().pipe( + const secondProviderLayer = makeProviderServiceWithScrubber().pipe( Layer.provide(ThreadSessionAdmissionPermissive), Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)), Layer.provide(secondDirectoryLayer), @@ -3207,7 +3212,7 @@ function makeFencedProviderServiceLayer() { ); const layer = it.layer( Layer.mergeAll( - makeProviderServiceLive().pipe( + makeProviderServiceWithScrubber().pipe( Layer.provide(admission), Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)), Layer.provide(directoryLayer), diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index bd3eff178..8eb55985b 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -9,6 +9,7 @@ * * @module ProviderServiceLive */ +import { SecretScrubber } from "../../secrets/SecretScrubber.ts"; import { EventId, MessageId, @@ -386,6 +387,9 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const registry = yield* ProviderAdapterRegistry; const directory = yield* ProviderSessionDirectory; + // Watched keys are hidden here, before anything stores, logs or sends an + // event (docs/design/secret-scrubbing.md, "Where it runs"). + const secretScrubber = yield* SecretScrubber; const admission = yield* ThreadSessionAdmission; const runtimeEventPubSub = yield* PubSub.unbounded(); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); @@ -675,7 +679,13 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( increment(providerRuntimeEventsTotal, { provider: canonicalEvent.provider, eventType: canonicalEvent.type, - }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))), + }).pipe( + Effect.andThen( + Effect.forEach(secretScrubber.scrubRuntimeEvent(canonicalEvent), publishRuntimeEvent, { + discard: true, + }), + ), + ), ), ); @@ -2537,7 +2547,11 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( "provider.thread_id": input.threadId, "provider.request_id": input.requestId, }); - yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); + yield* routed.adapter.respondToRequest( + routed.threadId, + input.requestId, + secretScrubber.restoreAnswer(routed.threadId, input.requestId, input.decision), + ); yield* analytics.record("provider.request.responded", { provider: routed.adapter.provider, decision: input.decision, @@ -2576,13 +2590,15 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( "provider.thread_id": input.threadId, "provider.request_id": input.requestId, }); + // A question shown with a key hidden is answered under its original text. + const answers = secretScrubber.restoreAnswer(routed.threadId, input.requestId, input.answers); yield* input.unanswered === undefined - ? routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers) + ? routed.adapter.respondToUserInput(routed.threadId, input.requestId, answers) : routed.adapter.respondToUserInput( routed.threadId, input.requestId, - input.answers, - input.unanswered, + answers, + secretScrubber.restoreAnswer(routed.threadId, input.requestId, input.unanswered), ); }).pipe( withMetrics({ diff --git a/apps/server/src/secrets/AgentSecretRequests.test.ts b/apps/server/src/secrets/AgentSecretRequests.test.ts index 7caf82dbe..235d79ef3 100644 --- a/apps/server/src/secrets/AgentSecretRequests.test.ts +++ b/apps/server/src/secrets/AgentSecretRequests.test.ts @@ -99,6 +99,7 @@ function run( readonly archived?: boolean; readonly recoverySeesNothing?: boolean; readonly threadReadFails?: boolean; + readonly watched?: Array; }, ) { let state = requests; @@ -179,6 +180,12 @@ function run( ), }, makeSecretDestinations({ agentSecretsDir: NodePath.join(home, "agent-secrets"), runGit }), + { + watch: (name, value) => { + options?.watched?.push([name, value]); + }, + gone: () => {}, + }, ); return yield* body(service, () => state); }); @@ -213,6 +220,15 @@ describe("answering an agent's request for a key", () => { expect(JSON.stringify(commands)).not.toContain(CANARY); }); + it("watches the value as typed, not the env file's quoted spelling, from before the write", async () => { + const watched: Array = []; + await run([waiting(ENV)], (service) => service.respond(save("claim-a", "abc#123456")), { + watched, + }); + expect(watched).toEqual([["STRIPE_SECRET_KEY", "abc#123456"]]); + expect(NodeFs.readFileSync(envFile(), "utf8")).toBe("STRIPE_SECRET_KEY='abc#123456'\n"); + }); + it("the first app to press Save wins; the second is told who answered and its value is dropped", async () => { const { result } = await run([waiting(ENV)], (service) => Effect.gen(function* () { diff --git a/apps/server/src/secrets/AgentSecretRequests.ts b/apps/server/src/secrets/AgentSecretRequests.ts index 49208493a..0a51b66da 100644 --- a/apps/server/src/secrets/AgentSecretRequests.ts +++ b/apps/server/src/secrets/AgentSecretRequests.ts @@ -54,6 +54,7 @@ import { OrchestrationEngineService } from "../orchestration/Services/Orchestrat import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; import { ProcessRunner } from "../processRunner.ts"; +import { SecretScrubber } from "./SecretScrubber.ts"; import { type SecretDestinations, makeSecretDestinations } from "./secretDestinations.ts"; export interface AgentSecretRequestsShape { @@ -149,7 +150,15 @@ const isPutAway = (thread: OrchestrationThread | undefined) => thread.archivedAt !== null || (thread.move ?? null) !== null; -export const make = (reads: AgentSecretRequestsReads, destinations: SecretDestinations) => +export const make = ( + reads: AgentSecretRequestsReads, + destinations: SecretDestinations, + /** The registry that hides a saved value if the agent prints it (SecretScrubber). */ + watched: { + readonly watch: (name: string, value: string, requestId: string) => void; + readonly gone: (requestId: string) => void; + } = { watch: () => {}, gone: () => {} }, +) => Effect.gen(function* () { const engine = yield* OrchestrationEngineService; const lock = yield* Semaphore.make(1); @@ -248,6 +257,7 @@ export const make = (reads: AgentSecretRequestsReads, destinations: SecretDestin const removeNow = (threadId: ThreadId, requestId: SecretRequestId) => Effect.gen(function* () { if (!(yield* destinations.removeCommandsFile(threadId, requestId))) return false; + watched.gone(requestId); return yield* recordRemoved(threadId, requestId); }); @@ -462,8 +472,17 @@ export const make = (reads: AgentSecretRequestsReads, destinations: SecretDestin : answerFor(after.request, input.claimId); } - const checked = checkSecretValue(request.use, Redacted.value(input.answer.value)); + const typed = Redacted.value(input.answer.value); + const checked = checkSecretValue(request.use, typed); if (!checked.ok) return { outcome: "rejected", detail: checked.detail }; + // Watched from before the file exists, as typed (not the env file's + // quoted spelling), and still after a failed write: the file can + // outlive it. + watched.watch(request.name, typed, request.requestId); + // A commands key lands with its line endings normalized: watch that too. + if (checked.written !== typed && request.use.kind === "commands") { + watched.watch(request.name, checked.written, request.requestId); + } // Only the committed claim authorizes a write: a request replaced // or cancelled since the read fails it, and nothing is written. @@ -537,6 +556,7 @@ export const make = (reads: AgentSecretRequestsReads, destinations: SecretDestin const timer = timers.get(request.requestId); if (timer !== undefined) yield* Fiber.interrupt(timer); timers.delete(request.requestId); + watched.gone(request.requestId); if (recordRemovals) yield* recordRemoved(threadId, request.requestId); } // A deleted thread has no requests left to retry from: try the folder again. @@ -624,6 +644,7 @@ export const layer = Layer.effect( const snapshots = yield* ProjectionSnapshotQuery; const config = yield* ServerConfig; const processes = yield* ProcessRunner; + const scrubber = yield* SecretScrubber; const destinations = makeSecretDestinations({ agentSecretsDir: config.agentSecretsDir, runGit: (cwd, args) => @@ -666,6 +687,7 @@ export const layer = Layer.effect( all: snapshots.listSecretRequests(), }, destinations, + scrubber, ); }), ); diff --git a/apps/server/src/secrets/SecretScrubber.test.ts b/apps/server/src/secrets/SecretScrubber.test.ts new file mode 100644 index 000000000..c40a20d6a --- /dev/null +++ b/apps/server/src/secrets/SecretScrubber.test.ts @@ -0,0 +1,63 @@ +import * as NodeFs from "node:fs"; +import * as NodeOs from "node:os"; +import * as NodePath from "node:path"; + +import { + type OrchestrationSecretRequest, + SecretRequestId, + ThreadId, + TurnId, +} from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; + +import { readBackSecret } from "./SecretScrubber.ts"; +import { threadKeyOf } from "./secretDestinations.ts"; + +const THREAD = ThreadId.make("thread-1"); +const REQUEST = SecretRequestId.make("4f1c2e8a-0b7d-4c7e-9a1f-3d2b6c5e8f10"); +let home: string; + +beforeEach(() => { + home = NodeFs.realpathSync(NodeFs.mkdtempSync(NodePath.join(NodeOs.tmpdir(), "scrub-read-"))); +}); +afterEach(() => NodeFs.rmSync(home, { recursive: true, force: true })); + +const request = (fields: Partial): OrchestrationSecretRequest => ({ + requestId: REQUEST, + participantId: null, + turnId: TurnId.make("turn-1"), + name: "STRIPE_SECRET_KEY", + reason: "Tests.", + use: { kind: "commands" }, + replaces: false, + status: "saved", + createdAt: "2026-11-19T10:00:00.000Z", + noted: true, + ...fields, +}); + +const read = (entry: OrchestrationSecretRequest) => + Effect.runPromise(readBackSecret(NodePath.join(home, "agent-secrets"), THREAD, entry)); + +describe("reading saved keys back at startup", () => { + it("reads a commands key's file while it exists, and nothing once it was removed", async () => { + const folder = NodePath.join(home, "agent-secrets", threadKeyOf(THREAD), REQUEST); + NodeFs.mkdirSync(folder, { recursive: true }); + NodeFs.writeFileSync(NodePath.join(folder, "value"), "sk_test_51HvQq2abc"); + expect(await read(request({}))).toBe("sk_test_51HvQq2abc"); + expect(await read(request({ removedAt: "2026-11-19T11:00:00.000Z" }))).toBeUndefined(); + }); + + it("reads an env key unquoted, also when a crash left the request uncertain", async () => { + NodeFs.writeFileSync( + NodePath.join(home, ".env.local"), + "A=1\nSTRIPE_SECRET_KEY='abc#123456'\n", + ); + const env = { use: { kind: "env_file", path: ".env.local" }, parent: home } as const; + expect(await read(request({ ...env }))).toBe("abc#123456"); + expect(await read(request({ ...env, status: "uncertain" }))).toBe("abc#123456"); + expect(await read(request({ ...env, status: "declined" }))).toBeUndefined(); + expect(await read(request({ ...env, name: "MISSING_KEY" }))).toBeUndefined(); + }); +}); diff --git a/apps/server/src/secrets/SecretScrubber.ts b/apps/server/src/secrets/SecretScrubber.ts new file mode 100644 index 000000000..ba7fed8e2 --- /dev/null +++ b/apps/server/src/secrets/SecretScrubber.ts @@ -0,0 +1,194 @@ +/** + * Hiding a printed key (docs/design/secret-scrubbing.md): one registry of + * watched values for this computer, in memory only, and the functions every + * hook uses. Values enter when the user presses Save (before the file is + * written) and at startup, read back from their destinations; they stay + * watched until the server stops, since a model can repeat a key after its + * file is gone. Built before the provider layer, so no provider event + * arrives before the read-back is done. + */ +import * as NodeFs from "node:fs/promises"; +import * as NodePath from "node:path"; + +import type { + OrchestrationSecretRequest, + ProviderRuntimeEvent, + ThreadId, +} from "@threadlines/contracts"; +import { readEnvValue } from "@threadlines/shared/secretRequests"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schedule from "effect/Schedule"; + +import { ServerConfig } from "../config.ts"; +import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { threadKeyOf } from "./secretDestinations.ts"; +import { + type HeldText, + type HoldResult, + makeNoticeMemory, + makeRuntimeEventScrubber, + makeSecretScrubberCore, + type Scrubbed, +} from "./secretScrubberCore.ts"; + +export interface SecretScrubberShape { + /** + * Starts watching a value the user saved under `name`, for `requestId` + * while its file holds it; false when it can't be hidden safely. + */ + readonly watch: (name: string, value: string, requestId?: string) => boolean; + /** A request's file is gone: its value stays watched, and goes first past the limit. */ + readonly gone: (requestId: string) => void; + /** Hides watched values in a string. */ + readonly scrubText: (text: string) => Scrubbed; + /** + * Hides whole watched values in every string and member name; the same + * value when nothing matched. Never cuts: for text already joined (what + * ingestion stores), not a snapshot still being written. + */ + readonly scrubDeep: (value: A) => A; + /** The names of the watched values a JSON-like value holds, for callers that refuse instead. */ + readonly contains: (value: unknown) => ReadonlyArray; + /** A provider event in, the events to publish in order out: the event, then any notice. */ + readonly scrubRuntimeEvent: (event: ProviderRuntimeEvent) => ReadonlyArray; + /** + * A piece ingestion appends to a buffer, with that buffer's held state: + * what to send now, what to hold next. See secretScrubberCore `holdPiece`. + */ + readonly holdPiece: (state: HeldText | undefined, piece: string) => HoldResult; + /** What a buffer keeps after releasing its held tail, so a reopened buffer can't complete a value. */ + readonly afterRelease: (state: HeldText | undefined) => HeldText | undefined; + /** The notice's line for a name; neutral when the line itself would hold a watched value. */ + readonly noticeLine: (name: string) => string; + /** The names not yet noticed in this thread's turn; they count as noticed from now. */ + readonly takeNotices: ( + threadId: string, + turnId: string | undefined, + names: Iterable, + ) => ReadonlyArray; + /** An answer to a question or approval, with the strings it was shown hidden put back. */ + readonly restoreAnswer: (session: string, requestId: string, answer: A) => A; +} + +export class SecretScrubber extends Context.Service()( + "threadlines/secrets/SecretScrubber", +) {} + +/** A scrubber over a fresh registry, for tests and for the layer. */ +export function makeSecretScrubber(): SecretScrubberShape { + const core = makeSecretScrubberCore(); + const notices = makeNoticeMemory(); + const runtime = makeRuntimeEventScrubber(core, notices); + return { + watch: core.watch, + gone: core.gone, + scrubText: (text) => core.scrubText(text), + scrubDeep: (value: A) => core.scrubDeep(value, new Set()) as A, + contains: core.contains, + scrubRuntimeEvent: runtime.scrubRuntimeEvent, + restoreAnswer: runtime.restoreAnswer, + holdPiece: core.holdPiece, + afterRelease: core.afterRelease, + noticeLine: core.noticeLine, + takeNotices: (threadId, turnId, names) => notices.take(threadId, turnId, names), + }; +} + +const readText = (path: string) => + Effect.tryPromise({ + try: () => NodeFs.readFile(path, "utf8"), + catch: () => "unreadable" as const, + }).pipe(Effect.option); + +/** + * The value a request saved, read back from where it went: a `commands` + * key's file while it exists; an env key's `NAME=` line in the file it is + * bound to. Undefined when it can't be read (gone, renamed, a form the reader + * doesn't know). + */ +export const readBackSecret = ( + agentSecretsDir: string, + threadId: ThreadId, + request: OrchestrationSecretRequest, +) => + Effect.gen(function* () { + if (request.use.kind === "commands") { + if (request.status !== "saved" || request.removedAt !== undefined) return undefined; + const file = NodePath.join( + agentSecretsDir, + threadKeyOf(threadId), + request.requestId, + "value", + ); + const text = yield* readText(file); + return text._tag === "Some" ? text.value : undefined; + } + // A crash after the rename leaves the value in the file with the request + // never marked saved: `claimed` before recovery, `uncertain` after. + if (!["saved", "uncertain", "claimed"].includes(request.status)) return undefined; + if (request.parent === undefined) return undefined; + const base = request.use.path.split(/[\\/]/).findLast((segment) => segment.length > 0); + if (base === undefined) return undefined; + const text = yield* readText(NodePath.join(request.parent, base)); + return text._tag === "Some" ? readEnvValue(text.value, request.name) : undefined; + }); + +/** + * The registry, filled at startup from every live thread's saved keys before + * the provider layer takes any event. A failed read is retried a few times + * right away, then in the background until it works: a key left unwatched + * is a key printed whole. + */ +export const layer = Layer.effect( + SecretScrubber, + Effect.gen(function* () { + const scrubber = makeSecretScrubber(); + const snapshots = yield* ProjectionSnapshotQuery; + const config = yield* ServerConfig; + const load = Effect.gen(function* () { + const threads = yield* snapshots.listSecretRequests(); + for (const { threadId, secretRequests } of threads) { + for (const request of secretRequests) { + const value = yield* readBackSecret(config.agentSecretsDir, threadId, request); + if (value === undefined) { + if (request.status === "saved") { + yield* Effect.logDebug("a saved key couldn't be read back to watch", { + threadId, + requestId: request.requestId, + }); + } + continue; + } + scrubber.watch( + request.name, + value, + request.status === "saved" ? request.requestId : undefined, + ); + } + } + }); + const loaded = yield* load.pipe( + Effect.retry({ times: 4, schedule: Schedule.exponential(Duration.millis(100)) }), + Effect.as(true), + Effect.catchCause((cause) => + Effect.logError("couldn't read saved keys to watch; trying again in the background", { + cause, + }).pipe(Effect.as(false)), + ), + ); + if (!loaded) { + yield* load.pipe( + Effect.retry(Schedule.spaced(Duration.seconds(30))), + Effect.ignore, + Effect.forkScoped, + ); + } + return scrubber; + }), +); + +/** An empty registry, for tests that build the provider service without the server's layers. */ +export const layerTest = Layer.sync(SecretScrubber, makeSecretScrubber); diff --git a/apps/server/src/secrets/secretScrubberCore.test.ts b/apps/server/src/secrets/secretScrubberCore.test.ts new file mode 100644 index 000000000..ffcf8ac85 --- /dev/null +++ b/apps/server/src/secrets/secretScrubberCore.test.ts @@ -0,0 +1,280 @@ +import { EventId, type ProviderRuntimeEvent, ThreadId, TurnId } from "@threadlines/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { makeSecretScrubber } from "./SecretScrubber.ts"; + +const KEY = "sk_test_51HvQq2abc"; +const SESSION = ThreadId.make("session-1"); +const TURN = TurnId.make("turn-1"); +let counter = 0; + +const base = () => ({ + eventId: EventId.make(`event-${(counter += 1)}`), + provider: "codex", + threadId: SESSION, + createdAt: "2026-11-19T10:00:00.000Z", + turnId: TURN, +}); + +const delta = ( + text: string, + options?: { + readonly itemId?: string; + readonly streamKind?: string; + readonly summaryIndex?: number; + }, +) => + ({ + ...base(), + type: "content.delta", + itemId: options?.itemId ?? "item-1", + payload: { + streamKind: options?.streamKind ?? "command_output", + delta: text, + ...(options?.summaryIndex !== undefined ? { summaryIndex: options.summaryIndex } : {}), + }, + raw: { source: "codex.app-server.notification", method: "item/delta", payload: { b64: "x" } }, + }) as unknown as ProviderRuntimeEvent; + +const event = (type: string, payload: unknown, extra?: object) => + ({ ...base(), type, payload, ...extra }) as unknown as ProviderRuntimeEvent; + +function watching(...values: ReadonlyArray) { + const scrubber = makeSecretScrubber(); + for (const [name, value] of values) scrubber.watch(name, value); + return scrubber; +} + +describe("hiding watched values in text", () => { + it("hides a whole value, its JSON-escaped and URL-encoded forms, in strings and member names", () => { + const quoted = 'p"ss/w+rd=12'; + const scrubber = watching(["STRIPE_SECRET_KEY", KEY], ["DB_PASSWORD", quoted]); + const input = { + out: `export STRIPE_SECRET_KEY=${KEY}`, + nested: [{ json: JSON.stringify({ password: quoted }) }], + url: `https://x.test/?p=${encodeURIComponent(quoted)}`, + [KEY]: "as a member name", + }; + const result = scrubber.scrubDeep(input); + const text = JSON.stringify(result); + expect(text).not.toContain(KEY); + expect(text).not.toContain("ss/w+rd"); + expect(text).not.toContain(encodeURIComponent(quoted)); + expect(result.out).toBe("export STRIPE_SECRET_KEY=[STRIPE_SECRET_KEY hidden]"); + expect(Object.keys(result)).toContain("[STRIPE_SECRET_KEY hidden]"); + }); + + it("hands back the same object when nothing matched, and never watches a short or plain value", () => { + const scrubber = watching(["A", "localhost"], ["B", "12345678"], ["C", "ab1"], ["D", KEY]); + const input = { text: "localhost:12345678 ab1", list: ["ok"] }; + expect(scrubber.scrubDeep(input)).toBe(input); + expect(scrubber.watch("E", "]1234567x")).toBe(false); + }); + + it("finds a long value by its head and hides it as far as the text agrees, even cut short", () => { + const pem = `-----BEGIN KEY-----\n${"A1b2C3d4".repeat(100)}\n-----END KEY-----`; + const scrubber = watching(["PEM", pem]); + expect(scrubber.scrubText(`key: ${pem} done`).text).toBe("key: [PEM hidden] done"); + const cut = pem.slice(0, 500); + expect(scrubber.scrubText(`partial ${cut}`).text).toBe("partial [PEM hidden]"); + }); + + it("cuts a provider snapshot that stops 4 or more characters into a value, not 3", () => { + const scrubber = watching(["K", KEY]); + const snapshot = (text: string) => + scrubber.scrubRuntimeEvent(event("item.updated", { detail: text }))[0]?.payload; + expect(snapshot(`x ${KEY.slice(0, 4)}`)).toEqual({ detail: "x " }); + expect(snapshot(`x ${KEY.slice(0, 3)}`)).toEqual({ detail: `x ${KEY.slice(0, 3)}` }); + // Text already joined is never cut: only whole values go. + expect(scrubber.scrubDeep({ text: `x ${KEY.slice(0, 4)}` }).text).toBe(`x ${KEY.slice(0, 4)}`); + }); + + it("gives two values under one name different placeholders", () => { + const scrubber = watching(["K", KEY], ["K", "sk_live_99zzQQ11"]); + expect(scrubber.scrubText(`${KEY} sk_live_99zzQQ11`).text).toBe("[K hidden] [K 2 hidden]"); + }); +}); + +describe("the registry", () => { + it("past 200 values drops one whose file is gone, before an older one still live", () => { + const scrubber = makeSecretScrubber(); + scrubber.watch("LIVE", "sk_live_0000aaaa", "request-live"); + scrubber.watch("GONE", "sk_gone_1111bbbb", "request-gone"); + scrubber.gone("request-gone"); + for (let index = 0; index < 199; index += 1) { + scrubber.watch(`K${index}`, `sk_fill_${index}_zz9`, `request-${index}`); + } + expect(scrubber.scrubText("sk_live_0000aaaa").text).toBe("[LIVE hidden]"); + expect(scrubber.scrubText("sk_gone_1111bbbb").text).toBe("sk_gone_1111bbbb"); + }); +}); + +describe("nothing watched", () => { + it("hands back the very same event, alone", () => { + const scrubber = makeSecretScrubber(); + const piece = delta(`token ${KEY}`); + const out = scrubber.scrubRuntimeEvent(piece); + expect(out).toHaveLength(1); + expect(out[0]).toBe(piece); + }); +}); + +describe("holding a buffer's pieces (ingestion's holder)", () => { + /** Runs pieces through one buffer's holder, releasing at the end as ingestion does. */ + function through(scrubber: ReturnType, pieces: ReadonlyArray) { + let state: Parameters[0]; + let out = ""; + for (const piece of pieces) { + const held = scrubber.holdPiece(state, piece); + out += held.out; + state = held.state; + } + return out + (state?.held ?? ""); + } + + it("hides a value split across pieces, holding only what could start it", () => { + const scrubber = watching(["K", KEY]); + expect(through(scrubber, ["total ", "s", "k_te", "st_51Hv", "Qq2abc and more", " end"])).toBe( + "total [K hidden] and more end", + ); + }); + + it("gives back a held tail that turned out not to be a value, intact and in order", () => { + const scrubber = watching(["K", KEY]); + expect(through(scrubber, ["build s", "k_tea is fine"])).toBe("build sk_tea is fine"); + expect(through(scrubber, ["Done with the tests"])).toBe("Done with the tests"); + }); + + it("follows a long value arriving one character at a time", () => { + const pem = `-----BEGIN-----${"x9".repeat(400)}`; + const scrubber = watching(["PEM", pem]); + expect(through(scrubber, [...`>> ${pem} <<`])).toBe(">> [PEM hidden] <<"); + }); + + it("keeps a released tail so a piece that reopens the message can't complete the key", () => { + const scrubber = watching(["K", KEY]); + const first = scrubber.holdPiece(undefined, "pay sk_te"); + expect(first.out).toBe("pay "); + // The message completes: its held tail is sent as it is. + expect(first.state?.held).toBe("sk_te"); + const reopened = scrubber.holdPiece(scrubber.afterRelease(first.state), "st_51HvQq2abc done"); + expect(reopened.out).toBe("[K hidden] done"); + expect(reopened.names).toEqual(["K"]); + }); + + it("never lets a notice line spell out a watched value", () => { + const scrubber = watching(["TOKEN", KEY], ["OTHER", "Hid TOKEN"]); + expect(scrubber.noticeLine("TOKEN")).toBe("Hid a saved key in the agent's output"); + expect(watching(["TOKEN", KEY]).noticeLine("TOKEN")).toBe("Hid TOKEN in the agent's output"); + }); + + it("holds nothing when nothing is watched", () => { + const scrubber = makeSecretScrubber(); + expect(scrubber.holdPiece(undefined, "sk_te")).toEqual({ + out: "sk_te", + state: undefined, + names: [], + }); + }); +}); + +describe("the provider hook", () => { + it("hides a whole value in a piece and the provider's message, and never holds or cuts a piece", () => { + const scrubber = watching(["K", KEY]); + const [whole] = scrubber.scrubRuntimeEvent(delta(`total ${KEY} done`)); + expect(whole?.type === "content.delta" && whole.payload.delta).toBe("total [K hidden] done"); + expect(whole?.raw?.payload).toEqual({ hidden: true }); + const piece = delta("ends with sk_te"); + expect(scrubber.scrubRuntimeEvent(piece)).toEqual([piece]); + }); + + it("notices a hidden key once per name per turn", () => { + const scrubber = watching(["K", KEY]); + const first = scrubber.scrubRuntimeEvent(delta(KEY)); + const second = scrubber.scrubRuntimeEvent(delta(KEY)); + expect(first.map((entry) => entry.type)).toEqual(["content.delta", "runtime.warning"]); + expect(second.map((entry) => entry.type)).toEqual(["content.delta"]); + }); +}); + +describe("questions and approvals", () => { + it("shows a question hidden and puts the original back in its answer, and nothing else", () => { + const scrubber = watching(["K", KEY]); + const question = `Use ${KEY} for prod?`; + const [shown] = scrubber.scrubRuntimeEvent( + event( + "user-input.requested", + { questions: [{ id: question, question, options: [{ label: "Yes", description: "" }] }] }, + { requestId: "request-1" }, + ), + ); + const hidden = (shown?.payload as { questions: Array<{ id: string }> } | undefined) + ?.questions[0]?.id; + expect(hidden).toBe("Use [K hidden] for prod?"); + const answer = scrubber.restoreAnswer(SESSION, "request-1", { + [hidden ?? ""]: "Yes", + other: "[K hidden]", + }); + expect(answer).toEqual({ [question]: "Yes", other: "[K hidden]" }); + }); +}); + +describe("review fixes", () => { + it("hides the provider's whole message when a clean piece carries the key in it", () => { + const scrubber = watching(["K", KEY]); + const piece = { + ...delta("ok"), + raw: { source: "claude.sdk.message", payload: { results: [KEY, "ok"] } }, + } as unknown as ProviderRuntimeEvent; + const [out] = scrubber.scrubRuntimeEvent(piece); + expect(JSON.stringify(out)).not.toContain(KEY); + expect(out?.type === "content.delta" && out.payload.delta).toBe("ok"); + }); + + it("never lets a placeholder or notice spell out another watched key", () => { + const scrubber = watching(["FIRST", "SERVICE_TOKEN"], ["SERVICE_TOKEN", KEY]); + const out = scrubber.scrubRuntimeEvent(event("item.updated", { detail: `token ${KEY}` })); + const text = JSON.stringify(out); + expect(text).not.toContain("SERVICE_TOKEN"); + expect(text).toContain("[a saved key hidden]"); + }); + + it("never cuts a member name or a question, and puts back only what a whole match rewrote", () => { + const scrubber = watching(["K", "message-1234"], ["K2", "ABCD1234"]); + const [warning] = scrubber.scrubRuntimeEvent(event("runtime.warning", { message: "ok" })); + expect(warning?.payload).toEqual({ message: "ok" }); + const [shown] = scrubber.scrubRuntimeEvent( + event("request.opened", { decision: "acceptABCD" }, { requestId: "r3" }), + ); + // A question's or approval's text is never cut: some providers key answers by it. + expect(shown?.payload).toEqual({ decision: "acceptABCD" }); + expect(scrubber.restoreAnswer(SESSION, "r3", "accept")).toBe("accept"); + }); + + it("keeps two questions apart when hiding makes them the same text", () => { + const value = "abc/12345"; + const scrubber = watching(["K", value]); + const first = `Use ${value}?`; + const second = `Use ${encodeURIComponent(value)}?`; + const [shown] = scrubber.scrubRuntimeEvent( + event( + "user-input.requested", + { + questions: [ + { id: first, question: first }, + { id: second, question: second }, + ], + }, + { requestId: "r4" }, + ), + ); + const ids = ( + (shown?.payload as { questions: Array<{ id: string }> } | undefined)?.questions ?? [] + ).map((question) => question.id); + expect(new Set(ids).size).toBe(2); + expect(scrubber.restoreAnswer(SESSION, "r4", { [ids[0]!]: "A", [ids[1]!]: "B" })).toEqual({ + [first]: "A", + [second]: "B", + }); + }); +}); diff --git a/apps/server/src/secrets/secretScrubberCore.ts b/apps/server/src/secrets/secretScrubberCore.ts new file mode 100644 index 000000000..42ce89652 --- /dev/null +++ b/apps/server/src/secrets/secretScrubberCore.ts @@ -0,0 +1,620 @@ +/** + * The matching behind hiding a printed key (docs/design/secret-scrubbing.md): + * a registry of watched values, each with its forms, and the functions every + * hook uses to replace them with `[NAME hidden]`. Synchronous and pure apart + * from its own state, so the provider path pays no effect overhead and the + * rules can be tested directly. Nothing here logs a value. + */ +import { randomUUID } from "node:crypto"; + +import { EventId, type ProviderRuntimeEvent, type ThreadId } from "@threadlines/contracts"; +import { isWatchableSecret, secretPlaceholder } from "@threadlines/shared/secretRequests"; +import { parseSessionKey } from "@threadlines/shared/threadParticipants"; + +/** A long value is found by its first characters, then hidden as far as the text agrees. */ +const HEAD_LENGTH = 256; +/** The most values watched at once; past it the oldest with no live file goes first. */ +export const MAX_WATCHED_SECRETS = 200; +/** A snapshot cut partway through a value loses a tail at least this long. */ +const MIN_CUT_TAIL = 4; +/** What stands in for a key whose own name would spell out another watched key. */ +const NEUTRAL_NAME = "a saved key"; + +interface Entry { + readonly name: string; + readonly value: string; + readonly ordinal: number; + readonly forms: ReadonlyArray
; + /** The requests whose file still holds it; none: it is kept only because a model may repeat it. */ + readonly requestIds: Set; + /** What replaces it, and the name a notice uses: never one that holds a watched value. */ + placeholder: string; + shownName: string; +} + +interface Form { + readonly entry: Entry; + readonly text: string; + readonly head: string; +} + +interface Match { + readonly start: number; + end: number; + readonly entry: Entry; + /** The match ran to the end of the text partway through a long value. */ + open: OpenMatch | undefined; +} + +interface OpenMatch { + readonly form: Form; + readonly offset: number; +} + +/** + * What a buffer held back: the tail that could start a watched value, and a + * long value still being matched across pieces. Never a whole value. + */ +export interface HeldText { + readonly held: string; + readonly open: OpenMatch | undefined; + /** Text already sent that a value could continue from: kept after a release. */ + readonly sent?: string; +} + +/** A piece after holding: what to send now, what the buffer holds next, the names it hid. */ +export interface HoldResult { + readonly out: string; + readonly state: HeldText | undefined; + readonly names: ReadonlyArray; +} + +/** A string with its watched values hidden, and the names it hid. */ +export interface Scrubbed { + readonly text: string; + readonly names: ReadonlyArray; +} + +export interface ScrubDeepOptions { + /** + * Cut a string value (never a member name) that stops 4 or more characters + * into a watched value: a snapshot of output still being written. + */ + readonly cutTail?: boolean; + /** + * Hears each string a whole match rewrote, with its original, and returns + * the string to use: questions keep two rewritten texts apart this way. + */ + readonly changed?: (hidden: string, original: string) => string; +} + +/** The forms a value can take in text: as saved, JSON-escaped, URL-encoded. */ +function formsOf(value: string): ReadonlyArray { + const forms = new Set([value]); + forms.add(JSON.stringify(value).slice(1, -1)); + forms.add(encodeURIComponent(value)); + return [...forms]; +} + +export function makeSecretScrubberCore() { + const entries: Entry[] = []; + let forms: Form[] = []; + /** First characters of every form's head: a cheap filter for held tails. */ + let firstCharacters = new Set(); + let longestHead = 0; + + const holdsWatched = (text: string) => forms.some((form) => text.includes(form.text)); + + const rebuild = () => { + forms = entries.flatMap((entry) => entry.forms); + firstCharacters = new Set(forms.map((form) => form.head[0] ?? "")); + longestHead = Math.max(0, ...forms.map((form) => form.head.length)); + // A placeholder or notice must never spell out another watched key, as a + // name chosen equal to one would. + for (const entry of entries) { + const placeholder = secretPlaceholder(entry.name, entry.ordinal); + const safe = !holdsWatched(placeholder); + entry.placeholder = safe ? placeholder : secretPlaceholder(NEUTRAL_NAME, entry.ordinal); + entry.shownName = safe ? entry.name : NEUTRAL_NAME; + } + }; + + /** + * Starts watching a value saved under `name`, for `requestId` while its + * file holds it. A value that can't be hidden safely is not watched + * (isWatchableSecret). Returns whether it is. + */ + const watch = (name: string, value: string, requestId?: string): boolean => { + if (!isWatchableSecret(name, value) || secretPlaceholder(NEUTRAL_NAME).includes(value)) { + return false; + } + const existing = entries.find((entry) => entry.value === value && entry.name === name); + if (existing !== undefined) { + if (requestId !== undefined) existing.requestIds.add(requestId); + return true; + } + const ordinal = entries.filter((entry) => entry.name === name).length + 1; + const entry: Entry = { + name, + value, + ordinal, + forms: [], + requestIds: new Set(requestId === undefined ? [] : [requestId]), + placeholder: "", + shownName: name, + }; + (entry as { forms: ReadonlyArray }).forms = formsOf(value).map((text) => ({ + entry, + text, + head: text.slice(0, HEAD_LENGTH), + })); + entries.push(entry); + if (entries.length > MAX_WATCHED_SECRETS) { + const gone = entries.findIndex((candidate) => candidate.requestIds.size === 0); + entries.splice(gone === -1 ? 0 : gone, 1); + } + rebuild(); + return true; + }; + + /** A request's file is gone: its value is still watched, but goes first past the limit. */ + const gone = (requestId: string) => { + for (const entry of entries) entry.requestIds.delete(requestId); + }; + + /** Every place a watched form starts in `text`, non-overlapping, earliest first. */ + const findMatches = (text: string): Match[] => { + const found: Match[] = []; + for (const form of forms) { + let from = 0; + while (from <= text.length - form.head.length) { + const at = text.indexOf(form.head, from); + if (at === -1) break; + let end = at + form.head.length; + while ( + end < text.length && + end - at < form.text.length && + text[end] === form.text[end - at] + ) { + end += 1; + } + const open = + end === text.length && end - at < form.text.length + ? { form, offset: end - at } + : undefined; + found.push({ start: at, end, entry: form.entry, open }); + from = end; + } + } + if (found.length <= 1) return found; + found.sort((a, b) => a.start - b.start || b.end - a.end); + const chosen: Match[] = []; + for (const match of found) { + const last = chosen.at(-1); + if (last === undefined || match.start >= last.end) { + chosen.push({ ...match }); + } else if (match.end > last.end) { + last.end = match.end; + last.open = match.open; + } + } + return chosen; + }; + + const replaceMatches = (text: string, matches: ReadonlyArray, upTo = text.length) => { + let out = ""; + let at = 0; + for (const match of matches) { + out += text.slice(at, match.start) + match.entry.placeholder; + at = match.end; + } + return out + text.slice(at, upTo); + }; + + /** + * The length of the longest tail of `text` that is the start of a watched + * form's head (and shorter than the head), at least `minimum` long. + */ + const startingTail = (text: string, minimum: number): number => { + const limit = Math.min(text.length, longestHead - 1); + for (let length = limit; length >= minimum; length -= 1) { + const tail = text.slice(text.length - length); + if (!firstCharacters.has(tail[0] ?? "")) continue; + if (forms.some((form) => form.head.length > length && form.head.startsWith(tail))) { + return length; + } + } + return 0; + }; + + const namesOf = (matches: ReadonlyArray) => [ + ...new Set(matches.map((match) => match.entry.shownName)), + ]; + + /** + * Hides watched values in a string. With `cutTail`, a string that stops + * 4 or more characters into a value (a snapshot of output still being + * written) loses that tail; the next snapshot holds the whole value. + */ + const scrubText = (text: string, options?: { readonly cutTail?: boolean }): Scrubbed => { + if (forms.length === 0 || text.length === 0) return { text, names: [] }; + const matches = findMatches(text); + const lastEnd = matches.at(-1)?.end ?? 0; + const cut = + options?.cutTail === true && matches.at(-1)?.open === undefined + ? startingTail(text.slice(lastEnd), MIN_CUT_TAIL) + : 0; + if (matches.length === 0 && cut === 0) return { text, names: [] }; + return { text: replaceMatches(text, matches, text.length - cut), names: namesOf(matches) }; + }; + + /** + * Hides watched values in every string and member name of a JSON-like + * value. The same object comes back when nothing matched. + */ + const scrubDeep = ( + value: unknown, + names: Set, + options?: ScrubDeepOptions, + isKey = false, + ): unknown => { + if (forms.length === 0) return value; + if (typeof value === "string") { + const scrubbed = scrubText(value, { cutTail: options?.cutTail === true && !isKey }); + if (scrubbed.text === value) return value; + for (const name of scrubbed.names) names.add(name); + return scrubbed.names.length > 0 && options?.changed !== undefined + ? options.changed(scrubbed.text, value) + : scrubbed.text; + } + if (Array.isArray(value)) { + let copy: unknown[] | undefined; + value.forEach((item, index) => { + const next = scrubDeep(item, names, options); + if (next !== item) { + copy ??= [...value]; + copy[index] = next; + } + }); + return copy ?? value; + } + if (value !== null && typeof value === "object") { + let copy: Record | undefined; + const record = value as Record; + for (const [key, item] of Object.entries(record)) { + const nextItem = scrubDeep(item, names, options); + const nextKey = scrubDeep(key, names, options, true) as string; + if (nextItem === item && nextKey === key) continue; + copy ??= { ...record }; + if (nextKey !== key) { + delete copy[key]; + let unique = nextKey; + for (let suffix = 2; unique in copy; suffix += 1) unique = `${nextKey} ${suffix}`; + copy[unique] = nextItem; + } else { + copy[key] = nextItem; + } + } + return copy ?? value; + } + return value; + }; + + /** The names of watched values a JSON-like value holds: for callers that refuse instead. */ + const contains = (value: unknown): ReadonlyArray => { + const names = new Set(); + scrubDeep(value, names); + return [...names]; + }; + + /** + * One piece of text ingestion appends to a buffer (a message's text, a + * command's output): joined with what the buffer held back, its whole + * values hidden, and the tail that could start a value held back again. + * The state lives with the buffer it belongs to; release `state.held` as it + * is when the buffer closes. + */ + const holdPiece = (state: HeldText | undefined, piece: string): HoldResult => { + if (forms.length === 0 && state === undefined) { + return { out: piece, state: undefined, names: [] }; + } + let rest = piece; + let open = state?.open; + if (open !== undefined) { + const { form, offset } = open; + let index = 0; + while ( + index < rest.length && + offset + index < form.text.length && + rest[index] === form.text[offset + index] + ) { + index += 1; + } + open = + index === rest.length && offset + index < form.text.length + ? { form, offset: offset + index } + : undefined; + rest = rest.slice(index); + } + // Text already sent that a value may still continue from (a message + // reopened after its tail was released): matched against, never re-sent. + const sent = state?.sent ?? ""; + const joined = (state?.held ?? "") + rest; + const full = sent + joined; + const matches = findMatches(full) + .filter((match) => match.end > sent.length) + .map((match) => ({ + ...match, + start: Math.max(match.start, sent.length) - sent.length, + end: match.end - sent.length, + })); + const last = matches.at(-1); + if (last !== undefined) open = last.open; + const lastEnd = sent.length + (last?.end ?? 0); + const tailLength = open !== undefined ? 0 : startingTail(full.slice(lastEnd), 1); + const tailStart = full.length - tailLength; + const heldFrom = Math.max(tailStart, sent.length); + const held = full.slice(heldFrom); + const stillSent = + tailLength > 0 && tailStart < sent.length ? full.slice(tailStart, sent.length) : ""; + return { + out: replaceMatches(joined, matches, joined.length - held.length), + state: + held.length === 0 && open === undefined && stillSent.length === 0 + ? undefined + : { held, open, ...(stillSent.length > 0 ? { sent: stillSent } : {}) }, + names: namesOf(matches), + }; + }; + + /** + * After a buffer released its held tail (its message completed), what to + * keep so a piece that reopens it can't complete a value the tail started. + */ + const afterRelease = (state: HeldText | undefined): HeldText | undefined => { + const sent = (state?.sent ?? "") + (state?.held ?? ""); + return sent.length === 0 ? undefined : { held: "", open: undefined, sent }; + }; + + /** A notice's line, or a neutral one when the line itself would hold a watched value. */ + const noticeLine = (name: string): string => { + const line = secretHiddenNotice(name); + return scrubText(line).text === line ? line : secretHiddenNotice(NEUTRAL_NAME); + }; + + return { + holdPiece, + afterRelease, + noticeLine, + watch, + gone, + scrubText, + scrubDeep, + contains, + findMatches, + replaceMatches, + startingTail, + get size() { + return entries.length; + }, + }; +} + +export type SecretScrubberCore = ReturnType; + +// --------------------------------------------------------------------------- +// Provider events: each one alone, plus question memory and the notice. + +/** The provider's own message, replaced once the event hid anything. */ +const hiddenRaw = (event: ProviderRuntimeEvent): ProviderRuntimeEvent["raw"] => + event.raw === undefined ? undefined : { ...event.raw, payload: { hidden: true } }; + +/** The notice's line, short enough for one row; the advice is its detail. */ +export const secretHiddenNotice = (name: string) => `Hid ${name} in the agent's output`; +export const SECRET_HIDDEN_DETAIL = "The agent may have seen it. Replace the key if that matters."; + +/** The kind the timeline gives its own row (session-logic.ts). */ +export const SECRET_HIDDEN_WARNING_KIND = "secret-hidden"; + +/** Names already noticed per thread and turn, shared by the provider hook and ingestion. */ +export function makeNoticeMemory() { + const noticed = new Map>(); + return { + /** The names not yet noticed in this thread's turn; they count as noticed now. */ + take(threadId: string, turnId: string | undefined, names: Iterable): string[] { + const key = `${threadId}\u0000${turnId ?? ""}`; + const seen = noticed.get(key) ?? new Set(); + noticed.set(key, seen); + const fresh = [...names].filter((name) => !seen.has(name)); + for (const name of fresh) seen.add(name); + return fresh; + }, + forgetThread(threadId: string) { + const prefix = `${threadId}\u0000`; + for (const key of noticed.keys()) if (key.startsWith(prefix)) noticed.delete(key); + }, + }; +} + +export type NoticeMemory = ReturnType; + +/** Every string and member name in a JSON-like value. */ +function stringsIn(value: unknown, into = new Set()): Set { + if (typeof value === "string") into.add(value); + else if (Array.isArray(value)) for (const item of value) stringsIn(item, into); + else if (value !== null && typeof value === "object") { + for (const [key, item] of Object.entries(value)) { + into.add(key); + stringsIn(item, into); + } + } + return into; +} + +const isStreamPiece = ( + event: ProviderRuntimeEvent, +): event is Extract< + ProviderRuntimeEvent, + { readonly type: "content.delta" | "turn.proposed.delta" } +> => event.type === "content.delta" || event.type === "turn.proposed.delta"; + +/** + * The provider hook: every event alone, before anything stores, logs or sends + * it. Whole values are hidden in `payload` and `raw.payload`; a stream piece + * is never cut, since only ingestion knows which pieces it joins and holds + * them there. A question or approval remembers what it was shown with, for + * the answer. + */ +export function makeRuntimeEventScrubber(core: SecretScrubberCore, notices: NoticeMemory) { + /** Per session and request: each string a question or approval was shown with, and its original. */ + const originals = new Map>(); + const requestKey = (session: string, requestId: string) => `${session}\u0000${requestId}`; + + const scrubPiece = ( + event: Extract< + ProviderRuntimeEvent, + { readonly type: "content.delta" | "turn.proposed.delta" } + >, + names: Set, + ): ProviderRuntimeEvent => { + const scrubbed = core.scrubText(event.payload.delta); + for (const name of scrubbed.names) names.add(name); + const rawPayload = + event.raw === undefined ? undefined : core.scrubDeep(event.raw.payload, names); + if (scrubbed.text === event.payload.delta && rawPayload === event.raw?.payload) return event; + return { + ...event, + payload: { ...event.payload, delta: scrubbed.text }, + raw: hiddenRaw(event), + } as ProviderRuntimeEvent; + }; + + /** Any other event: hide in `payload` and `raw.payload`; remember what a question was shown with. */ + const scrubWhole = (event: ProviderRuntimeEvent, names: Set): ProviderRuntimeEvent => { + const remembers = + (event.type === "request.opened" || event.type === "user-input.requested") && + event.requestId !== undefined; + const shown = remembers ? new Map() : undefined; + // Every text the question already holds: a hidden one must not read the same. + const taken = remembers ? stringsIn(event.payload) : undefined; + // Two texts hidden to the same string stay two, and never match a text the + // question already had: the answer is keyed by them. + const changed = shown + ? (hidden: string, original: string) => { + let unique = hidden; + for ( + let suffix = 2; + (shown.has(unique) && shown.get(unique) !== original) || taken?.has(unique) === true; + suffix += 1 + ) { + unique = `${hidden} (${suffix})`; + } + shown.set(unique, original); + return unique; + } + : undefined; + const payload = core.scrubDeep(event.payload, names, { + // A question's text is its id for some providers: never cut there. + cutTail: !remembers, + ...(changed !== undefined ? { changed } : {}), + }); + const rawPayload = + event.raw === undefined ? undefined : core.scrubDeep(event.raw.payload, names); + if (shown !== undefined && shown.size > 0 && event.requestId !== undefined) { + originals.set(requestKey(event.threadId, event.requestId), shown); + } + if (payload === event.payload && rawPayload === event.raw?.payload) return event; + return { + ...event, + payload, + ...(event.raw === undefined + ? {} + : { + raw: + payload !== event.payload ? hiddenRaw(event) : { ...event.raw, payload: rawPayload }, + }), + } as ProviderRuntimeEvent; + }; + + const forget = (event: ProviderRuntimeEvent) => { + if ( + (event.type === "request.resolved" || event.type === "user-input.resolved") && + event.requestId !== undefined + ) { + originals.delete(requestKey(event.threadId, event.requestId)); + } + if (event.type === "session.exited") { + const prefix = `${event.threadId}\u0000`; + for (const key of originals.keys()) if (key.startsWith(prefix)) originals.delete(key); + } + }; + + /** One notice per name per turn, after the event that hid it. */ + const noticesFor = (event: ProviderRuntimeEvent, names: Set): ProviderRuntimeEvent[] => { + if (names.size === 0) return []; + const thread = parseSessionKey(event.threadId as ThreadId).threadId; + return notices.take(thread, event.turnId, names).map( + (name) => + ({ + eventId: EventId.make(randomUUID()), + provider: event.provider, + ...(event.providerInstanceId !== undefined + ? { providerInstanceId: event.providerInstanceId } + : {}), + threadId: event.threadId, + createdAt: event.createdAt, + ...(event.turnId !== undefined ? { turnId: event.turnId } : {}), + type: "runtime.warning", + payload: { + message: core.noticeLine(name), + warningKind: SECRET_HIDDEN_WARNING_KIND, + detail: SECRET_HIDDEN_DETAIL, + }, + }) as ProviderRuntimeEvent, + ); + }; + + /** + * One provider event in, the events to publish in order out: the event + * with whole watched values hidden, and a notice after it. Nothing + * watched: the same event, alone. + */ + const scrubRuntimeEvent = (event: ProviderRuntimeEvent): ReadonlyArray => { + if (core.size === 0) { + if (originals.size > 0) forget(event); + return [event]; + } + const names = new Set(); + const scrubbed = isStreamPiece(event) ? scrubPiece(event, names) : scrubWhole(event, names); + forget(event); + const after = noticesFor(event, names); + return after.length === 0 ? [scrubbed] : [scrubbed, ...after]; + }; + + /** + * An answer on its way back to the provider: any string or member name + * that equals one the question was shown with is put back to the original. + */ + const restoreAnswer = (session: string, requestId: string, answer: A): A => { + const changed = originals.get(requestKey(session, requestId)); + if (changed === undefined) return answer; + const restore = (value: unknown): unknown => { + if (typeof value === "string") return changed.get(value) ?? value; + if (Array.isArray(value)) return value.map(restore); + if (value !== null && typeof value === "object") { + return Object.fromEntries( + Object.entries(value as Record).map(([key, item]) => [ + changed.get(key) ?? key, + restore(item), + ]), + ); + } + return value; + }; + return restore(answer) as A; + }; + + return { scrubRuntimeEvent, restoreAnswer }; +} + +export type RuntimeEventScrubber = ReturnType; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5bc00997a..eb491c3ad 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -117,6 +117,7 @@ import { McpAppCallRepositoryLive } from "./persistence/Layers/McpAppCalls.ts"; import * as CommandRuns from "./commandRuns/CommandRuns.ts"; import * as AgentSettingsChanges from "./settingsChanges/AgentSettingsChanges.ts"; import * as AgentSecretRequests from "./secrets/AgentSecretRequests.ts"; +import * as SecretScrubber from "./secrets/SecretScrubber.ts"; import { PageFileSweepLive } from "./pages/PageFileSweep.ts"; import * as PagePreview from "./pages/preview/PagePreview.ts"; import { ThemeLibraryLive } from "./themes/ThemeLibrary.ts"; @@ -418,6 +419,9 @@ const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe( // `ProviderService` and the per-instance drivers read the same logger pair. const ProviderLayerLive = ProviderServiceLive.pipe( Layer.provide(ProviderAdapterRegistryLive), + // Watched keys, read back from their files before any provider event + // passes the hook in ProviderService (docs/design/secret-scrubbing.md). + Layer.provideMerge(SecretScrubber.layer), Layer.provideMerge(ProviderSessionDirectoryLayerLive), // The session fence reads the thread's row (docs/design/fleet.md, Part 3b). Layer.provide(ThreadSessionAdmissionLive.pipe(Layer.provide(ProjectionThreadRepositoryLive))), diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 9410b7914..134fc74fa 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -2924,6 +2924,28 @@ describe("deriveWorkLogEntries", () => { expect(entry?.detail).toBeUndefined(); }); + it("shows a key hidden from the agent's output as its line with the advice under it", () => { + const message = "Hid STRIPE_SECRET_KEY in the agent's output"; + const [entry] = deriveWorkLogEntries( + [ + makeActivity({ + id: "secret-hidden", + kind: "runtime.warning", + summary: "Runtime warning", + tone: "warning", + payload: { + message, + warningKind: "secret-hidden", + detail: "The agent may have seen it. Replace the key if that matters.", + }, + }), + ], + undefined, + ); + expect(entry?.label).toBe(message); + expect(entry?.detail).toBe("The agent may have seen it. Replace the key if that matters."); + }); + it("collapses repeated api-retry warnings into one updating row", () => { const activities: OrchestrationThreadActivity[] = [ makeActivity({ diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1be5bcd99..aa466e718 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -4508,6 +4508,12 @@ function deriveRuntimeWarningDisplay( return { label: message }; } + // A key hidden from the agent's output: the line, and the advice under it. + if (warningKind === "secret-hidden" && message) { + const rawDetail = extractRuntimeActivityDetail(activity, payload); + return rawDetail ? { label: message, detail: rawDetail } : { label: message }; + } + if (warningKind === "api-retry") { if (!codexStreamWarning) { const label = message ?? "Provider API retry"; diff --git a/docs/design/secret-requests.md b/docs/design/secret-requests.md index d91c6a883..620859b0a 100644 --- a/docs/design/secret-requests.md +++ b/docs/design/secret-requests.md @@ -543,53 +543,9 @@ fails this test. The agent can still pull a saved value into view: `env`, `cat .env.local`, `curl -v` showing an Authorization header, or a file tool reading the env -file. Today that text goes into activities, the provider logs and every -connected app. Step 2 replaces a known value with `[NAME hidden]` before -Threadlines stores or shows it, and tells the user. - -- Which values: one registry for the computer, not per thread, so a key one - thread saved is hidden when another thread prints it. It holds the - destination of every saved request still in a thread's state and reads the - value back from there (the `commands` file while it exists, the `NAME=` - line of the env file), cached by the file's time. Threadlines keeps no - extra copy to do this. -- Fast path: with no saved request on the computer, one check per event. -- Provider output: `ProviderService.publishRuntimeEvent`, before the - canonical log and delivery, on every string in the event's payload. The - registry is not keyed by thread, so the provider session key that events - still carry at that point (`ProviderService.ts:345`) does not matter. -- The native log: the write in `EventNdjsonLogger`, matching the raw and the - JSON-escaped form in each record. -- `ask_user_to_run` output: where the run's output is recorded - (`CommandRuns.ts`, the `dispatchProgress` calls that carry `output`), - before the event, the projection row and the message to the agent. Here - the model never sees the value. -- Streams: a value can be split across two chunks. The scrubber holds back a - chunk's tail only while that tail is the start of a live value, and - releases it with the next chunk or when the item ends. Ordinary output is - never delayed. -- The notice: a row on the thread, once per request per turn. For provider - output: "A command showed STRIPE_SECRET_KEY to the model. Threadlines hid - it here. Replace the key if that matters." For `ask_user_to_run` output: - "Threadlines hid STRIPE_SECRET_KEY in this command's output." - -What it does not cover, said in the guide topic: - -- the model's context and the provider's own transcript - (`~/.claude/projects/*.jsonl`, Codex rollouts), which a move carries; -- the user's own terminal: its scrollback file and what another app - watching that terminal sees; -- values under 8 characters; -- an old value after the file changed, was removed or expired, and an env - key whose request has left the thread's state; -- a value changed on the way out (base64, reversed, split by the command); -- the native log when `THREADLINES_PROVIDER_LOG_STREAM_FRAGMENTS` is on, - where a value can be split across two records. - -This is cover for accidents with keys saved through a card, not a secret -scanner. It touches the path every provider event takes, so it is its own PR -with a throughput check: a thread streaming output with one live value, -against the same thread with none. +file. Step 2 replaces a known value with `[NAME hidden]` before Threadlines +stores, logs or sends it, and tells the user. It has its own plan, +`secret-scrubbing.md`, which replaces the sketch that stood here. ## Store cleanup @@ -665,12 +621,8 @@ Step 1, one PR: the card, both uses, store cleanup. `environments/runtime/threadDetailSubscriptions.ts`, `rpc/wsRpcClient.ts`, the push alert text. -Step 2, its own PR: hiding a printed key. - -- Server: `secrets/SecretScrubber.ts` (new), - `provider/Layers/ProviderService.ts`, `provider/Layers/EventNdjsonLogger.ts`, - `commandRuns/CommandRuns.ts`, the notice activity and its row in the web - timeline. +Step 2, its own PR: hiding a printed key. Its files are listed in +`secret-scrubbing.md`. ## Testing @@ -706,10 +658,7 @@ Step 2, its own PR: hiding a printed key. from two windows at once. Check the agent asks on the card without being told to, and that Codex reads the `commands` file in both sandbox modes. A Windows run for the ACL and the PowerShell line. -- Step 2: whole payloads; a value split across chunks; a value in - JSON-escaped log text; a key saved by one thread printed by another; - command-run output hidden in the event, the row and the message; both - notices; the throughput check. +- Step 2: see `secret-scrubbing.md`. ## Later, not in this build diff --git a/docs/design/secret-scrubbing.md b/docs/design/secret-scrubbing.md new file mode 100644 index 000000000..c6fffdc09 --- /dev/null +++ b/docs/design/secret-scrubbing.md @@ -0,0 +1,748 @@ +# Hiding a printed key + +Status: plan rev 4 (Nov 19 2026). Step 2a (the scrubber and provider output) built; step 2b (the other doors) not built. Rev 4 moves stream holding from the provider hook into ingestion (see "Streams"). Debug logs: Will chose to keep them (whole values hidden, pieces may remain). Step 2 of +`secret-requests.md`, whose step 1 is on main (#1000). GPT-6.2 Astra +reviewed rev 1 (fifteen findings) and the new parts of rev 2 (thirteen); +"Review" at the end says what each changed. One choice is left for Will, +under "The debug logs". + +## The problem + +A key saved through a card stays out of Threadlines' records only until the +agent pulls it into view: `env`, `cat .env.local`, `curl -v` showing an +Authorization header, a file tool reading the env file, or the model +repeating it in a reply. From there the text goes into the thread's events, +the activity rows, the provider logs and every connected app, and a thread +move carries it. + +This step replaces a known value with `[NAME hidden]` before Threadlines +stores, logs or sends it, and tells the user it happened. + +## What it promises + +1. A watched value never appears whole in anything Threadlines stores, + logs or sends to an app, on the paths listed under "Where it runs". +2. In reply text, plan text and command output, which arrive in pieces that + Threadlines stores and joins, a value split across pieces is hidden too. +3. For `ask_user_to_run` output the agent never sees the value: Threadlines + owns that text before the model does. + +What it does not promise: + +- That the agent has not seen the value. For provider output it usually + has. Threadlines cannot take a value out of the model's context or the + provider's own transcript. +- That the two debug logs hold no pieces of a value. See "The debug logs". +- Anything in "What it does not cover". + +This is cover for accidents with keys saved through a card. It is not a +secret scanner. + +## The scrubber + +One module, `apps/server/src/secrets/SecretScrubber.ts`, used by every hook. +It holds the watched values in memory and offers: + +- `scrubText(text)`: replaces watched values in a string. +- `scrubDeep(value)`: the same for every string and every member name + inside a JSON-like value. It returns the same object when nothing matched, + so an untouched value is not copied. A renamed member that collides with + another gets a numbered suffix. +- `scrubRuntimeEvent(event)`: for provider events, with the stream handling + under "Streams". +- `contains(value)`: whether anything would be hidden, for callers that + refuse instead of rewriting. + +Each reports the names it hid, for the notice. + +### What a watched value is + +A watched value has a name, the exact text, and its forms: + +- the text as saved; +- its JSON-escaped form, when that differs (a value with a quote, a + backslash or a line break, as it sits inside a JSON string that was itself + put in a string); +- its URL-encoded form, when that differs (a key with `+`, `/` or `=` in a + query string). + +Matching is exact and case-sensitive. + +A long value is matched by its head. Once the first 256 characters of a +form match, the value counts as found, and the scrubber hides on from there +for as long as the text keeps agreeing with the value. A value of 256 +characters or fewer is matched whole. This keeps the work linear, bounds +what a stream ever holds back to 255 characters, and also hides a long key +that a tool printed cut short. + +The replacement is `[NAME hidden]`, with the request's name. When two +different values are watched under one name, the second is `[NAME 2 +hidden]`, so two texts that differ only by the key still differ after +hiding. + +A value is watched only if hiding it cannot damage ordinary output or give +itself away: + +- at least 8 characters; +- not letters only and not digits only, so `localhost`, `development` or + `12345678` saved as a "key" never blanks those words everywhere; +- not part of its own name: a value that appears in `[NAME hidden]` would be + printed by its own placeholder; +- not able to join a placeholder: a value that starts with `]` or with the + end of ` hidden]`, or ends with `[` and name characters, could be formed + by a placeholder and the text beside it. No real key looks like that. + +A value that fails these is not watched. Nothing is shown for that; the +guide topic states the rule. + +The registry holds at most 200 values. Past that the oldest retained value +with no live destination is dropped first. + +### Where the values come from + +The server stores no copy of a value on disk (step 1). The registry is +memory only, filled two ways: + +- At save: the answer service hands the scrubber the value as the user + typed it, before the write. Not the text it writes: for an env file that + is the shell spelling, quotes included + (`checkSecretValue`, `secretRequests.ts:129`), and a command that prints + the variable prints the value without them. Handing it over first matters + because the service writes and then settles + (`AgentSecretRequests.ts:375` to `:408`), so reading the file back + afterward would leave a window in which another thread's agent could + read and print a key nobody is watching yet. A failed write does not + unwatch the value: the file can outlive a failed save + (`secretDestinations.ts:510`), and watching costs nothing. +- At startup: one read-back from the destinations, below. + +One registry for the whole computer, not one per thread. A key one thread +saved is hidden when another thread prints it, and no hook needs to know +which thread an event belongs to. + +### When a value enters and leaves + +| Moment | What happens | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| The user presses Save | the typed value is watched from before the file is written | +| The server starts | every `saved` request the startup read returns is read back from its destination and watched (`reads.all`, `AgentSecretRequests.ts:82`: every thread that is not deleted, archived ones included). So is every `env_file` request that is `uncertain` or still `claimed`: a crash after the rename leaves the value in the file with the request never marked saved (`secretDestinations.ts:306`) | +| Remove now, the 24-hour expiry, thread cleanup | the file goes. The value stays watched | +| The request leaves the thread's state, the thread is archived or deleted | the value stays watched | +| A second card saves the same name | both values are watched | +| The server stops | everything is forgotten | + +A value stays watched after its file is gone because the model can still +hold it: a session that read the key an hour ago can repeat it after the +file expired. + +The startup read-back, per destination: + +- a `commands` key: the file + `/agent-secrets///value` + (`secretDestinations.ts`, `commandsFilePath`), when it still exists; +- an `env_file` key: the `NAME=` line of the file the request is bound to + (`parent` joined with the file name), read by the reverse of + `writeEnvLine` in `packages/shared/src/secretRequests.ts`: bare, or in + single or double quotes with no escapes. + +The load is one query and a handful of small file reads. It finishes while +the server starts, as part of building the scrubber, so no provider event +can arrive before it. + +What the registry does not do: + +- It does not follow the env file between restarts. A key the user changes + by hand in the file is watched after the next restart. A key changed + through a new card is watched at once. +- A destination that cannot be read at startup (the file is gone, the name + is no longer in it, the line is in a form the reader does not know) is + skipped until the next restart. A debug log line names the request, never + a value. + +## Where it runs + +### 1. Provider output: one place + +Every provider's events enter the server at `processRuntimeEvent` +(`ProviderService.ts:665`), called for each event of each adapter's +`streamEvents` (`:715`) and for the events the server makes for a session +(compaction `:2267`, goals `:2373`). It calls `publishRuntimeEvent` +(`:584`), which writes the canonical log (`:589`), holds events of an early +session (`:605`, `:1406`), and delivers to analytics and to every consumer +through one PubSub (`:614`; the only other delivery, `:1302`, hands on +events it already took). Ingestion, the events, the projections, alerts and +the client streams are all behind that PubSub. No adapter writes to the +event store itself. + +The scrubber goes in `processRuntimeEvent`, after +`correlateRuntimeEventWithInstance` and before `publishRuntimeEvent`. + +`scrubRuntimeEvent` works on `payload` and on `raw.payload`. It leaves the +event's own ids alone: they route the event, and rewriting one would detach +it from its item or request. An event can come back as one event, or as +that event with others before or after it (released stream tails, the +notice), published in order. + +`raw.payload` is the provider's own message, the same content in another +shape, and Codex and Muse can carry output there as base64 +(`CodexAdapter.ts:2488`, `MuseAdapter.ts:1148`), which a text match cannot +see. So when anything was hidden in an event's `payload` or `raw.payload`, +`raw.payload` is replaced with `{ "hidden": true }`. The +`source` and `method` beside it stay, since ingestion reads `raw.method` +(`ProviderRuntimeIngestion.ts:3545`). + +Events are still keyed by the provider session key here, not the thread id +(`toThreadRuntimeEvent`, `:353`). The registry is per computer, so this +does not matter. The hook keeps no stream state (see "Streams"). + +One place joins text after this hook: ingestion keeps a child's partial +answers and joins them with its final one before handing the result to the +parent (`ProviderRuntimeIngestion.ts:3690`). `scrubText` runs on that joined +text too. + +#### Text that stops in the middle of a value + +Some text is a snapshot of output still being written: a growing tool +input, a running command's output so far. It can end partway through a +value. In any string that is not a stream piece, a tail of 4 or more +characters that is the start of a watched form is cut off. The next +snapshot holds the whole value and hides it. Fewer than 4 characters are +left alone, so ordinary text does not lose its last letter. + +#### Questions and approvals + +Two kinds of event are answered by the user, and the answer goes back to +the provider: + +- An approval (`request.opened`). The card shows the command or edit with + the key hidden. On approval the provider runs its own copy of the input + (Claude: `updatedInput: toolInput`, `ClaudeAdapter.ts:9451`), so what runs + is what the agent asked for. The card says less than what runs by exactly + the hidden key. +- A question (`user-input.requested`). Claude uses the question's own text + as its id and expects the answer keyed by that text + (`ClaudeAdapter.ts:9224`). A rewritten question would come back under a + key the adapter does not know. + +So for these two event types the scrubber remembers, per session and +request id, each string it changed and what it was. When the answer passes +`respondToRequest` or `respondToUserInput` (`ProviderService.ts:2518`, +`:2556`), any string or member name in it that exactly equals a remembered +changed string is put back to the original before the adapter gets it. The +memory is dropped when the request resolves or the session exits. Nothing +else is ever put back, so typing `[NAME hidden]` into a reply does nothing. + +Two cases this leaves as they are: + +- A Codex question answered as a message. The reactor writes the question + and the chosen label into a sentence and sends it as the user's message + (`ProviderCommandReactor.ts:4631`). That sentence is stored, so it keeps + the placeholder, and the agent reads `[NAME hidden]` where the key was. +- A form an MCP server sends with a watched key as a field's default + (`mcpElicitation.ts:104`). The field shows the placeholder, and a length + or format rule on it can reject that until the user types the value. + +### 2. `ask_user_to_run` + +A run's output is read from the user's terminal and recorded in two places +in `commandRuns/CommandRuns.ts`: + +- `dispatchProgress` (`:204`) carries `output` into the + `thread.command-run.update` command, which becomes the server-only output + event and the `projection_thread_command_runs.output` row. Every recorded + output passes here (`:336`, `:353`). +- `deliver` (`:226`) builds the message to the agent from the output in + hand, the row, or the open terminal (`:238` to `:259`). + +`scrubText` runs on `output` at the top of `dispatchProgress`, and in +`deliver` on the output once it is chosen, before +`buildCommandOutputMessage`. The second call matters for a run still going, +whose output is read straight from the terminal (`:245`). + +The terminal manager cuts a run's output to its last 16,000 characters +before `CommandRuns` sees it (`terminal/Layers/Manager.ts:2594`, `:4702`), +and a cut can fall inside a value. Both cuts scrub first, then cut. A run +still going can also have printed only the start of a long value: the rule +for text that stops in the middle of a value covers that. + +The request is checked too. `request` (`:122`) refuses a command or a +reason that contains a watched value: "This command contains +STRIPE_SECRET_KEY. Read it from its file inside the command instead." A +placeholder inside a shell command would only break it. + +### 3. Threadlines' own tools + +An agent that has read a key can put it into one of Threadlines' tools: a +message to another thread, a question to another agent, a scheduled task's +prompt, a page. Each handler stores the arguments it was called with. + +These calls are refused, not rewritten. A rewritten message would tell +another agent something the caller did not say, and a refusal teaches the +agent what to do instead. + +- The room endpoint's handlers are one object (`McpRoomServer.ts:185` to + `:548`). A wrapper around it checks every tool's input with `contains` + and answers a call that has a watched value with a tool error: "Your call + contains STRIPE_SECRET_KEY. Don't pass a key through this tool. The other + agent can ask the user for it." +- `show_page` (`AgentPages.ts:396`, `publish`) refuses the same way, for + every string it is given: the title, the content and the icon. +- A Claude artifact that Threadlines adopts as a page (`AgentPages.ts:557`) + is not a call it can refuse. Its title and content are scrubbed. + +### 4. Provider text read back for an app + +Some screens read a provider's own files or live state and send the text +straight to the app that asked, with no event in between. A subagent that +ran `cat .env.local`, or a background task that printed a key, would show +there. + +Two of these readers return only the end of a longer text, so they scrub +before they cut: + +- a running command's output (`ClaudeAdapter.ts:10605`): the adapter has + the whole of what Claude kept, so it scrubs that and then takes the + 4,096-character tail; +- a background run's output file (`BackgroundRunOutput.ts:88`): it reads + the wanted tail plus the length of the longest watched form in bytes, + scrubs, then keeps the tail. A value that overlaps the tail starts no + further back than that, so it is always read whole. + +The others return whole strings, and their `ws.ts` handlers pass the result +through `scrubDeep`: + +- `serverReadSubagentTranscript` (`:1813`) +- `serverListExternalProviderThreads` (`:1864`, titles and previews) +- `serverReadWorkflowRunFile` and `serverReadWorkflowAgentTranscript` + (`:2178`, `:2184`) + +### 5. Imported sessions + +Importing a session made outside Threadlines reads the provider's own +transcript and writes a thread from it: a title from the session's name or +preview (`ExternalThreadImport.ts:73`), then its messages (`:93`, `:104`). +`scrubDeep` runs once on the whole transcript, right after it is read and +before anything is dispatched. + +### 6. Provider failure text + +A provider's error text is stored without passing hook 1: Pi, OpenCode and +Muse append the end of the process's stderr to a failure +(`PiRpc.ts:384`), and the reactor stores it as an activity and as +`session.lastError`, from where it can reach a phone alert +(`pushAlertRules.ts:174`). That text is made in one function, +`formatFailureDetail` (`ProviderCommandReactor.ts:1041`). `scrubText` runs +on its result, and on the side-answer start error (`:6666`). + +### 7. The debug logs + +Two files per thread under `/logs/provider/`, kept 30 days: + +- the canonical log, written by `publishRuntimeEvent` from events hook 1 + already scrubbed; +- the native log, each provider's raw messages, written by the adapters + before any canonical event exists. Every native write goes through one + function, `write` in `EventNdjsonLogger.ts:680`, including the ACP + protocol log (`AcpNativeLogging.ts:21`). + +`makeEventNdjsonLogger` gains an optional `scrub` function, applied to the +record before it is serialized (`:681`). `ProviderEventLoggersLive` +(`ProviderEventLoggers.ts:98`) passes `scrubDeep` for the native logger, and +so do the three adapters that can build a logger of their own +(`ClaudeAdapter.ts:4285`, `CodexAdapter.ts:3267`, `AcpAdapter.ts:564`). + +This hides a value that sits whole in one record. It does not hide a value +spread over several records, and both logs can hold one that way. Since rev +4 that includes the canonical log's stream pieces themselves, since the hook +no longer holds stream text: + +- the native log keeps the pieces of a reply and of command output as + separate records for most providers (`ClaudeAdapter.ts:4234` and + `CodexAdapter.ts:132` leave out only thinking pieces; OpenCode and ACP + mark none, and ACP logs each message twice); +- the canonical log keeps each event's `raw.payload`, and some events that + are not stream pieces carry a piece there (Claude's partial tool input, + `ClaudeAdapter.ts:5240`). + +Rev 1 tried to mark those records provider by provider. Astra showed the +lists were already wrong for OpenCode, Codex and ACP, and a list like that +goes stale with every provider release. There are two honest designs: + +- **Keep the logs, hide whole values (the plan's default).** The logs stay + as useful as they are today. A value can sit in them in pieces. They are + files under the same OS account that can already read the key file + itself, and nothing sends them anywhere. +- **Quiet logs.** While any value is watched, the native log is not written + and every event loses its `raw.payload`. Then no log holds a piece. The + cost is that provider problems on that computer can no longer be debugged + from the logs, for good, since an env key stays watched across restarts. + +This is Will's call. The build takes one flag either way +(`THREADLINES_QUIET_PROVIDER_LOGS`), off by default until he says. + +## Streams + +Rev 4 (Nov 19 2026), after two review rounds on the build and a design call +by Fable: the hook does not hold stream text. It could not know when +ingestion closes the message a piece feeds, and every review round found +another case where its guess and ingestion's buffers disagreed. Ingestion +owns those buffers, so it holds there. + +Reply text, side answers and realtime transcripts reach the store as +`thread.message.assistant.delta` commands that the projector appends by +message id. That is the only stored text built by appending across +commands. Everything else ingestion stores is a whole snapshot. + +- **Message text.** `dispatchAssistantDelta` in + `ProviderRuntimeIngestion.ts` holds per message id, the projector's own + append key. Each piece is joined with what the message held back, whole + values are hidden, and a tail that could start one is held again. A piece + held whole sends nothing. Every delta dispatch goes through it, the + buffered-mode spill included. The held tail is released as one more + delta just before `thread.message.assistant.complete` + (`finalizeAssistantMessage` and the side answer's completion), and + dropped in `clearAssistantMessageState`. +- **Command output and thinking.** Held per activity stream before the text + enters its buffer (`appendBufferedActivityStream`), with the held state + kept in the buffer entry so it lives and dies with it. The buffer's + 4,000-character window can cut a key's front, and its snapshot is + dispatched whole, so holding has to happen before the window. +- **Snapshots.** Plans (`upsertProposedPlan`), a child's answer so far + (`dispatchSubagentResultActivity`) and every activity's summary and + payload (`projectRuntimeActivities`) get a whole-value check where they + are stored. Nothing touches a command's ids, type or member names. + +The holder (`holdPiece` in `secretScrubberCore.ts`) is the same three steps +as before: join, scan once, hold the longest tail that starts a watched +head. Long values are followed across pieces from a saved position. Held +text is at most 255 characters and in practice one or two, and is always +original text, never a placeholder. At completion it is released as it is: +the promise is "never whole", and cutting there would eat the last word of +ordinary replies. + +The hook keeps whole-value hiding per event, never cuts a stream piece, and +drops `raw.payload` when it hid anything. + +## Cost + +Every provider event passes hook 1, and the registry stays non-empty for +good once a user saves an env key. The watched case is the normal case for +anyone who used the card, so it has to be cheap, not rare. + +- Nothing watched: one length check, and the event is passed on as the same + object. No allocation. +- A stream piece: one key string, one pass over the held text plus the + piece per form. No rescanning of text already scanned. +- Any other event: one walk over the strings and member names in `payload` + and `raw.payload`, one `indexOf` per form per string. Linear in the + event's size, no copy unless something matched. +- Memory: at most 200 values, and per open stream at most 255 held + characters and one small event to copy for the release. Stream state is + freed at its release. + +The throughput check, reported in the PR: + +- Workloads: the runtime events of the recorded Claude and Codex sessions + in `apps/server/integration/replay/fixtures`; 100,000 token-sized reply + pieces; 2,000 command-output events of 64 KB; a 64 KB key arriving one + character per piece; 200 streams open at once; and the same records + through the native logger's `scrub`. +- Registries: nothing watched, one value, 50, and 200 (one of them a 64 KB + multi-line key). +- Measured: events per second and the slowest single piece through + `scrubRuntimeEvent`; the same events' time through ingestion, for + scale; memory held with 200 streams mid-value; wall time with nothing + watched against the code without the hook. +- Pass: with nothing watched, no measurable change; with 50 values the + scrubber adds less than 5% to an event's time through ingestion; the + one-character workload stays linear. If it does not pass, the build stops + and comes back to the plan. + +A unit test pins the nothing-watched case by identity (`toBe`), so that +part cannot flake on a loaded CI machine. The timings are a PR report, not +a CI gate. + +## The notice + +Two places notice a hidden key: the provider hook for whole values in one +event, and ingestion for values its holder or snapshot checks hid. They +share one memory, keyed by thread id and turn id, so the user is told once +per name per turn either way. A side answer gets no notice; its text is +still hidden. + +When hook 1 hides a value in a thread's own session, the user is told once +per name per turn. The scrubber emits a `runtime.warning` event after the +scrubbed one, with `warningKind: "secret-hidden"`. It rides the path +warnings already take (`ProviderActivityProjection.ts:797`), and the +timeline gives that kind its own row, as it does for `api-retry` and +`sign-in-resend` (`apps/web/src/session-logic.ts:4496`). No new event type +and no migration. + +> Hid STRIPE_SECRET_KEY in the agent's output +> +> The agent may have seen it. Replace the key if that matters. + +The first line is the row; the second is its detail, so the row fits one +line on a narrow screen. + +"May have": a command's output can be hidden as it streams and the turn +stopped before the model reads it. + +Where there is no notice, and why: + +- a side answer (`room_ask`, a review): ingestion handles side sessions + apart and drops warnings there (`ProviderRuntimeIngestion.ts:2305`). The + text is still hidden; +- `ask_user_to_run`, the read-backs, imports and adopted pages: nothing was + shown to the model by that path, or nothing new was; +- a refused tool call: the agent gets the reason, and the tool call itself + passes hook 1, which shows the notice. + +The guide topic for secret requests (`guide/topics.ts`) gains a short +paragraph: what is hidden, the 8-character rule, and the gaps below in +plain words. + +## What it does not cover + +1. The model's context, and the provider's own transcript files + (`~/.claude/projects/*.jsonl`, Codex rollouts, Pi sessions). + Threadlines carries these on a thread move as they are. +2. Pieces of a value across records of the two debug logs, unless quiet + logs are on. +3. The user's own terminal: its scrollback file and what another app + watching that terminal sees (`ws.ts:3175`). It is the user's screen. +4. Files in the project. If the agent writes a key into a tracked file, the + diff and file views show what the file holds (`ws.ts:1443`, the + checkpoint diffs). The edit's tool call is hidden and the notice fires. +5. A value that is not watched: too short or too plain; after a restart, + one whose file is gone or unreadable; a key changed by hand in the env + file since the last restart. +6. A value changed on the way out: base64, reversed, spaced out, or + combined with other text and then encoded (`Authorization: Basic`). Also + a long value the provider itself cut at the front before Threadlines saw + it: without its first 256 characters it is not recognized. +7. An id the provider chose. Codex uses a process handle as an item id + (`CodexAdapter.ts:2495`); ids are never rewritten. +8. Voice. A realtime session's audio goes to apps on its own channel + (`CodexSessionRuntime.ts:2312`). Its transcript is covered. +9. MCP Apps and browser tools: what a page or an MCP server returns to an + app, and what the agent types into a page with `browser_type`. +10. Other failure text: an error an adapter put on its own session object + (`session.lastError` from `CodexSessionRuntime.ts:2393`), a review that + failed to start, and server log lines that quote a provider's message. + A saved key is in a file, not in the provider's environment, so it has + no ordinary way into that text. +11. What the user types. A saved key pasted into the message box is sent + as typed. +12. The two question cases under "Questions and approvals": a Codex + question answered as a message, and an MCP form with a watched key as a + default. +13. Two long texts that share their first 256 characters. If one is a + watched value, the shared start of the other is hidden too. +14. A side answer stopped or timed out from outside, mid-stream: up to the + last few characters it held back, because they could start a key, are + dropped. Ingestion never sees that stop, and the answer is closed by + then. The key is never shown; only those few ordinary characters go. + +## Providers + +Hook 1 needs no per-provider code: every provider reaches the server +through `adapter.streamEvents` and `processRuntimeEvent`. Side answers run +under a side session key on the same streams, and room tools read their +text back from the stored message. + +| Provider | What is particular | +| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Claude | Questions are keyed by their text: the original is put back on the way to the adapter. Partial tool input rides `item.updated` as a growing snapshot, hidden once the value is whole. Command output tail and background output are scrubbed before the cut. | +| Codex | Output pieces are base64 in `raw`: `raw.payload` is dropped when the stream hides or holds. Plan text is `turn.proposed.delta`, its own stream type. Imports are hook 5. | +| OpenCode | Child sessions share a session key: the stream key carries the provider's thread id. Stderr in failure text is hook 6. | +| Pi | Stderr in failure text is hook 6. | +| Muse | Output can outlive its turn: output streams are released at the item's end, not the turn's. Summary index is part of the stream key. | +| Cursor, fx, Antigravity, Grok (ACP) | Reply pieces can lack an item id: one stream per kind per turn. Handled once in the scrubber, nothing per agent. | +| Community agents | The same generic path. | + +## Build order and files + +Two PRs. The promise needs both. + +Step 2a: the scrubber and provider output. + +- New: `apps/server/src/secrets/SecretScrubber.ts` and its test. +- `packages/shared/src/secretRequests.ts`: `readEnvValue` (the reverse of + `writeEnvLine`) and `isWatchableSecret`. +- `apps/server/src/secrets/AgentSecretRequests.ts`: hand over the value + before the write, drop it on a failed write; the startup read-back. +- `apps/server/src/provider/Layers/ProviderService.ts`: the call in + `processRuntimeEvent`; putting originals back in `respondToRequest` and + `respondToUserInput`. +- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`: the + child's joined answer. +- `apps/web/src/session-logic.ts` and the timeline row for `secret-hidden`. +- `apps/server/src/guide/topics.ts`. +- The throughput check. + +Step 2b: the other doors. + +- `apps/server/src/commandRuns/CommandRuns.ts`: `request`, + `dispatchProgress`, `deliver`; `apps/server/src/terminal/Layers/Manager.ts`: + the two cuts of a run's output. +- `apps/server/src/mcp/McpRoomServer.ts`: the input check. +- `apps/server/src/pages/AgentPages.ts`: `publish` and adopt. +- `apps/server/src/provider/Layers/ClaudeAdapter.ts` (the command output + tail), `apps/server/src/diagnostics/BackgroundRunOutput.ts`, and the four + `ws.ts` read handlers. +- `apps/server/src/provider/ExternalThreadImport.ts`. +- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`: + `formatFailureDetail` and the side-answer start error. +- `apps/server/src/provider/Layers/EventNdjsonLogger.ts`, + `ProviderEventLoggers.ts` and the three adapters' own loggers: `scrub`, + and the quiet-logs flag. + +## Testing + +The main test is a reconstruction check, not a search for the literal +value: a search passes while every character of a key is still +recoverable. For a session whose command output, reply and tool input each +carry a saved key, split at awkward places: + +- read back every event, every projection row and every frame a second + client received, join each stream's pieces in order, and require that no + joined stream and no single string holds the value; +- the same for both debug logs, for whole values, and for pieces too with + quiet logs on; +- run it on the Claude and Codex replays, and on recorded or hand-made + event sequences for OpenCode, Pi (`pi/fixtures/pi-1.3.0-records.jsonl`), + Muse and ACP. + +Then, by part: + +- The scrubber: a whole value in a string, in nested objects and arrays, + and as a member name; a snapshot that ends 4 or more characters into a + value loses that tail, and one that ends 3 in keeps it; a child's partial + and final answers that join into a value are hidden in what the parent + gets; the JSON-escaped and URL-encoded forms; the same + object back when nothing matched; a short, plain or self-naming value + never hidden; a long value found by its head and hidden as far as it + agrees, including one cut short; two names with one value. +- Streams: a value split across two and across five pieces; two streams + interleaved; two summary indexes kept apart; pieces with no item id; a + value that could join a placeholder (`]1234567`) is not watched; held + text released before each closing event in the list, asserted on the + final projected text: a plan ending in a held letter is whole after + `turn.proposed.completed`, a reply before an approval card keeps its last + letter, a realtime transcript's tail stays in its own message, a reused + Codex process handle does not get the old tail; a command whose output + crosses its turn's end stays hidden; several streams released by one + event; a tail that turns out not to be a value arrives intact and in + order. +- Questions and approvals: a Claude question containing a watched value is + shown hidden and its answer reaches the adapter under the original text; + two questions that differ only by two values of one name stay two + questions; + an approval shows the command hidden and the original runs; nothing is + put back for any other string. +- The registry: watched before the file exists (a barrier between the + hand-over and the write, with another session printing the value); an + env value with a `#` in it is hidden when a command prints the variable + right after Save; still watched after a failed write; read back at + startup, archived threads included, and for an env request left + `uncertain` by a crash after the rename; two values under one name get + different placeholders; a removed `commands` key still hidden until restart; an + unreadable destination skipped without a failure; the 200-value limit. +- `ask_user_to_run`: output hidden in the event, the row and the message, + for a finished run and a run still going; a 300-character key sent once + while half printed and once after 16,000 more characters is hidden both + times; a command or reason with a watched value refused. +- Tools: a `thread_send`, a `room_ask` and a `show_page` with a watched + value (in its content, its title or its icon) are refused and store + nothing; an adopted artifact is stored + hidden, title included. +- Read-backs: both tail readers give the same result as scrubbing the + whole source and then cutting, for a short key, a multi-line key and a + URL-encoded one; a subagent transcript and an import (title and messages) come + back hidden. +- Failure text: a start failure whose stderr tail holds the value is + stored, and alerted, hidden. +- The notice: one per name per turn, its own row, none for a side answer. +- The throughput check above. +- A polish check of the notice row with the app's real fonts, light and + dark. + +## Review + +Astra reviewed rev 1 without the room's conversation. I checked its +findings against the code. All fifteen held at least in part. What each +changed: + +1. The per-provider lists of log records to leave out were already + incomplete (OpenCode's text deltas, Codex's realtime transcript, ACP's + second copy). The lists are gone. The logs get whole-value hiding, and + the choice between useful logs and piece-free logs goes to Will. +2. A piece can ride an event that is not a stream piece, in `raw`. Same + answer as 1. In the event's `payload` those are growing snapshots, which + are hidden once whole. +3. Releasing held text at the end of a turn leaked output that outlives the + turn. Output streams now release at their item's end. +4. Scrubbing a tail after it was cut misses a value across the cut. The two + tail readers scrub before they cut. +5. Reading the file back after the save left a window with an unwatched + key on disk. The value is handed over before the write. +6. Three fields went around the hooks: an import's title, a command + request's reason, a page's title. Each is covered where it enters. +7. Member names are scrubbed. Ids are not, and that is listed. +8. Failure text is covered at `formatFailureDetail`. The terminal, voice + and project files are listed as not covered, each with its reason. +9. A rewritten question broke Claude's answer keys. Originals are put back + on the way to the adapter, for exactly the strings that were changed. + Threadlines' own tools refuse instead of rewriting. +10. The stream step matched its own placeholder. Held text and tail checks + now use original text only, and a value that is part of its own name is + not watched. +11. The stream key was too coarse. It now carries summary index, content + index and the provider's thread id, with a rule for missing item ids. +12. A release is now an event of the stream's own type, and one event can + release several streams. +13. The background refresh of env files is gone: it could miss an edit and + could lag for hours. Values come from the card at save and from one + read-back at startup, and the plan says what that leaves out. The + startup read includes archived threads, as the query does. +14. The notice says "may have seen", and the paths with no notice are + listed with reasons. +15. Long values are matched by their first 256 characters, which bounds + held text and keeps the work linear. The registry is capped. The + throughput check now covers long keys, many values, many streams, the + logger and the nothing-watched wall time. + +Also from the review: the acceptance test is now a reconstruction check. + +Astra then reviewed only the parts new in rev 2 and found thirteen more. I +checked them against the code. What rev 3 changed: + +1. The env save handed over the shell spelling, quotes and all. It now + hands over the value as typed. +2. A crash after the rename left a key in the file with its request never + marked saved. Startup now reads back `uncertain` and `claimed` env + requests too. +3. Ingestion joins a child's partial and final answers. That joined text is + scrubbed. +4. A placeholder and the text beside it could spell another watched value. + A value shaped to do that is not watched. +5. `show_page` checks its icon too. `browser_type` is listed as not + covered. +6. A failed write no longer unwatches the value. +7. A long key sent in two cut snapshots of command output got through in + two halves. The terminal manager scrubs before it cuts, and a snapshot + that ends partway into a value loses that tail. +8. A Codex question answered as a message keeps the placeholder. Listed. +9. Two values under one name get different placeholders, so two questions + cannot collapse into one. +10. An MCP form with a watched key as a default is listed as a limit. +11. and 12. Held text is now released before every event at which ingestion + closes the message: a finished plan, a finished voice transcript, an + approval or question card, a reused process handle. +12. The tail readers read back as far as the longest watched value, not 255 + characters. Shared 256-character starts and a long key the provider cut + at the front are listed. + +I stopped at two rounds. The second found less than the first, and what is +left is the kind of thing the build's own tests and diff review catch. diff --git a/packages/shared/src/secretRequests.test.ts b/packages/shared/src/secretRequests.test.ts index 80250d960..5d2d4f644 100644 --- a/packages/shared/src/secretRequests.test.ts +++ b/packages/shared/src/secretRequests.test.ts @@ -8,6 +8,8 @@ import { checkSecretValue, envFilePathProblem, hasEdgeWhitespace, + isWatchableSecret, + readEnvValue, posixShellQuote, scanEnvFile, secretAnswerMessageId, @@ -167,3 +169,25 @@ describe("secret answer messages", () => { expect(secretRequestIdOfAnswerMessage("command-output:run-1")).toBeNull(); }); }); + +describe("hiding a printed key", () => { + it("reads an env value back the way it was written, or by hand", () => { + expect(readEnvValue("A=1\nKEY=sk_test_1\n", "KEY")).toBe("sk_test_1"); + expect(readEnvValue("KEY='abc#123 x'\n", "KEY")).toBe("abc#123 x"); + expect(readEnvValue('export KEY="sk_live_9" # prod\n', "KEY")).toBe("sk_live_9"); + expect(readEnvValue("KEY=sk_test_1 # note\n", "KEY")).toBe("sk_test_1"); + expect(readEnvValue('KEY="a\\nb"\n', "KEY")).toBeUndefined(); + expect(readEnvValue("OTHER=1\n", "KEY")).toBeUndefined(); + }); + + it("watches only values that can't blank ordinary words or form from a placeholder", () => { + expect(isWatchableSecret("KEY", "sk_test_51Hv")).toBe(true); + expect(isWatchableSecret("KEY", "short1")).toBe(false); + expect(isWatchableSecret("KEY", "localhost")).toBe(false); + expect(isWatchableSecret("KEY", "12345678")).toBe(false); + expect(isWatchableSecret("KEY", "]1234567x")).toBe(false); + expect(isWatchableSecret("KEY", "den]abc123")).toBe(false); + expect(isWatchableSecret("KEY", "abc123[KEY")).toBe(false); + expect(isWatchableSecret("STRIPE_KEY", "STRIPE_KEY h")).toBe(false); + }); +}); diff --git a/packages/shared/src/secretRequests.ts b/packages/shared/src/secretRequests.ts index 5729f4264..b4baffcc7 100644 --- a/packages/shared/src/secretRequests.ts +++ b/packages/shared/src/secretRequests.ts @@ -279,6 +279,66 @@ export function writeEnvLine( return { ok: true, text: lines.join("\n") }; } +/** + * The value `name` holds in an env file's text, as Threadlines writes it or a + * person does by hand: bare (up to a ` #` comment), or in single or double + * quotes with no escapes. Undefined when the name isn't there or the line is + * in a form this doesn't read; the reverse of `writeEnvLine`. + */ +export function readEnvValue(text: string, name: string): string | undefined { + const scan = scanEnvFile(text, name, "env"); + if (!scan.ok || scan.line === null) return undefined; + const line = (text.split("\n")[scan.line] ?? "").replace(/\r$/, ""); + const rest = (ASSIGNMENT.exec(line)?.[4] ?? "").trimStart(); + const quote = rest[0]; + if (quote === "'" || quote === '"') { + const end = rest.indexOf(quote, 1); + if (end === -1) return undefined; + const inner = rest.slice(1, end); + return quote === '"' && inner.includes("\\") ? undefined : inner; + } + let end = rest.length; + for (let index = 1; index < rest.length; index += 1) { + if (rest[index] === "#" && (rest[index - 1] === " " || rest[index - 1] === "\t")) { + end = index; + break; + } + } + const bare = rest.slice(0, end).trim(); + return bare.length === 0 || /\s/.test(bare) ? undefined : bare; +} + +// --------------------------------------------------------------------------- +// Hiding a printed key (docs/design/secret-scrubbing.md). + +/** The shortest value Threadlines watches for: shorter ones would blank ordinary text. */ +export const MIN_WATCHED_SECRET_LENGTH = 8; + +/** What a watched value is replaced with; the second distinct value under one name is numbered. */ +export const secretPlaceholder = (name: string, ordinal = 1): string => + ordinal === 1 ? `[${name} hidden]` : `[${name} ${ordinal} hidden]`; + +const PLACEHOLDER_END = " hidden]"; +const PLACEHOLDER_NAME_TAIL = /^[A-Za-z0-9_ ]*$/; + +/** + * Whether hiding this value can't damage ordinary output or give itself + * away: long enough, not letters or digits alone, not inside its own + * placeholder, and unable to be formed by a placeholder and the text beside it. + */ +export function isWatchableSecret(name: string, value: string): boolean { + if (value.length < MIN_WATCHED_SECRET_LENGTH) return false; + if (/^[A-Za-z]+$/.test(value) || /^[0-9]+$/.test(value)) return false; + if (secretPlaceholder(name).includes(value) || secretPlaceholder(name, 2).includes(value)) { + return false; + } + for (let length = 1; length <= PLACEHOLDER_END.length; length += 1) { + if (value.startsWith(PLACEHOLDER_END.slice(-length))) return false; + } + const open = value.lastIndexOf("["); + return open === -1 || !PLACEHOLDER_NAME_TAIL.test(value.slice(open + 1)); +} + // --------------------------------------------------------------------------- // Shell quoting.