diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 55cb71288..ca1eb709b 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -450,6 +450,7 @@ export const makeOrchestrationIntegrationHarness = ( Layer.provide(persistenceLayer), Layer.provideMerge(RepositoryIdentityResolverLive), Layer.provideMerge(serverSettingsLayer), + Layer.provideMerge(secretScrubberLayer), Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)), Layer.provideMerge(NodeServices.layer), ); diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts index 4039295f2..ec0610c96 100644 --- a/apps/server/integration/providerService.integration.test.ts +++ b/apps/server/integration/providerService.integration.test.ts @@ -38,11 +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"; +import { layer as SecretScrubberLive } 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)); + makeProviderServiceLive(...args).pipe(Layer.provide(SecretScrubberLive)); const codexInstanceId = ProviderInstanceId.make("codex"); diff --git a/apps/server/src/commandRuns/CommandRuns.ts b/apps/server/src/commandRuns/CommandRuns.ts index dc7af3d24..c4f0447ce 100644 --- a/apps/server/src/commandRuns/CommandRuns.ts +++ b/apps/server/src/commandRuns/CommandRuns.ts @@ -50,6 +50,7 @@ import type { McpInvocationScope } from "../mcp/McpSessionRegistry.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { ProjectionThreadCommandRepository } from "../persistence/Services/ProjectionThreadCommands.ts"; +import { SecretScrubber } from "../secrets/SecretScrubber.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { TerminalManager, type TerminalCommandRunUpdate } from "../terminal/Services/Manager.ts"; @@ -104,6 +105,7 @@ const make = Effect.gen(function* () { const commandRows = yield* ProjectionThreadCommandRepository; const terminals = yield* TerminalManager; const settings = yield* ServerSettingsService; + const secretScrubber = yield* SecretScrubber; /** The thread each run of this process belongs to; run updates carry only the run id. */ const runThreads = new Map(); @@ -149,6 +151,15 @@ const make = Effect.gen(function* () { detail: `Keep the command under ${MAX_SHELL_COMMAND_LENGTH} characters and ${MAX_SHELL_COMMAND_LINES} lines; put longer scripts in a file and ask to run that.`, }; } + // A card shows its command, and the run prints it: a saved key in it + // would be on screen and in the output (docs/design/secret-scrubbing.md). + const [watched] = secretScrubber.contains([command, reason]); + if (watched !== undefined) { + return { + outcome: "refused" as const, + detail: `This command contains ${watched}. Read it from its file inside the command instead.`, + }; + } const dialect = serverCommandDialect(); const assessment = assessShellCommand(command, dialect); if (assessment.blocked !== null) { @@ -213,7 +224,7 @@ const make = Effect.gen(function* () { commandId: CommandId.make(`command-run:${progress.runId}:${key}`), threadId, progress, - ...(output !== undefined ? { output } : {}), + ...(output !== undefined ? { output: secretScrubber.scrubText(output).text } : {}), createdAt: yield* nowIso, }); }); @@ -256,7 +267,12 @@ const make = Effect.gen(function* () { threadId, runId: run.runId, automatic, - message: { messageId, text: buildCommandOutputMessage({ run, output }) }, + message: { + messageId, + // The whole message, command and folder included: a card or a + // record made before a key was saved still holds it whole. + text: secretScrubber.scrubText(buildCommandOutputMessage({ run, output })).text, + }, createdAt: yield* nowIso, }) .pipe(Effect.mapError((error) => failWith(error.message))); diff --git a/apps/server/src/diagnostics/BackgroundRunOutput.test.ts b/apps/server/src/diagnostics/BackgroundRunOutput.test.ts index dc042274d..bbb7b7cbb 100644 --- a/apps/server/src/diagnostics/BackgroundRunOutput.test.ts +++ b/apps/server/src/diagnostics/BackgroundRunOutput.test.ts @@ -7,6 +7,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; +import { makeSecretScrubber, type SecretScrubberShape } from "../secrets/SecretScrubber.ts"; import { canMakeSymlinks } from "../testUtils/symlinks.ts"; import { makeBackgroundRunOutputReader } from "./BackgroundRunOutput.ts"; @@ -27,7 +28,10 @@ afterEach(async () => { }); /** A thread whose only activity is Claude's reply naming `announcedFile`. */ -function readerForThreadAnnouncing(announcedFile: string) { +function readerForThreadAnnouncing( + announcedFile: string, + scrubber: SecretScrubberShape = makeSecretScrubber(), +) { const thread = { activities: [ { @@ -37,9 +41,10 @@ function readerForThreadAnnouncing(announcedFile: string) { }, ], } as unknown as OrchestrationThread; - return makeBackgroundRunOutputReader({ - getThreadDetailById: () => Effect.succeed(Option.some(thread)), - }); + return makeBackgroundRunOutputReader( + { getThreadDetailById: () => Effect.succeed(Option.some(thread)) }, + scrubber, + ); } describe("readBackgroundRunOutput", () => { @@ -49,6 +54,20 @@ describe("readBackgroundRunOutput", () => { expect(result.tail).toContain("http://localhost:5173/"); }); + it("hides a saved key whole even when it reaches into the end from before it", async () => { + // A key of many lines, long enough that the 8 KB end starts inside it: + // cut first, the lines after the cut would show. + const key = Array.from({ length: 12 }, (_, line) => `${line}a1b2c3d4`.repeat(8)).join("\n"); + const scrubber = makeSecretScrubber(); + scrubber.watch("DEPLOY_KEY", key); + await writeFile(outputFile, `${"x".repeat(9_000)}\n${key}\n${"y".repeat(8_000)}\ndone\n`); + const read = readerForThreadAnnouncing(outputFile, scrubber); + const result = await Effect.runPromise(read({ threadId: THREAD_ID, outputFile })); + expect(result.tail).toContain("[DEPLOY_KEY hidden]"); + expect(result.tail).not.toContain("a1b2c3d4"); + expect(result.tail).toContain("done"); + }); + it("refuses a file the thread never named, even one shaped like Claude's", async () => { const read = readerForThreadAnnouncing(path.join(directory, "tasks", "other.output")); const result = await Effect.runPromise(read({ threadId: THREAD_ID, outputFile })); diff --git a/apps/server/src/diagnostics/BackgroundRunOutput.ts b/apps/server/src/diagnostics/BackgroundRunOutput.ts index 36b920ccd..239d04ce8 100644 --- a/apps/server/src/diagnostics/BackgroundRunOutput.ts +++ b/apps/server/src/diagnostics/BackgroundRunOutput.ts @@ -66,9 +66,21 @@ export function announcedOutputFiles( * platform supports it (not Windows). */ const OPEN_NO_FOLLOW = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0); -/** The end of a regular file as text, from a whole line on. Null for a - * symlink, or a path whose real location is not a `tasks/.output` file. */ -async function readFileTail(file: string): Promise { +/** Hides saved keys in text, and says how far back to read to catch one whole. */ +export interface OutputScrubber { + readonly scrubText: ( + text: string, + options?: { readonly cutTail?: boolean }, + ) => { readonly text: string }; + readonly longestFormBytes: () => number; +} + +/** + * The end of a regular file as text, from a whole line on, with saved keys + * hidden. Null for a symlink, or a path whose real location is not a + * `tasks/.output` file. + */ +async function readFileTail(file: string, scrubber: OutputScrubber): Promise { const linkStats = await lstat(file); if (!linkStats.isFile()) return null; // A symlinked parent directory could still move the read elsewhere; the @@ -85,12 +97,21 @@ async function readFileTail(file: string): Promise { if (!stats.isFile() || stats.ino !== linkStats.ino || stats.dev !== linkStats.dev) { return null; } - const length = Math.min(stats.size, OUTPUT_TAIL_BYTES); + // Read further back by the longest key's length, hide keys, then keep + // the end: a key reaching into the end starts inside the read, so it is + // hidden whole rather than cut (docs/design/secret-scrubbing.md). + const length = Math.min(stats.size, OUTPUT_TAIL_BYTES + scrubber.longestFormBytes()); const buffer = Buffer.alloc(length); const { bytesRead } = await handle.read(buffer, 0, length, stats.size - length); - const text = buffer.subarray(0, bytesRead).toString("utf8"); + // The file may still be written: a tail that could start a key goes too. + const read = scrubber.scrubText(buffer.subarray(0, bytesRead).toString("utf8"), { + cutTail: true, + }).text; + const text = read.length > OUTPUT_TAIL_BYTES ? read.slice(-OUTPUT_TAIL_BYTES) : read; // A read that starts mid-file starts mid-line; drop the partial line. - return length < stats.size ? text.slice(text.indexOf("\n") + 1) : text; + return length < stats.size || text.length < read.length + ? text.slice(text.indexOf("\n") + 1) + : text; } finally { await handle.close(); } @@ -98,6 +119,7 @@ async function readFileTail(file: string): Promise { export function makeBackgroundRunOutputReader( projectionSnapshotQuery: Pick, + scrubber: OutputScrubber, now: () => number = Date.now, ) { /** When each file was last confirmed, per thread. */ @@ -134,7 +156,7 @@ export function makeBackgroundRunOutputReader( Effect.orElseSucceed(() => false), ); if (!announced) return UNREADABLE; - const tail = yield* Effect.tryPromise(() => readFileTail(file)).pipe( + const tail = yield* Effect.tryPromise(() => readFileTail(file, scrubber)).pipe( Effect.orElseSucceed(() => null), ); return { tail } satisfies ServerReadBackgroundRunOutputResult; diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 26050d6d6..911656e47 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -562,7 +562,7 @@ Settings that give agents more reach ({place:threads.agentThreads}, {place:threa 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.`, +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. An agent's message to another agent or thread, a page, or a command it asks you to run is refused while it holds one. 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/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index b4427b611..07b50347b 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -18,6 +18,11 @@ import * as PreviewAutomationBroker from "../preview/PreviewAutomationBroker.ts" import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts"; import { ProviderService } from "../provider/Services/ProviderService.ts"; import { ServerSettingsService } from "../serverSettings.ts"; +import { + makeSecretScrubber, + SecretScrubber, + type SecretScrubberShape, +} from "../secrets/SecretScrubber.ts"; import { AgentSecretRequests } from "../secrets/AgentSecretRequests.ts"; import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; @@ -200,6 +205,7 @@ const ROOM_THREAD = { const roomServerStubs = ( settings?: Parameters[0], thread: object = ROOM_THREAD, + secretScrubber: SecretScrubberShape = makeSecretScrubber(), ) => Layer.mergeAll( Layer.succeed(OrchestrationEngineService, { @@ -217,6 +223,7 @@ const roomServerStubs = ( Layer.succeed(ProviderService, { listSessions: () => Effect.succeed([]) } as never), Layer.succeed(GitVcsDriver, {} as never), Layer.succeed(AgentSecretRequests, { destinations: {} } as never), + Layer.succeed(SecretScrubber, secretScrubber), ServerSettingsService.layerTest(settings), PreviewAutomationBroker.layer, ); @@ -381,6 +388,45 @@ describe("MCP endpoints", () => { ); }); + it("refuses a call that would carry a saved key to another agent or thread", async () => { + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const base = yield* serve( + McpRoomServer.layer.pipe( + Layer.provide(roomServerStubs(undefined, ROOM_THREAD, secretScrubber)), + ), + ); + const agent = yield* mcpSessionRegistry.credentialFor({ + sessionKey: THREAD, + browser: true, + room: true, + }); + const result = yield* Effect.promise(async () => ({ + send: await callTool(`${base}/mcp/room`, agent.token, "thread_send", { + threadId: "child-1", + message: "Use sk_test_51Hq9xYz for the webhook.", + }), + ask: await callTool(`${base}/mcp/room`, agent.token, "room_ask", { + agent: "Reviewer", + question: "Is sk_test_51Hq9xYz the live key?", + }), + })); + for (const call of [result.send, result.ask]) { + expect(call.structuredContent).toMatchObject({ + outcome: "refused", + detail: + "Your call contains STRIPE_SECRET_KEY. Don't pass a key through this tool. The other agent can ask the user for it.", + }); + } + yield* mcpSessionRegistry.revoke(THREAD, agent.generation); + }), + ).pipe(onLoopback), + ); + }); + it("lists only its own tools on each endpoint, and keeps side runtimes off the browser", async () => { await Effect.runPromise( Effect.scoped( diff --git a/apps/server/src/mcp/McpRoomServer.ts b/apps/server/src/mcp/McpRoomServer.ts index e0ec91f80..41810a9bf 100644 --- a/apps/server/src/mcp/McpRoomServer.ts +++ b/apps/server/src/mcp/McpRoomServer.ts @@ -75,6 +75,7 @@ import { SettingsChangeToolkit } from "./settingsChangeTools.ts"; import { makeSecretRequestToolHandler } from "./secretRequestToolHandlers.ts"; import { SecretRequestToolkit } from "./secretRequestTools.ts"; import { AgentSecretRequests } from "../secrets/AgentSecretRequests.ts"; +import { SecretScrubber } from "../secrets/SecretScrubber.ts"; import { makeAlertAssistantsToolHandler } from "./alertAssistantsToolHandlers.ts"; import { AlertAssistantsToolkit } from "./alertAssistantsTools.ts"; import { makeProjectNoteToolHandlers } from "./projectNoteToolHandlers.ts"; @@ -100,6 +101,10 @@ export const RoomEndpointToolkit = Toolkit.merge( type RoomEndpointToolName = keyof typeof RoomEndpointToolkit.tools; +/** Why a call that changes something was refused: it held a saved key's value. */ +export const secretInCallDetail = (name: string) => + `Your call contains ${name}. Don't pass a key through this tool. The other agent can ask the user for it.`; + /** * What each tool on this endpoint reaches, for outside work's limit: `own`, * only the caller's own thread or checkout; `project`, threads and tasks @@ -209,6 +214,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( const providerService = yield* ProviderService; const git = yield* GitVcsDriver; const settings = yield* ServerSettingsService; + const secretScrubber = yield* SecretScrubber; // Linked computers, when this server has them (docs/design/fleet.md). const linkClient = yield* Effect.serviceOption(ComputerLinkClient); const linkRepo = yield* Effect.serviceOption(ComputerLinkRepository); @@ -504,15 +510,34 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( _tool: ToolsReaching<"own">, run: (scope: McpInvocationScope) => Effect.Effect, ) => Effect.flatMap(caller, run); + /** + * Refuses a call whose input holds a saved key's value: what these tools + * carry reaches another agent, a thread, a card or a task's history, none + * of which hides one (docs/design/secret-scrubbing.md). + */ + const unlessWatched = ( + input: unknown, + run: () => Effect.Effect, + refusedAs: (detail: string) => R = (detail) => + ({ outcome: "refused", detail }) satisfies Refused as R, + ): Effect.Effect => { + const [watched] = secretScrubber.contains(input); + return watched === undefined ? run() : Effect.succeed(refusedAs(secretInCallDetail(watched))); + }; const changes = ( _tool: ToolsReaching<"changes">, + input: unknown, run: (scope: McpInvocationScope) => Effect.Effect, ) => - Effect.flatMap(caller, (scope): Effect.Effect => - scope.outsideLimit === undefined - ? run(scope) - : Effect.succeed({ outcome: "refused", detail: outsideLimitDetail(scope.outsideLimit) }), - ); + Effect.flatMap(caller, (scope): Effect.Effect => { + if (scope.outsideLimit !== undefined) { + return Effect.succeed({ + outcome: "refused", + detail: outsideLimitDetail(scope.outsideLimit), + }); + } + return unlessWatched(input, () => run(scope)); + }); const projectRead = ( _tool: ToolsReaching<"project">, run: (scope: McpInvocationScope) => Effect.Effect, @@ -532,12 +557,14 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( room_agents: () => own("room_agents", handlers.room_agents), room_history: (input) => own("room_history", (scope) => handlers.room_history(scope, input)), room_diff: (input) => own("room_diff", (scope) => handlers.room_diff(scope, input)), - room_ask: (input) => changes("room_ask", (scope) => handlers.room_ask(scope, input)), - room_review: (input) => changes("room_review", (scope) => handlers.room_review(scope, input)), + room_ask: (input) => changes("room_ask", input, (scope) => handlers.room_ask(scope, input)), + room_review: (input) => + changes("room_review", input, (scope) => handlers.room_review(scope, input)), room_hand_off: (input) => - changes("room_hand_off", (scope) => handlers.room_hand_off(scope, input)), + changes("room_hand_off", input, (scope) => handlers.room_hand_off(scope, input)), room_available_agents: () => own("room_available_agents", handlers.room_available_agents), - room_invite: (input) => changes("room_invite", (scope) => handlers.room_invite(scope, input)), + room_invite: (input) => + changes("room_invite", input, (scope) => handlers.room_invite(scope, input)), thread_agents: (input) => projectRead( "thread_agents", @@ -545,7 +572,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( (detail) => ({ outcome: "refused", detail, agents: [], unavailable: [] }), ), thread_start: (input) => - changes("thread_start", (scope) => threadHandlers.thread_start(scope, input)), + changes("thread_start", input, (scope) => threadHandlers.thread_start(scope, input)), thread_list: (input) => projectRead( "thread_list", @@ -559,11 +586,11 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( (detail) => ({ outcome: "refused", detail, messages: [], next: null, more: false }), ), thread_send: (input) => - changes("thread_send", (scope) => threadHandlers.thread_send(scope, input)), + changes("thread_send", input, (scope) => threadHandlers.thread_send(scope, input)), thread_stop: (input) => - changes("thread_stop", (scope) => threadHandlers.thread_stop(scope, input)), + changes("thread_stop", input, (scope) => threadHandlers.thread_stop(scope, input)), thread_move: (input) => - changes("thread_move", (scope) => threadHandlers.thread_move(scope, input)), + changes("thread_move", input, (scope) => threadHandlers.thread_move(scope, input)), schedule_list: (input) => projectRead( "schedule_list", @@ -571,15 +598,26 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( (detail) => ({ outcome: "refused", detail, tasks: [] }), ), schedule_create: (input) => - changes("schedule_create", (scope) => scheduleHandlers.schedule_create(scope, input)), + changes("schedule_create", input, (scope) => + scheduleHandlers.schedule_create(scope, input), + ), schedule_update: (input) => - changes("schedule_update", (scope) => scheduleHandlers.schedule_update(scope, input)), + changes("schedule_update", input, (scope) => + scheduleHandlers.schedule_update(scope, input), + ), scheduled_run_finish: (input) => - own("scheduled_run_finish", (scope) => scheduleHandlers.scheduled_run_finish(scope, input)), + own("scheduled_run_finish", (scope) => + unlessWatched( + input, + () => scheduleHandlers.scheduled_run_finish(scope, input), + (detail) => ({ outcome: "not_allowed" as const, detail }), + ), + ), settings_change: (input) => - changes("settings_change", (scope) => settingsChange(scope, input)), - secret_request: (input) => own("secret_request", (scope) => secretRequest(scope, input)), - alert_assistants: () => changes("alert_assistants", alertAssistants), + changes("settings_change", input, (scope) => settingsChange(scope, input)), + secret_request: (input) => + own("secret_request", (scope) => unlessWatched(input, () => secretRequest(scope, input))), + alert_assistants: () => changes("alert_assistants", undefined, alertAssistants), project_note_read: (input) => projectRead( "project_note_read", @@ -587,7 +625,9 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( (detail) => ({ outcome: "refused", detail }), ), project_note_write: (input) => - changes("project_note_write", (scope) => projectNotes.project_note_write(scope, input)), + changes("project_note_write", input, (scope) => + projectNotes.project_note_write(scope, input), + ), // Listed only to runtimes granted it; a call from any other is refused // too (a review runtime reads the checkout and nothing else). Refused // while outside work limits the caller: it reads app-wide settings, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 4d9293238..5916d70e9 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -57,6 +57,11 @@ import * as Stream from "effect/Stream"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test"; import { deriveServerPaths, ServerConfig } from "../../config.ts"; +import { + makeSecretScrubber, + SecretScrubber, + type SecretScrubberShape, +} from "../../secrets/SecretScrubber.ts"; import { TextGenerationError } from "@threadlines/contracts"; import { ProviderAdapterRequestError, @@ -214,6 +219,8 @@ describe("ProviderCommandReactor", () => { * reactor starts. */ readonly beforeStart?: (engine: OrchestrationEngineShape) => Effect.Effect; readonly serverSettings?: Parameters[0]; + /** The watched keys; none by default. */ + readonly secretScrubber?: SecretScrubberShape; /** Instances that are no longer configured (an account was removed). */ readonly removedInstanceIds?: ReadonlyArray; /** Computer links' check on a linked computer's queued messages. */ @@ -717,6 +724,9 @@ describe("ProviderCommandReactor", () => { }), ), Layer.provideMerge(ServerSettingsService.layerTest(input?.serverSettings)), + Layer.provideMerge( + Layer.succeed(SecretScrubber, input?.secretScrubber ?? makeSecretScrubber()), + ), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)), Layer.provideMerge(SqlitePersistenceMemory), Layer.provideMerge(NodeServices.layer), @@ -1330,6 +1340,34 @@ describe("ProviderCommandReactor", () => { expect(harness.sendTurn.mock.calls.length).toBe(0); }); + it("hides a saved key in a provider's failure text before storing it", async () => { + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); + const harness = await createHarness({ secretScrubber }); + harness.startSession.mockImplementationOnce(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: "codex", + method: "thread.turn.start", + detail: "spawn failed: invalid key sk_test_51Hq9xYz", + }), + ), + ); + await startTurn(harness, "fails"); + + await waitFor(async () => { + const thread = (await harness.readModel()).threads.find( + (entry) => entry.id === ThreadId.make("thread-1"), + ); + return thread?.session?.lastError?.includes("spawn failed") === true; + }); + const thread = (await harness.readModel()).threads.find( + (entry) => entry.id === ThreadId.make("thread-1"), + ); + expect(thread?.session?.lastError).toContain("invalid key [STRIPE_SECRET_KEY hidden]"); + expect(JSON.stringify(thread)).not.toContain("sk_test_51Hq9xYz"); + }); + it("shows a failed start again after the user closed the same failure", async () => { const harness = await createHarness(); const spawnFails = () => diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index a30ee393b..a2d41311c 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -138,6 +138,7 @@ import type { ProviderServiceError, SteerRejection } from "../../provider/Errors import { TextGeneration } from "../../textGeneration/TextGeneration.ts"; import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import { SecretScrubber } from "../../secrets/SecretScrubber.ts"; import { ThreadContextSeedBuilder } from "../../provider/contextSeed/ThreadContextSeedBuilder.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; @@ -594,6 +595,7 @@ function stalePendingRequestDetail( const make = Effect.gen(function* () { const handoverCaptureWait = yield* HandoverCaptureWait; const orchestrationEngine = yield* OrchestrationEngineService; + const secretScrubber = yield* SecretScrubber; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; const projectionTurnRepository = yield* ProjectionTurnRepository; // Computer links, when this server has them: see RemoteRequestGate. @@ -969,7 +971,8 @@ const make = Effect.gen(function* () { kind: input.kind, summary: input.summary, payload: { - detail: input.detail, + // Some callers pass a cause as it is; a provider error can quote a key. + detail: secretScrubber.scrubText(input.detail).text, ...(input.requestId ? { requestId: input.requestId } : {}), ...(input.failedCommandId ? { commandId: input.failedCommandId } : {}), }, @@ -1038,7 +1041,15 @@ const make = Effect.gen(function* () { return null; }; - const formatFailureDetail = (cause: Cause.Cause): string => { + /** + * A failure as the user reads it. Saved keys are hidden: a provider's + * stderr (Pi, OpenCode, Muse) never passed the event hook, and this text is + * stored and can reach a phone alert (docs/design/secret-scrubbing.md). + */ + const formatFailureDetail = (cause: Cause.Cause): string => + secretScrubber.scrubText(failureText(cause)).text; + + const failureText = (cause: Cause.Cause): string => { const failReason = cause.reasons.find(Cause.isFailReason); const providerError = isProviderAdapterRequestError(failReason?.error) ? failReason.error @@ -1063,7 +1074,11 @@ const make = Effect.gen(function* () { type: "thread.session.set", commandId: serverCommandId("provider-session-set"), threadId: input.threadId, - session: input.session, + // The stored error reaches the thread and phone alerts: no saved key in it. + session: + input.session.lastError === null || input.session.lastError === undefined + ? input.session + : { ...input.session, lastError: secretScrubber.scrubText(input.session.lastError).text }, createdAt: input.createdAt, }); @@ -6679,7 +6694,9 @@ const make = Effect.gen(function* () { threadId, sideTurnId: sideTurn.sideTurnId, outcome: "failed", - error: `The side answer could not start: ${Cause.squash(cause) instanceof Error ? (Cause.squash(cause) as Error).message : "unknown error"}`, + error: secretScrubber.scrubText( + `The side answer could not start: ${Cause.squash(cause) instanceof Error ? (Cause.squash(cause) as Error).message : "unknown error"}`, + ).text, createdAt: yield* nowIso, }); return false; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index f006f0fae..1bc5c15a4 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -1,6 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off import { - layerTest as SecretScrubberTest, + layer as SecretScrubberLive, makeSecretScrubber, SecretScrubber, type SecretScrubberShape, @@ -317,7 +317,7 @@ describe("ProviderRuntimeIngestion", () => { const layer = ProviderRuntimeIngestionLive.pipe( Layer.provide( options?.secretScrubber === undefined - ? SecretScrubberTest + ? SecretScrubberLive : Layer.succeed(SecretScrubber, options.secretScrubber), ), Layer.provideMerge( diff --git a/apps/server/src/pages/AgentPages.test.ts b/apps/server/src/pages/AgentPages.test.ts index ec2e18a1d..6ef53377f 100644 --- a/apps/server/src/pages/AgentPages.test.ts +++ b/apps/server/src/pages/AgentPages.test.ts @@ -22,6 +22,11 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as TestClock from "effect/testing/TestClock"; +import { + makeSecretScrubber, + SecretScrubber, + type SecretScrubberShape, +} from "../secrets/SecretScrubber.ts"; import { ServerConfig } from "../config.ts"; import type { McpInvocationScope } from "../mcp/McpSessionRegistry.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; @@ -111,6 +116,8 @@ const makeLayer = (options: { readonly previewed?: Array; /** Each document measured for its height. */ readonly measured?: Array; + /** The watched keys; none by default. */ + readonly secretScrubber?: SecretScrubberShape; }) => AgentPagesLayer.pipe( Layer.provide( @@ -143,6 +150,7 @@ const makeLayer = (options: { }), }), ServerSettingsService.layerTest({ enableAgentPages: options.enabled ?? true }), + Layer.succeed(SecretScrubber, options.secretScrubber ?? makeSecretScrubber()), Layer.mock(PagePreview.PagePreview)({ measure: ({ document }) => Effect.sync(() => { @@ -212,6 +220,33 @@ it.layer(NodeServices.layer)("AgentPages.show", (it) => { ); }); + it.effect("refuses a page that holds a saved key, and records nothing", () => { + const dispatched: Array = []; + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); + return Effect.gen(function* () { + const pages = yield* AgentPages; + const outcome = yield* pages.show(caller(), { + title: "Setup", + html: "

Your key: sk_test_51Hq9xYz

", + }); + assert.deepStrictEqual(outcome, { + outcome: "refused", + detail: + "Your page contains STRIPE_SECRET_KEY. Don't put a key on a page; name the file it is in instead.", + }); + assert.strictEqual(dispatched.length, 0); + }).pipe( + Effect.provide( + makeLayer({ + thread: threadWith({ participantId: null, activeTurnId: TURN }), + dispatched, + secretScrubber, + }), + ), + ); + }); + it.effect("records the page on the turn the calling agent is working on", () => { const dispatched: Array = []; return Effect.gen(function* () { @@ -377,6 +412,42 @@ it.layer(NodeServices.layer)("AgentPages.adopt", (it) => { }, ); + it.effect("hides a saved key in a page it adopts, since that call can't be refused", () => { + readCount = 0; + const dispatched: Array = []; + const measured: Array = []; + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); + return Effect.gen(function* () { + const pages = yield* AgentPages; + const outcome = yield* pages.adopt({ + threadId: THREAD, + turnId: TURN, + participantId: null, + path: publishedFile("keys.html", "

Your key: sk_test_51Hq9xYz

"), + title: "Key sk_test_51Hq9xYz", + shareUrl: LINK, + }); + assert.strictEqual(outcome.outcome, "shown"); + const command = dispatched[0]; + assert.strictEqual(command?.type, "thread.page.publish"); + if (command?.type === "thread.page.publish") { + assert.strictEqual(command.page.title, "Key [STRIPE_SECRET_KEY hidden]"); + } + assert.ok(measured[0]?.includes("Your key: [STRIPE_SECRET_KEY hidden]")); + assert.ok(!measured.some((document) => document.includes("sk_test_51Hq9xYz"))); + }).pipe( + Effect.provide( + makeLayer({ + thread: threadWith({ participantId: null, activeTurnId: TURN }), + dispatched, + measured, + secretScrubber, + }), + ), + ); + }); + it.effect("updates the page already showing a link that is published again", () => { const dispatched: Array = []; const shown = { pageId: "22222222-2222-4222-8222-222222222222", version: 3, shareUrl: LINK }; diff --git a/apps/server/src/pages/AgentPages.ts b/apps/server/src/pages/AgentPages.ts index a3928d335..2dc551dcd 100644 --- a/apps/server/src/pages/AgentPages.ts +++ b/apps/server/src/pages/AgentPages.ts @@ -86,6 +86,7 @@ import { removePageVersion, writePageVersion, } from "./PageStore.ts"; +import { SecretScrubber } from "../secrets/SecretScrubber.ts"; import { PagePreview, type PagePreviewResult } from "./preview/PagePreview.ts"; import { THEME_PAGE_HEIGHT, themePageContent, themePreviewText } from "./themePages.ts"; @@ -319,6 +320,7 @@ const make = Effect.gen(function* () { const workshop = yield* ThemeWorkshop; const vscode = yield* ThemeVsCode; const analytics = yield* AnalyticsService; + const secretScrubber = yield* SecretScrubber; const pending = new Set(); // One publish at a time per page, so versions are numbered in the order @@ -406,6 +408,12 @@ const make = Effect.gen(function* () { readonly height?: number | undefined; readonly icon?: string | undefined; readonly shareUrl?: string | undefined; + /** + * A page the agent published elsewhere and Threadlines adopts: a saved + * key in it is hidden, since the call can't be refused. Otherwise a page + * holding one is refused (docs/design/secret-scrubbing.md). + */ + readonly adopted?: boolean | undefined; /** What the agent is told once it shows. Default: SHOWN_MESSAGE. */ readonly message?: Effect.Effect | undefined; /** Whether the page still has its turn to show in, asked right before it is stored. */ @@ -424,7 +432,21 @@ const make = Effect.gen(function* () { .map((page) => page.version), ); - const prepared = yield* args.content; + const content = yield* args.content; + let title = args.title; + let prepared = content; + if (args.adopted === true) { + title = secretScrubber.scrubText(title).text; + prepared = secretScrubber.scrubText(content).text; + } else { + const [watched] = secretScrubber.contains([args.title, content, args.icon ?? ""]); + if (watched !== undefined) { + return { + outcome: "refused" as const, + detail: `Your page contains ${watched}. Don't put a key on a page; name the file it is in instead.`, + }; + } + } // A theme shows as a row of one height; there is nothing to measure. const measured = @@ -484,7 +506,7 @@ const make = Effect.gen(function* () { version, turnId: args.turnId, participantId: args.participantId, - title: args.title, + title, kind, height, ...(heights !== undefined ? { heights } : {}), @@ -576,6 +598,7 @@ const make = Effect.gen(function* () { content: Effect.succeed(published.content), icon: input.icon, shareUrl, + adopted: true, stillStands, }), ); diff --git a/apps/server/src/provider/ExternalThreadImport.test.ts b/apps/server/src/provider/ExternalThreadImport.test.ts index 0474f5b82..c3287bb28 100644 --- a/apps/server/src/provider/ExternalThreadImport.test.ts +++ b/apps/server/src/provider/ExternalThreadImport.test.ts @@ -11,10 +11,11 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { describe, it, vi } from "vite-plus/test"; +import { makeSecretScrubber } from "../secrets/SecretScrubber.ts"; import { importExternalProviderThread } from "./ExternalThreadImport.ts"; describe("importExternalProviderThread", () => { - it("backfills the transcript in order and requires the exact native Codex session", async () => { + it("backfills the transcript in order, keys hidden, and requires the exact native Codex session", async () => { const providerInstanceId = ProviderInstanceId.make("codex"); const projectId = ProjectId.make("project-1"); const threadId = ThreadId.make("thread-imported"); @@ -40,6 +41,8 @@ describe("importExternalProviderThread", () => { }), ); const stopSession = vi.fn((_input: { readonly threadId: ThreadId }) => Effect.void); + const secretScrubber = makeSecretScrubber(); + secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); const services: Parameters[1] = { projectionSnapshotQuery: { getProjectShellById: () => @@ -86,7 +89,7 @@ describe("importExternalProviderThread", () => { providerItemId: "item-assistant", providerTurnId: "turn-1", role: "assistant", - text: "I fixed the parser.", + text: "I fixed the parser. The key is sk_test_51Hq9xYz.", createdAt: "2026-07-19T10:05:00.000Z", }, ], @@ -96,6 +99,7 @@ describe("importExternalProviderThread", () => { stopSession, }, orchestrationEngine: { dispatch }, + secretScrubber, }; const result = await Effect.runPromise( @@ -123,6 +127,8 @@ describe("importExternalProviderThread", () => { "thread.session.set", ], ); + const reply = commands.find((command) => command.type === "thread.message.assistant.delta"); + assert.equal(reply?.delta, "I fixed the parser. The key is [STRIPE_SECRET_KEY hidden]."); const createCommand = commands.find((command) => command.type === "thread.create"); assert.equal(createCommand?.createdAt, "2026-07-19T10:00:00.000Z"); assert.equal(startSession.mock.calls.length, 1); diff --git a/apps/server/src/provider/ExternalThreadImport.ts b/apps/server/src/provider/ExternalThreadImport.ts index 1d1496892..c204c40ab 100644 --- a/apps/server/src/provider/ExternalThreadImport.ts +++ b/apps/server/src/provider/ExternalThreadImport.ts @@ -15,6 +15,8 @@ import * as Schema from "effect/Schema"; import type { OrchestrationEngineShape } from "../orchestration/Services/OrchestrationEngine.ts"; import type { ProjectionSnapshotQueryShape } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { scrubExternalThreadSnapshot } from "../secrets/readBackScrubbing.ts"; +import type { SecretScrubberShape } from "../secrets/SecretScrubber.ts"; import type { ProviderServiceShape } from "./Services/ProviderService.ts"; interface ExternalThreadImportServices { @@ -24,6 +26,7 @@ interface ExternalThreadImportServices { >; readonly projectionSnapshotQuery: Pick; readonly orchestrationEngine: Pick; + readonly secretScrubber: Pick; } const isProviderExternalThreadError = Schema.is(ProviderExternalThreadError); @@ -64,11 +67,17 @@ export function importExternalProviderThread( }); } - const snapshot = yield* services.providerService.readExternalThread({ - providerInstanceId: input.providerInstanceId, - providerThreadId: input.providerThreadId, - expectedCwd: project.workspaceRoot, - }); + // The provider's own transcript, never through the event hook: saved + // keys are hidden once, before any of it is stored + // (docs/design/secret-scrubbing.md). + const snapshot = scrubExternalThreadSnapshot( + services.secretScrubber, + yield* services.providerService.readExternalThread({ + providerInstanceId: input.providerInstanceId, + providerThreadId: input.providerThreadId, + expectedCwd: project.workspaceRoot, + }), + ); yield* services.orchestrationEngine.dispatch({ type: "thread.create", @@ -144,7 +153,9 @@ export function importExternalProviderThread( runtimeMode: input.runtimeMode, activeTurnId: null, pendingBackgroundTaskCount: 0, - lastError, + // A failed attach quotes the provider's error, stored like the transcript. + lastError: + lastError === null ? null : services.secretScrubber.scrubText(lastError).text, updatedAt, }, createdAt: updatedAt, diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 808fcbb52..9699ac197 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -2174,7 +2174,7 @@ describe("ClaudeAdapterLive", () => { harness.query.taskOutputs.set("task-run", "line 1\nline 2\n"); assert.deepEqual(yield* read("tool-run"), { status: "running", - tail: "line 1\nline 2\n", + output: "line 1\nline 2\n", totalBytes: 14, }); diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index d4be1f62c..89d4ece63 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -2881,9 +2881,6 @@ const CLAUDE_STEER_TAKEN_TIMEOUT = Duration.seconds(2); /** How long a read of a running command's output may take; a slower one * answers "nothing yet" and the client asks again. */ const CLAUDE_COMMAND_OUTPUT_READ_TIMEOUT = Duration.seconds(3); -/** The most of a running command's output a read hands back: its end, which - * holds the lines a client shows. Claude itself keeps the last 8 KiB. */ -const CLAUDE_COMMAND_OUTPUT_TAIL_CHARS = 4_096; /** How long reading the session's MCP tools may hold up a finished MCP tool * call's step; a slower read leaves that step without its app. */ const CLAUDE_MCP_TOOLS_READ_TIMEOUT = Duration.millis(1500); @@ -10619,7 +10616,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const { output, total_bytes: totalBytes } = read.value; return { status: "running", - tail: output.slice(-CLAUDE_COMMAND_OUTPUT_TAIL_CHARS), + output, totalBytes: Number.isSafeInteger(totalBytes) && totalBytes > 0 ? totalBytes : 0, } as const; }); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts index 4468a7eef..2e998d9d6 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts @@ -8,6 +8,12 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Layer from "effect/Layer"; + +import { ServerConfig } from "../../config.ts"; +import { layer as SecretScrubberLayer, SecretScrubber } from "../../secrets/SecretScrubber.ts"; +import { ProviderEventLoggers, ProviderEventLoggersLive } from "./ProviderEventLoggers.ts"; import { cleanupProviderEventLogDirectory, @@ -153,6 +159,48 @@ describe("EventNdjsonLogger", () => { }), ); + it.effect("hides saved keys in the native log, as written by the shared loggers", () => + Effect.gen(function* () { + const scrubber = yield* SecretScrubber; + scrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); + // A value that ends in a quote: matched against the raw line, it would + // take the closing quote of an innocent field that holds the rest. + scrubber.watch("QUOTED_KEY", 'abc1234"'); + const { native } = yield* ProviderEventLoggers; + const { providerEventLogPath } = yield* ServerConfig; + assert.notEqual(native, undefined); + if (!native) return; + yield* native.write( + { + method: "item/completed", + params: { output: "STRIPE_SECRET_KEY=sk_test_51Hq9xYz", note: "abc1234" }, + }, + ThreadId.make("thread-1"), + ); + yield* native.close(); + const written = fs.readFileSync( + path.join(path.dirname(providerEventLogPath), "thread-1.log"), + "utf8", + ); + const payload = JSON.parse(parseLogLine(written.trim()).payload) as { + params: { output: string; note: string }; + }; + assert.deepEqual(payload.params, { + output: "STRIPE_SECRET_KEY=[STRIPE_SECRET_KEY hidden]", + note: "abc1234", + }); + assert.notInclude(written, "sk_test_51Hq9xYz"); + }).pipe( + Effect.provide( + ProviderEventLoggersLive.pipe( + Layer.provideMerge(SecretScrubberLayer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "tl-native-log-" })), + Layer.provideMerge(NodeServices.layer), + ), + ), + ), + ); + it.effect("leaves stream fragments out unless the logger keeps them", () => Effect.gen(function* () { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts index f714bceab..0813fe880 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts @@ -58,6 +58,13 @@ export interface EventNdjsonLogger { export interface EventNdjsonLoggerOptions { readonly stream: EventNdjsonStream; + /** + * Rewrites each record's JSON line before it is written: the native log + * hides saved keys this way (docs/design/secret-scrubbing.md). A value's + * JSON-escaped form is one the scrubber looks for, so a key inside a string + * is found whole. + */ + readonly scrubLine?: (line: string) => string; /** Write records marked as stream fragments too, for debugging streaming. */ readonly keepStreamFragments?: boolean; readonly maxBytes?: number; @@ -678,10 +685,11 @@ export const makeEventNdjsonLogger = Effect.fnUntraced(function* ( const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) { const threadSegment = resolveThreadSegment(threadId); - const message = yield* toLogMessage(event); - if (!message) { + const serialized = yield* toLogMessage(event); + if (!serialized) { return; } + const message = options.scrubLine === undefined ? serialized : options.scrubLine(serialized); const writer = yield* resolveThreadWriter(threadSegment); if (!writer) { diff --git a/apps/server/src/provider/Layers/ProviderEventLoggers.ts b/apps/server/src/provider/Layers/ProviderEventLoggers.ts index 8d706b68b..40b08171f 100644 --- a/apps/server/src/provider/Layers/ProviderEventLoggers.ts +++ b/apps/server/src/provider/Layers/ProviderEventLoggers.ts @@ -36,6 +36,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { ServerConfig } from "../../config.ts"; +import { SecretScrubber, type SecretScrubberShape } from "../../secrets/SecretScrubber.ts"; import { cleanupProviderEventLogDirectory, type EventNdjsonLogger, @@ -70,6 +71,24 @@ export const NoOpProviderEventLoggers: ProviderEventLoggersShape = { canonical: undefined, }; +/** + * A record's JSON line with saved keys hidden. The text is only searched; a + * line with a match is parsed and its strings and member names scrubbed, so + * a value that ends in a quote can't eat the line's own quote and break it. + */ +function scrubJsonLine( + scrubber: Pick, + line: string, +): string { + const found = scrubber.scrubText(line); + if (found.names.length === 0) return line; + try { + return JSON.stringify(scrubber.scrubDeep(JSON.parse(line) as unknown)); + } catch { + return found.text; + } +} + /** * Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`. * If the directory create fails for either stream, the corresponding field @@ -97,9 +116,14 @@ export const ProviderEventLoggersLive = Layer.effect( Config.withDefault(false), Effect.orElseSucceed(() => false), ); + // Raw provider messages, written before any event passes the hook in + // ProviderService: saved keys are hidden here, line by line. The + // canonical log only ever gets events the hook already scrubbed. + const secretScrubber = yield* SecretScrubber; const native = yield* makeEventNdjsonLogger(providerEventLogPath, { stream: "native", keepStreamFragments, + scrubLine: (line) => scrubJsonLine(secretScrubber, line), }); const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, { stream: "canonical", diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 5f236983f..e21105bfe 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -84,11 +84,11 @@ import { ThreadSessionAdmission, ThreadSessionAdmissionPermissive, } from "../Services/ThreadSessionAdmission.ts"; -import { layerTest as SecretScrubberTest } from "../../secrets/SecretScrubber.ts"; +import { layer as SecretScrubberLive } 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)); + makeProviderServiceLive(...args).pipe(Layer.provide(SecretScrubberLive)); const defaultServerSettingsLayer = ServerSettingsService.layerTest(); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 9dbd6d92d..5692c8025 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -84,6 +84,9 @@ import { type EarlySessionEndReason, makeEarlySessionLedger } from "../earlySess /** An early start that takes longer than this is given up. */ const EARLY_SESSION_START_TIMEOUT = Duration.seconds(60); +/** The most of a running command's output a read hands back: its end, which + * holds the lines a client shows. Claude itself keeps the last 8 KiB. */ +const COMMAND_OUTPUT_TAIL_CHARS = 4_096; /** How often unused early sessions are checked for expiry. */ const EARLY_SESSION_SWEEP_INTERVAL = Duration.seconds(30); /** How long quiesceThread waits for a start or recovery of the thread already under way. */ @@ -2954,7 +2957,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( if (!routed.isActive || read === undefined) return undefined; return yield* read(routed.threadId, input.toolCallId); }).pipe(Effect.orElseSucceed(() => undefined)); - if (answer?.status === "running") return answer; + if (answer?.status === "running") { + // Hidden whole, then cut: a cut first could leave part of a key. + return { + status: "running", + tail: secretScrubber + .scrubText(answer.output, { cutTail: true }) + .text.slice(-COMMAND_OUTPUT_TAIL_CHARS), + totalBytes: answer.totalBytes, + } as const; + } if (answer?.status === "pending") pending = true; } return { status: pending ? "pending" : "unavailable" } as const; diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index 6187a01a1..6a8300108 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -27,7 +27,6 @@ import type { ProviderRealtimeOutputModality, ProviderSubagentInputRequest, ProviderSubagentInputResult, - ProviderCommandOutputResult, McpAppToolResult, ProviderSubagentTranscriptInput, ProviderSubagentTranscriptResult, @@ -67,6 +66,11 @@ export type ProviderNativeThreadForkMode = "supported" | "unsupported"; export type ProviderRealtimeVoiceMode = "supported" | "unsupported"; /** Partial goal update: omitted fields keep their provider-side values. */ +/** A running command's output as an adapter reads it, before keys are hidden and it is cut. */ +export type ProviderAdapterCommandOutput = + | { readonly status: "running"; readonly output: string; readonly totalBytes: number } + | { readonly status: "pending" | "unavailable" }; + export interface ProviderSetThreadGoalInput { readonly threadId: ThreadId; readonly objective?: string; @@ -448,14 +452,15 @@ export interface ProviderAdapterShape { /** * What a command the session is running now has printed so far, by the - * tool call that started it. Optional: drivers whose output already + * tool call that started it, whole: ProviderService hides saved keys in it + * before cutting it to its end. Optional: drivers whose output already * streams as `command_output` deltas omit it. Answers `unavailable` for a * tool call the session doesn't know, so another session can be asked. */ readonly readCommandOutput?: ( threadId: ThreadId, toolCallId: string, - ) => Effect.Effect; + ) => Effect.Effect; /** * MCP Apps (docs/mcp-apps.md), through the session's own MCP client and diff --git a/apps/server/src/secrets/SecretScrubber.ts b/apps/server/src/secrets/SecretScrubber.ts index ba7fed8e2..774f9c577 100644 --- a/apps/server/src/secrets/SecretScrubber.ts +++ b/apps/server/src/secrets/SecretScrubber.ts @@ -4,8 +4,9 @@ * 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. + * file is gone. The registry (`layer`) sits under everything that shows or + * stores agent text; `loadSavedKeys` fills it inside 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"; @@ -42,14 +43,23 @@ export interface SecretScrubberShape { 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 watched values in a string. With `cutTail`, for a snapshot of + * output still being written: a string that stops partway into a value + * loses that tail, since it is too short to match yet. + */ + readonly scrubText: (text: string, options?: { readonly cutTail?: boolean }) => 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 longest form a watched value takes, in UTF-8 bytes: how much more to + * read before a file's end so a value reaching into it is hidden whole. + */ + readonly longestFormBytes: () => number; /** 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. */ @@ -85,9 +95,10 @@ export function makeSecretScrubber(): SecretScrubberShape { return { watch: core.watch, gone: core.gone, - scrubText: (text) => core.scrubText(text), + scrubText: (text, options) => core.scrubText(text, options), scrubDeep: (value: A) => core.scrubDeep(value, new Set()) as A, contains: core.contains, + longestFormBytes: () => core.longestFormBytes, scrubRuntimeEvent: runtime.scrubRuntimeEvent, restoreAnswer: runtime.restoreAnswer, holdPiece: core.holdPiece, @@ -136,16 +147,18 @@ export const readBackSecret = ( return text._tag === "Some" ? readEnvValue(text.value, request.name) : undefined; }); +/** The registry, empty until `loadSavedKeys` and Save fill it. One for the server. */ +export const layer = Layer.sync(SecretScrubber, makeSecretScrubber); + /** - * 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. + * Fills the registry at startup from every live thread's saved keys; the + * provider layer depends on it, so this runs before any provider 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, +export const loadSavedKeys = Layer.effectDiscard( Effect.gen(function* () { - const scrubber = makeSecretScrubber(); + const scrubber = yield* SecretScrubber; const snapshots = yield* ProjectionSnapshotQuery; const config = yield* ServerConfig; const load = Effect.gen(function* () { @@ -186,9 +199,5 @@ export const layer = Layer.effect( 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/readBackScrubbing.test.ts b/apps/server/src/secrets/readBackScrubbing.test.ts new file mode 100644 index 000000000..3a0844deb --- /dev/null +++ b/apps/server/src/secrets/readBackScrubbing.test.ts @@ -0,0 +1,52 @@ +import { ProviderInstanceId } from "@threadlines/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { scrubExternalThreadList, scrubWorkflowRunFile } from "./readBackScrubbing.ts"; +import { makeSecretScrubber } from "./SecretScrubber.ts"; + +describe("read-back scrubbing", () => { + it("hides a key in what a person reads, never in ids or status words that equal it", () => { + const scrubber = makeSecretScrubber(); + scrubber.watch("API_KEY", "not-ended"); + scrubber.watch("SESSION_KEY", "native-thread-7"); + + expect( + scrubWorkflowRunFile(scrubber, { + text: "export KEY=not-ended", + format: "text", + truncated: false, + unavailableReason: "not-ended", + logs: ["using not-ended"], + }), + ).toEqual({ + text: "export KEY=[API_KEY hidden]", + format: "text", + truncated: false, + unavailableReason: "not-ended", + logs: ["using [API_KEY hidden]"], + }); + + const [candidate] = scrubExternalThreadList(scrubber, { + data: [ + { + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: "native-thread-7", + sessionId: "session-1", + source: "cli", + name: "Rotate native-thread-7", + preview: "native-thread-7 leaked", + cwd: "/workspace", + cliVersion: "0.145.0", + createdAt: "2026-07-19T10:00:00.000Z", + updatedAt: "2026-07-19T10:05:00.000Z", + status: "idle", + canImport: true, + }, + ], + }).data; + // The id goes back as it is: an import sends it back to find the session. + expect(candidate?.providerThreadId).toBe("native-thread-7"); + expect(candidate?.name).toBe("Rotate [SESSION_KEY hidden]"); + expect(candidate?.preview).toBe("[SESSION_KEY hidden] leaked"); + }); +}); diff --git a/apps/server/src/secrets/readBackScrubbing.ts b/apps/server/src/secrets/readBackScrubbing.ts new file mode 100644 index 000000000..1ea4ab15f --- /dev/null +++ b/apps/server/src/secrets/readBackScrubbing.ts @@ -0,0 +1,87 @@ +/** + * Provider text read straight from a provider's files or live state for the + * app, with saved keys hidden (docs/design/secret-scrubbing.md, "Provider + * text read back for an app"). Only the fields a person reads are scrubbed: + * ids, cursors and status words go back as they are, so a key that happens + * to equal one can't break a reply's schema or an import that sends the id + * back. + */ +import type { + ProviderExternalThreadCandidate, + ProviderExternalThreadListResult, + ProviderExternalThreadSnapshot, + ProviderSubagentTranscriptResult, + WorkflowReadRunFileResult, +} from "@threadlines/contracts"; + +import type { SecretScrubberShape } from "./SecretScrubber.ts"; + +type TextScrubber = Pick; + +const text = (scrubber: TextScrubber, value: string) => scrubber.scrubText(value).text; +const optionalText = (scrubber: TextScrubber, value: T): T => + (typeof value === "string" ? text(scrubber, value) : value) as T; + +/** A subagent's or a workflow agent's transcript: what it said, ran and printed. */ +export const scrubTranscript = ( + scrubber: TextScrubber, + result: ProviderSubagentTranscriptResult, +): ProviderSubagentTranscriptResult => ({ + ...result, + entries: result.entries.map((entry) => ({ + ...entry, + text: text(scrubber, entry.text), + toolUses: entry.toolUses.map((use) => ({ + ...use, + summary: text(scrubber, use.summary), + ...(use.description !== undefined ? { description: text(scrubber, use.description) } : {}), + })), + ...(entry.outputPreview !== undefined + ? { outputPreview: text(scrubber, entry.outputPreview) } + : {}), + })), + ...(result.agent?.description !== undefined + ? { agent: { ...result.agent, description: text(scrubber, result.agent.description) } } + : {}), +}); + +/** A session from outside Threadlines, as listed: its name and preview. */ +const scrubCandidate = ( + scrubber: TextScrubber, + candidate: ProviderExternalThreadCandidate, +): ProviderExternalThreadCandidate => ({ + ...candidate, + name: optionalText(scrubber, candidate.name), + preview: text(scrubber, candidate.preview), +}); + +export const scrubExternalThreadList = ( + scrubber: TextScrubber, + result: ProviderExternalThreadListResult, +): ProviderExternalThreadListResult => ({ + ...result, + data: result.data.map((candidate) => scrubCandidate(scrubber, candidate)), +}); + +/** A session from outside Threadlines, read to import: its name, preview and messages. */ +export const scrubExternalThreadSnapshot = ( + scrubber: TextScrubber, + snapshot: ProviderExternalThreadSnapshot, +): ProviderExternalThreadSnapshot => ({ + candidate: scrubCandidate(scrubber, snapshot.candidate), + messages: snapshot.messages.map((message) => ({ + ...message, + text: text(scrubber, message.text), + })), +}); + +/** A workflow run's script or result: its text, error and logged lines. */ +export const scrubWorkflowRunFile = ( + scrubber: TextScrubber, + result: WorkflowReadRunFileResult, +): WorkflowReadRunFileResult => ({ + ...result, + text: optionalText(scrubber, result.text), + ...(result.error !== undefined ? { error: text(scrubber, result.error) } : {}), + ...(result.logs !== undefined ? { logs: result.logs.map((line) => text(scrubber, line)) } : {}), +}); diff --git a/apps/server/src/secrets/secretScrubberCore.ts b/apps/server/src/secrets/secretScrubberCore.ts index 42ce89652..5c9020b82 100644 --- a/apps/server/src/secrets/secretScrubberCore.ts +++ b/apps/server/src/secrets/secretScrubberCore.ts @@ -102,6 +102,7 @@ export function makeSecretScrubberCore() { /** First characters of every form's head: a cheap filter for held tails. */ let firstCharacters = new Set(); let longestHead = 0; + let longestFormBytes = 0; const holdsWatched = (text: string) => forms.some((form) => text.includes(form.text)); @@ -109,6 +110,7 @@ export function makeSecretScrubberCore() { 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)); + longestFormBytes = Math.max(0, ...forms.map((form) => Buffer.byteLength(form.text, "utf8"))); // A placeholder or notice must never spell out another watched key, as a // name chosen equal to one would. for (const entry of entries) { @@ -394,6 +396,14 @@ export function makeSecretScrubberCore() { findMatches, replaceMatches, startingTail, + /** + * The longest form any watched value takes, in UTF-8 bytes: a reader that + * keeps a file's end reads this much more first, so a value reaching into + * the end starts inside what it read and is hidden whole. + */ + get longestFormBytes() { + return longestFormBytes; + }, get size() { return entries.length; }, diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index ad361d8e7..1aecc2894 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -186,6 +186,7 @@ import { McpApps } from "./mcpApps/McpApps.ts"; import { CommandRuns } from "./commandRuns/CommandRuns.ts"; import { AgentSettingsChanges } from "./settingsChanges/AgentSettingsChanges.ts"; import { AgentSecretRequests } from "./secrets/AgentSecretRequests.ts"; +import { layer as SecretScrubberLive } from "./secrets/SecretScrubber.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; @@ -797,6 +798,8 @@ const buildAppUnderTest = (options?: { Layer.mock(AgentSettingsChanges)({}), // So are agents' requests for keys (AgentSecretRequests.test.ts). Layer.mock(AgentSecretRequests)({ destinations: {} as never }), + // The watched keys' registry, empty: the routes' doors read it. + SecretScrubberLive, Layer.mock(CommandRuns)({ request: () => Effect.succeed({ outcome: "off" as const, detail: "off in this test" }), start: () => Effect.fail(new CommandRunError({ message: "No runs in this test." })), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 484fce885..66f28cc7e 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -438,7 +438,8 @@ 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), + // The registry itself sits at the bottom of the runtime, for every door. + Layer.provide(SecretScrubber.loadSavedKeys), Layer.provideMerge(ProviderSessionDirectoryLayerLive), // The session fence reads the thread's row (docs/design/fleet.md, Part 3b). Layer.provide(ThreadSessionAdmissionLive.pipe(Layer.provide(ProjectionThreadRepositoryLive))), @@ -707,7 +708,12 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe( // `ProviderService` (canonical stream, written after event normalization). // Provided once at the runtime level so every consumer sees the same // logger instances. - Layer.provideMerge(ProviderEventLoggersLive), + // + // Under them, the watched keys (docs/design/secret-scrubbing.md): one + // registry under every place that shows, stores or logs agent text, the + // native log included. Filled by the provider layer's `loadSavedKeys` and + // by Save. + Layer.provideMerge(ProviderEventLoggersLive.pipe(Layer.provideMerge(SecretScrubber.layer))), Layer.provideMerge(ServerSettingsLive), Layer.provideMerge(WorkspaceLayerLive), Layer.provideMerge(ProjectFaviconResolverLive), diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index be9925c63..9dea937cb 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -38,6 +38,7 @@ import { type PtySpawnInput, PtySpawnError, } from "../Services/PTY.ts"; +import { makeSecretScrubber } from "../../secrets/SecretScrubber.ts"; import { makeTerminalManagerWithOptions, type TerminalProcessTreeControl } from "./Manager.ts"; import { SERVER_ADDED_VARIABLE, @@ -212,6 +213,7 @@ const multiTerminalHistoryLogPath = ( ); interface CreateManagerOptions { + scrubText?: (text: string, options?: { readonly cutTail?: boolean }) => string; shellResolver?: () => string; platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; @@ -269,6 +271,7 @@ const createManager = ( historyLineLimit, ptyAdapter, ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}), + ...(options.scrubText !== undefined ? { scrubText: options.scrubText } : {}), ...(options.platform !== undefined ? { platform: options.platform } : {}), ...(options.env !== undefined ? { env: options.env } : {}), ...(options.subprocessChecker !== undefined @@ -2252,6 +2255,60 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( }), ); + it.effect("hides a saved key in a run's output before cutting it to its end", () => + Effect.gen(function* () { + // A key of many lines where the cut to the last 16,000 characters falls: + // cut first, the lines after the cut would reach the thread. + const key = Array.from({ length: 12 }, (_, line) => `${line}a1b2c3d4`.repeat(6)).join("\n"); + const scrubber = makeSecretScrubber(); + scrubber.watch("DEPLOY_KEY", key); + const { manager, ptyAdapter } = yield* createManager(50, { + platform: "darwin", + shellResolver: () => "/bin/zsh", + scrubText: (text) => scrubber.scrubText(text).text, + }); + yield* manager.startCommandRun(commandRunInput({ command: "cat deploy.log" })); + const after = Array.from({ length: 245 }, () => "y".repeat(63)).join("\r\n"); + ptyAdapter.processes[0]!.emitData( + `\u001b]6973;run-1;start\u0007${key.replaceAll("\n", "\r\n")}\r\n${after}\r\nDONE\r\n`, + ); + yield* waitFor( + manager + .readCommandRunOutput("run-1") + .pipe(Effect.map((out) => out?.endsWith("DONE") === true)), + ); + const output = (yield* manager.readCommandRunOutput("run-1")) ?? ""; + expect(output).toContain("[DEPLOY_KEY hidden]"); + expect(output).not.toContain("a1b2c3d4"); + }), + ); + + it.effect("leaves out the start of a long key a run is still printing", () => + Effect.gen(function* () { + const key = `sk_live_${"9fK2".repeat(75)}`; + const scrubber = makeSecretScrubber(); + scrubber.watch("STRIPE_SECRET_KEY", key); + const { manager, ptyAdapter } = yield* createManager(50, { + platform: "darwin", + shellResolver: () => "/bin/zsh", + scrubText: (text, options) => scrubber.scrubText(text, options).text, + }); + yield* manager.startCommandRun(commandRunInput({ command: "cat .env" })); + // Paused halfway: too short to match a 300-character key yet. + ptyAdapter.processes[0]!.emitData( + `\u001b]6973;run-1;start\u0007loading\r\nKEY=${key.slice(0, 150)}`, + ); + yield* waitFor( + manager + .readCommandRunOutput("run-1") + .pipe(Effect.map((out) => out?.startsWith("loading") === true)), + ); + const output = (yield* manager.readCommandRunOutput("run-1")) ?? ""; + expect(output).not.toContain("9fK2"); + expect(output).toContain("KEY="); + }), + ); + it.effect("refuses to run a POSIX command where only PowerShell can run it", () => Effect.gen(function* () { const { manager } = yield* createManager(50, { diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 59b0022b7..f884349be 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -41,6 +41,7 @@ import { ChildProcessSpawner } from "effect/process"; import { writeFileStringAtomically } from "../../atomicWrite.ts"; import { ServerConfig } from "../../config.ts"; +import { SecretScrubber } from "../../secrets/SecretScrubber.ts"; import { ProcessSnapshot, readListeningPortRows, @@ -1467,6 +1468,11 @@ const defaultProcessTreeControl: TerminalProcessTreeControl = { interface TerminalManagerOptions { logsDir: string; + /** + * Hides watched keys in a run's rendered output before it is cut to its + * tail, so a cut can't leave part of one (docs/design/secret-scrubbing.md). + */ + scrubText?: (text: string, options?: { readonly cutTail?: boolean }) => string; historyLineLimit?: number; historyCharLimit?: number; persistDebounceMs?: number; @@ -1622,8 +1628,10 @@ const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () { const { terminalLogsDir } = yield* ServerConfig; const ptyAdapter = yield* PtyAdapter; const processSnapshot = yield* ProcessSnapshot; + const secretScrubber = yield* SecretScrubber; return yield* makeTerminalManagerWithOptions({ logsDir: terminalLogsDir, + scrubText: (text, options) => secretScrubber.scrubText(text, options).text, ptyAdapter, processRowsReader: () => processSnapshot.readTree, }); @@ -1637,6 +1645,14 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const runFork = Effect.runForkWith(context); const logsDir = options.logsDir; + const scrubText = options.scrubText ?? ((text: string) => text); + /** + * A run's rendered output as it reaches the thread: keys hidden, then cut + * to its tail. `live`: read while it may still be printing, so a tail + * that could be the start of a key goes too. + */ + const runOutputOf = (rendered: string, clipped: boolean, live = false) => + clipCommandOutput(scrubText(rendered, { cutTail: live }), clipped); const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; const historyCharLimit = options.historyCharLimit ?? DEFAULT_HISTORY_CHAR_LIMIT; const persistDebounceMs = options.persistDebounceMs ?? DEFAULT_PERSIST_DEBOUNCE_MS; @@ -2591,7 +2607,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith return; } const rendered = yield* Effect.promise(() => renderTerminalText(end.run.output, end.cols)); - const output = clipCommandOutput(rendered, end.run.outputClipped); + const output = runOutputOf(rendered, end.run.outputClipped); yield* publishRunUpdate( end.kind === "finished" ? { @@ -2625,7 +2641,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith const output = captured === null ? null - : clipCommandOutput( + : runOutputOf( yield* Effect.promise(() => renderTerminalText(captured.raw, captured.cols)), captured.clipped, ); @@ -4699,7 +4715,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ); if (found === null) return null; const text = yield* Effect.promise(() => renderTerminalText(found.raw, found.cols)); - return clipCommandOutput(text, found.clipped); + return runOutputOf(text, found.clipped, true); }); const close: TerminalManagerShape["close"] = (input) => diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 9bea2c17b..58ebac1e5 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -191,6 +191,12 @@ import { ProjectSetupSource } from "./projectSetup/ProjectSetupSource.ts"; import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts"; import { ServerAuth } from "./auth/Services/ServerAuth.ts"; import { makeBackgroundRunOutputReader } from "./diagnostics/BackgroundRunOutput.ts"; +import { + scrubExternalThreadList, + scrubTranscript, + scrubWorkflowRunFile, +} from "./secrets/readBackScrubbing.ts"; +import { SecretScrubber } from "./secrets/SecretScrubber.ts"; import { makeWorkflowRunRequests } from "./orchestration/workflowRunRequests.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; @@ -877,6 +883,7 @@ const makeCoreRpcLayer = ( const projectSetups = yield* ProjectSetups; const projectSetupSource = yield* ProjectSetupSource; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const secretScrubber = yield* SecretScrubber; const agentPages = yield* AgentPages; const mcpApps = yield* McpApps; const commandRuns = yield* CommandRuns; @@ -952,7 +959,10 @@ const makeCoreRpcLayer = ( Effect.catch(() => Ref.get(sentFromRef)), ); const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; - const readBackgroundRunOutput = makeBackgroundRunOutputReader(projectionSnapshotQuery); + const readBackgroundRunOutput = makeBackgroundRunOutputReader( + projectionSnapshotQuery, + secretScrubber, + ); const workflowRunRequests = makeWorkflowRunRequests({ projectionSnapshotQuery, providerService, @@ -1816,6 +1826,9 @@ const makeCoreRpcLayer = ( observeRpcEffect( WS_METHODS.serverReadSubagentTranscript, providerService.readSubagentTranscript(input).pipe( + // Read straight from the provider's files: hide saved keys + // (docs/design/secret-scrubbing.md), as for the next three. + Effect.map((result) => scrubTranscript(secretScrubber, result)), Effect.mapError( (error) => new ProviderSubagentTranscriptError({ @@ -1867,6 +1880,7 @@ const makeCoreRpcLayer = ( observeRpcEffect( WS_METHODS.serverListExternalProviderThreads, providerService.listExternalThreads(input).pipe( + Effect.map((result) => scrubExternalThreadList(secretScrubber, result)), Effect.mapError( (error) => new ProviderExternalThreadError({ @@ -1887,6 +1901,7 @@ const makeCoreRpcLayer = ( providerService, projectionSnapshotQuery, orchestrationEngine, + secretScrubber, }), { "rpc.aggregate": "server" }, ), @@ -2180,13 +2195,17 @@ const makeCoreRpcLayer = ( [WS_METHODS.serverReadWorkflowRunFile]: (input) => observeRpcEffect( WS_METHODS.serverReadWorkflowRunFile, - workflowRunRequests.readRunFile(input), + workflowRunRequests + .readRunFile(input) + .pipe(Effect.map((result) => scrubWorkflowRunFile(secretScrubber, result))), { "rpc.aggregate": "server" }, ), [WS_METHODS.serverReadWorkflowAgentTranscript]: (input) => observeRpcEffect( WS_METHODS.serverReadWorkflowAgentTranscript, - workflowRunRequests.readAgentTranscript(input), + workflowRunRequests + .readAgentTranscript(input) + .pipe(Effect.map((result) => scrubTranscript(secretScrubber, result))), { "rpc.aggregate": "server" }, ), [WS_METHODS.serverSaveWorkflowCommand]: (input) => diff --git a/docs/design/secret-scrubbing.md b/docs/design/secret-scrubbing.md index c6fffdc09..7ec2046a0 100644 --- a/docs/design/secret-scrubbing.md +++ b/docs/design/secret-scrubbing.md @@ -1,10 +1,10 @@ # 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 +Status: plan rev 4 (Nov 19 2026). Step 2a (the scrubber and provider output) and step 2b (the other doors) 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". +"Review" at the end says what each changed. Will chose to keep the debug +logs ("The debug logs"). ## The problem @@ -263,7 +263,9 @@ 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. +for text that stops in the middle of a value covers that (`cutTail` on +every read of output that may still be printing: the terminal's live read, +Claude's running command, a background run's file). The request is checked too. `request` (`:122`) refuses a command or a reason that contains a watched value: "This command contains @@ -280,13 +282,19 @@ 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. +- The room endpoint's handlers are one object (`McpRoomServer.ts`). Every + tool that changes something goes through one wrapper (`changes`), which + checks the input with `contains` and refuses a call that has a watched + value: "Your call contains STRIPE_SECRET_KEY. Don't pass a key through + this tool. The other agent can ask the user for it." Two tools that only + touch the caller's own thread but store what they are given + (`secret_request`'s card and `scheduled_run_finish`'s summary) are + checked the same way. Reads (`room_history`, `thread_read`, the guide) + are not: they store nothing. +- `show_page` (`AgentPages.ts`, `publish`) refuses a page whose title, + content or icon holds a watched value: "Your page contains + STRIPE_SECRET_KEY. Don't put a key on a page; name the file it is in + instead." Theme pages go through `publish` too. - 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. @@ -300,16 +308,19 @@ 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 +- a running command's output (`ClaudeAdapter.ts`, `readCommandOutput`): + the adapter hands back the whole of what Claude kept (8 KiB at most), and + `ProviderService.readCommandOutput` scrubs it, 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`: +The others return whole strings. Their `ws.ts` handlers scrub the fields a +person reads (`secrets/readBackScrubbing.ts`), never ids, cursors or status +words, so a key that equals one can't break the reply or an import that +sends the id back: - `serverReadSubagentTranscript` (`:1813`) - `serverListExternalProviderThreads` (`:1864`, titles and previews) @@ -321,8 +332,9 @@ through `scrubDeep`: 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. +Its name, preview and messages are scrubbed once, right after it is read and +before anything is dispatched (`scrubExternalThreadSnapshot`); a failed +attach's error is scrubbed before it is stored. ### 6. Provider failure text @@ -332,7 +344,10 @@ Muse append the end of the process's stderr to a failure `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`). +on its result, on the side-answer start error, and at the two places the +reactor stores such text, so callers that pass a cause as it is (a failed +interrupt or approval answer) are covered too: the failure activity's +detail and the session's `lastError`. ### 7. The debug logs @@ -345,11 +360,14 @@ Two files per thread under `/logs/provider/`, kept 30 days: 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`). +`makeEventNdjsonLogger` takes an optional `scrubLine`, applied to each +record's JSON line before it is written. For the native logger, +`ProviderEventLoggersLive` searches the line, and only a line with a match +is parsed, scrubbed with `scrubDeep` and written again, so a value ending in +a quote can't take the line's own quote and break it. The +three adapters that can build a logger of their own (`ClaudeAdapter.ts`, +`CodexAdapter.ts`, `AcpAdapter.ts`, from `nativeEventLogPath`) do so only +in tests; the server always hands them the shared one. 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 @@ -377,8 +395,7 @@ goes stale with every provider release. There are two honest designs: 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. +Will chose to keep the logs, so the quiet-logs flag was not built. ## Streams @@ -588,15 +605,18 @@ Step 2b: the other doors. 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 +- `apps/server/src/provider/Layers/ClaudeAdapter.ts` and + `ProviderService.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. +- `apps/server/src/provider/Layers/EventNdjsonLogger.ts` and + `ProviderEventLoggers.ts`: `scrubLine`. +- `apps/server/src/secrets/SecretScrubber.ts` and `server.ts`: the registry + (`layer`) sits at the bottom of the runtime, under every door above; + `loadSavedKeys` fills it inside the provider layer. ## Testing