Skip to content

Commit 1eb9b1c

Browse files
t3dotggclaude
andcommitted
feat(server): request_secret can save a CLI token to a private file
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a8603af commit 1eb9b1c

13 files changed

Lines changed: 186 additions & 11 deletions

File tree

‎apps/mobile/src/features/threads/SecretRequestCard.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import {
22
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
3-
SECRET_REQUEST_PRIVACY_NOTE,
43
secretRequestAnswerInput,
54
secretRequestDisplay,
65
secretRequestFailureMessage,
6+
secretRequestPrivacyNote,
77
type SecretRequestItem,
88
} from "@t3tools/client-runtime/secret-request";
99
import {
@@ -144,7 +144,7 @@ function PendingSecretRequestForm(props: {
144144
type="monochrome"
145145
/>
146146
<Text className="flex-1 font-sans text-xs text-foreground-muted">
147-
{SECRET_REQUEST_PRIVACY_NOTE}
147+
{secretRequestPrivacyNote(item)}
148148
</Text>
149149
</View>
150150
<Button

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1969,6 +1969,7 @@ const make = Effect.gen(function* () {
19691969
label: input.label,
19701970
reason: input.reason,
19711971
...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }),
1972+
...(input.delivery === "file" ? { delivery: "file" as const } : {}),
19721973
secretStatus,
19731974
})
19741975
.pipe(
@@ -2047,6 +2048,12 @@ const make = Effect.gen(function* () {
20472048
yield* Effect.annotateCurrentSpan({ "secret_request.status": status });
20482049
yield* Metrics.increment(Metrics.secretRequestsTotal, { status });
20492050
if (status !== "saved") return { status };
2051+
if (input.delivery === "file") {
2052+
const file = yield* secretRequests
2053+
.saveToFile({ threadId, turnItemId })
2054+
.pipe(Effect.mapError((error) => failure("orchestration_error", error.message)));
2055+
return { status, file };
2056+
}
20502057
const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId });
20512058
if (Option.isNone(secretRef)) {
20522059
return yield* failure(

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
189189

190190
const RequestSecretTool = Tool.make("request_secret", {
191191
description:
192-
"Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is kept by the app and NEVER returned to you or shown in the transcript. When saved, the result carries a secretRef: pass it to a tool that accepts one (e.g. schedule_task's signature.secretRef). It works once. Never ask for secrets in chat, and never invent one.",
192+
"Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is NEVER returned to you or shown in the transcript. By default the result carries a one-use secretRef for a tool that accepts one (e.g. schedule_task's signature.secretRef). For a shell CLI token, set delivery to file. Never ask for secrets in chat, and never invent one.",
193193
parameters: OrchestratorMcpRequestSecretInput,
194194
success: OrchestratorMcpRequestSecretResult,
195195
failure: OrchestratorMcpFailure,

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7749,6 +7749,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
77497749
label: command.label,
77507750
reason: command.reason,
77517751
...(command.placeholder === undefined ? {} : { placeholder: command.placeholder }),
7752+
...(command.delivery === undefined ? {} : { delivery: command.delivery }),
77527753
secretStatus: command.secretStatus,
77537754
};
77547755
yield* emit(

‎apps/server/src/secrets/SecretRequests.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import { assert, it } from "@effect/vitest";
4+
import * as HostProcess from "@t3tools/shared/HostProcess";
45
import {
56
ProjectId,
67
type OrchestrationV2ServerCommand,
8+
SecretRef,
79
ThreadId,
810
TurnItemId,
911
} from "@t3tools/contracts";
1012
import * as Effect from "effect/Effect";
13+
import * as FileSystem from "effect/FileSystem";
1114
import * as Layer from "effect/Layer";
1215
import * as Metric from "effect/Metric";
1316
import * as Tracer from "effect/Tracer";
1417
import * as Option from "effect/Option";
18+
import * as Path from "effect/Path";
1519
import * as PlatformError from "effect/PlatformError";
20+
import * as TestClock from "effect/testing/TestClock";
1621

1722
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
1823
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
@@ -30,6 +35,8 @@ const withService = <A, E>(
3035
}) => Effect.Effect<A, E>,
3136
options: {
3237
readonly threadId?: ThreadId;
38+
readonly delivery?: "file";
39+
readonly directory?: string;
3340
readonly runStatus?: string;
3441
readonly removeFails?: boolean;
3542
readonly closedFirst?: boolean;
@@ -48,6 +55,7 @@ const withService = <A, E>(
4855
Layer.succeed(
4956
ServerSecretStore.ServerSecretStore,
5057
ServerSecretStore.ServerSecretStore.of({
58+
...(options.directory === undefined ? {} : { directory: options.directory }),
5159
get: (name) => Effect.yieldNow.pipe(Effect.as(Option.fromNullishOr(stored.get(name)))),
5260
set: (name, value) => Effect.sync(() => void stored.set(name, value)),
5361
create: (name, value) =>
@@ -98,6 +106,7 @@ const withService = <A, E>(
98106
type: "secret_request",
99107
label: "GitHub token",
100108
reason: "Used as GH_TOKEN.",
109+
...(options.delivery === undefined ? {} : { delivery: options.delivery }),
101110
secretStatus,
102111
},
103112
],
@@ -338,3 +347,61 @@ it.effect("a used value that cannot be deleted is not handed out", () =>
338347
{ removeFails: true },
339348
),
340349
);
350+
351+
const SECRET_FILE_TTL_MS = 24 * 60 * 60 * 1000;
352+
353+
it.effect("a file request moves its value to an owner-only file, once", () =>
354+
Effect.gen(function* () {
355+
const fs = yield* FileSystem.FileSystem;
356+
const path = yield* Path.Path;
357+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" });
358+
const file = yield* withService(
359+
({ service, stored, dispatched }) =>
360+
Effect.gen(function* () {
361+
yield* service.answer({
362+
threadId,
363+
turnItemId,
364+
answer: { type: "save", secret: "cf_token'$(id)" },
365+
});
366+
assert.include(dispatched[0] as object, { secretStatus: "saved", delivery: "file" });
367+
const file = yield* service.saveToFile({ threadId, turnItemId });
368+
assert.equal(yield* fs.readFileString(file), "cf_token'$(id)");
369+
assert.deepEqual(valuesOf(stored), []);
370+
if ((yield* HostProcess.Platform) !== "win32") {
371+
assert.equal((yield* fs.stat(file)).mode & 0o777, 0o600);
372+
assert.equal((yield* fs.stat(path.dirname(file))).mode & 0o777, 0o700);
373+
}
374+
// A retried request_secret gets the same file; the value is never a ref again.
375+
assert.equal(yield* service.saveToFile({ threadId, turnItemId }), file);
376+
const ref = SecretRef.make(`secret-ref:${path.basename(file)}`);
377+
const reused = yield* service.consume({ ref, projectId }).pipe(Effect.flip);
378+
assert.equal(reused.reason, "ref_unavailable");
379+
return file;
380+
}),
381+
{ delivery: "file", directory },
382+
);
383+
384+
const { mtime } = yield* fs.stat(file);
385+
yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS);
386+
yield* withService(() => Effect.void, { directory });
387+
assert.isTrue(yield* fs.exists(file));
388+
yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS + 1);
389+
yield* withService(() => Effect.void, { directory });
390+
assert.isFalse(yield* fs.exists(file));
391+
}).pipe(Effect.provide(NodeServices.layer)),
392+
);
393+
394+
it.effect("a secret the card promised to keep from the agent is never written to a file", () =>
395+
withService(({ service, stored }) =>
396+
Effect.gen(function* () {
397+
yield* service.answer({
398+
threadId,
399+
turnItemId,
400+
answer: { type: "save", secret: "ghp_secret" },
401+
});
402+
const refused = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip);
403+
assert.equal(refused.reason, "not_a_file_request");
404+
assert.isTrue(valuesOf(stored).some((value) => value.includes("ghp_secret")));
405+
}),
406+
),
407+
);

‎apps/server/src/secrets/SecretRequests.ts‎

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Answers stay in the secret store behind one-use refs; orchestration records only request status.
22
// Consuming tools keep values out of transcripts, projections, clients and model context.
3+
// A `file` request instead moves its value to an owner-only file for the agent's own shell.
34
import {
45
CommandId,
56
SecretRef,
@@ -17,6 +18,7 @@ import * as Effect from "effect/Effect";
1718
import * as FileSystem from "effect/FileSystem";
1819
import * as Layer from "effect/Layer";
1920
import * as Option from "effect/Option";
21+
import * as Path from "effect/Path";
2022
import * as Schedule from "effect/Schedule";
2123
import * as Schema from "effect/Schema";
2224
import * as Semaphore from "effect/Semaphore";
@@ -30,6 +32,7 @@ const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PRE
3032
const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/;
3133
const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
3234
const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
35+
const FILE_NAME_PATTERN = /^[0-9a-f]{32}$/;
3336

3437
const refFor = (salt: string, threadId: ThreadId, turnItemId: string) =>
3538
SecretRef.make(
@@ -57,13 +60,21 @@ export class SecretRequests extends Context.Service<
5760
readonly ref: SecretRef;
5861
readonly projectId: ProjectId;
5962
}) => Effect.Effect<string, SecretRequestError>;
63+
/** Moves a saved `file` request's value to an owner-only file and returns its path. */
64+
readonly saveToFile: (input: {
65+
readonly threadId: ThreadId;
66+
readonly turnItemId: string;
67+
}) => Effect.Effect<string, SecretRequestError>;
6068
}
6169
>()("t3/secrets/SecretRequests") {}
6270

6371
const make = Effect.gen(function* () {
6472
const store = yield* ServerSecretStore.ServerSecretStore;
6573
const fileSystem = yield* FileSystem.FileSystem;
74+
const path = yield* Path.Path;
6675
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
76+
// Beside the store's own files so the same owner-only directory and cleanup rules apply.
77+
const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files");
6778

6879
const salt = Buffer.from(
6980
yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
@@ -124,6 +135,7 @@ const make = Effect.gen(function* () {
124135
label: item.label,
125136
reason: item.reason,
126137
...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),
138+
...(item.delivery === undefined ? {} : { delivery: item.delivery }),
127139
secretStatus,
128140
})
129141
.pipe(
@@ -210,6 +222,43 @@ const make = Effect.gen(function* () {
210222
return decoded.value.value;
211223
});
212224

225+
const saveToFile: SecretRequests["Service"]["saveToFile"] = Effect.fn(
226+
"SecretRequests.saveToFile",
227+
)(function* (input) {
228+
const records = yield* threadManagement
229+
.getThreadRecords(input.threadId, ["turnItems"], {
230+
turnItemTypes: ["secret_request"],
231+
messageRoles: [],
232+
})
233+
.pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
234+
const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
235+
// Only a card that told the user the agent's commands can read the value may write it out.
236+
if (
237+
item?.type !== "secret_request" ||
238+
item.secretStatus !== "saved" ||
239+
item.delivery !== "file"
240+
) {
241+
return yield* new SecretRequestError({ reason: "not_a_file_request" });
242+
}
243+
if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
244+
const ref = refFor(salt, input.threadId, item.id);
245+
const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));
246+
return yield* Effect.gen(function* () {
247+
// A retry with the same clientRequestId gets the file the first call wrote.
248+
if (yield* fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))) return file;
249+
const value = yield* consumeRef({ ref, projectId: records.thread.projectId });
250+
yield* fileSystem.makeDirectory(filesDir, { recursive: true, mode: 0o700 }).pipe(
251+
Effect.andThen(fileSystem.chmod(filesDir, 0o700)),
252+
// `wx` never follows or replaces an existing path.
253+
Effect.andThen(
254+
fileSystem.writeFile(file, new TextEncoder().encode(value), { flag: "wx", mode: 0o600 }),
255+
),
256+
Effect.mapError((cause) => new SecretRequestError({ reason: "store_failed", cause })),
257+
);
258+
return file;
259+
}).pipe(consumeLock.withPermits(1));
260+
});
261+
213262
const sweepExpired = Effect.gen(function* () {
214263
if (store.directory === undefined) return;
215264
const now = yield* Clock.currentTimeMillis;
@@ -231,14 +280,32 @@ const make = Effect.gen(function* () {
231280
Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)),
232281
Effect.withSpan("SecretRequests.sweepExpired"),
233282
);
234-
yield* sweepExpired;
235-
yield* sweepExpired.pipe(
283+
const sweepExpiredFiles = Effect.gen(function* () {
284+
if (filesDir === undefined || !(yield* fileSystem.exists(filesDir))) return;
285+
const now = yield* Clock.currentTimeMillis;
286+
let removed = 0;
287+
for (const name of yield* fileSystem.readDirectory(filesDir)) {
288+
if (!FILE_NAME_PATTERN.test(name)) continue;
289+
const file = path.join(filesDir, name);
290+
const { mtime } = yield* fileSystem.stat(file);
291+
if (Option.exists(mtime, (time) => now - time.getTime() <= SECRET_REF_TTL_MS)) continue;
292+
yield* fileSystem.remove(file);
293+
removed += 1;
294+
}
295+
yield* Effect.annotateCurrentSpan({ "secret_request.expired_files_removed": removed });
296+
}).pipe(
297+
Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret files", cause)),
298+
Effect.withSpan("SecretRequests.sweepExpiredFiles"),
299+
);
300+
const sweep = Effect.andThen(sweepExpired, sweepExpiredFiles);
301+
yield* sweep;
302+
yield* sweep.pipe(
236303
Effect.delay("1 hour"),
237304
Effect.repeat(Schedule.spaced("1 hour")),
238305
Effect.forkScoped,
239306
);
240307

241-
return SecretRequests.of({ answer, savedRef, consume });
308+
return SecretRequests.of({ answer, savedRef, consume, saveToFile });
242309
});
243310

244311
export const layer = Layer.effect(SecretRequests, make);

‎apps/web/src/components/chat/SecretRequestCard.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import {
22
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
3-
SECRET_REQUEST_PRIVACY_NOTE,
43
secretRequestAnswerInput,
54
secretRequestDisplay,
65
secretRequestFailureMessage,
6+
secretRequestPrivacyNote,
77
type SecretRequestItem,
88
} from "@t3tools/client-runtime/secret-request";
99
import {
@@ -150,7 +150,7 @@ function PendingSecretRequestForm(props: {
150150
className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
151151
>
152152
<ShieldCheckIcon className="size-3.5 shrink-0" aria-hidden />
153-
{SECRET_REQUEST_PRIVACY_NOTE}
153+
{secretRequestPrivacyNote(item)}
154154
</p>
155155
<Button
156156
type="button"

‎packages/client-runtime/src/secretRequest.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import { SecretRequestError } from "@t3tools/contracts";
22
import { describe, expect, it } from "vite-plus/test";
33

4-
import { secretRequestDisplay, secretRequestFailureMessage } from "./secretRequest.ts";
4+
import {
5+
secretRequestDisplay,
6+
secretRequestFailureMessage,
7+
secretRequestPrivacyNote,
8+
} from "./secretRequest.ts";
59

610
describe("secretRequestDisplay", () => {
711
it("never offers the form for a request inherited from another thread", () => {
@@ -15,6 +19,13 @@ describe("secretRequestDisplay", () => {
1519
});
1620
});
1721

22+
describe("secretRequestPrivacyNote", () => {
23+
it("does not promise to hide a value that the agent's commands can read", () => {
24+
expect(secretRequestPrivacyNote({})).toBe("Stored securely, never shown to the agent");
25+
expect(secretRequestPrivacyNote({ delivery: "file" })).not.toContain("never shown");
26+
});
27+
});
28+
1829
describe("secretRequestFailureMessage", () => {
1930
it("passes through server errors but hides anything that could echo the payload", () => {
2031
expect(

‎packages/client-runtime/src/secretRequest.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ export type SecretRequestItem = Extract<
55
{ readonly type: "secret_request" }
66
>;
77

8-
export const SECRET_REQUEST_PRIVACY_NOTE = "Stored securely, never shown to the agent";
8+
/** A `file` request lets the agent's commands read the value, so its card must not promise more. */
9+
export const secretRequestPrivacyNote = (item: Pick<SecretRequestItem, "delivery">) =>
10+
item.delivery === "file"
11+
? "Kept out of chat, in a private file this agent's commands can read for 24 hours"
12+
: "Stored securely, never shown to the agent";
913
export const SECRET_REQUEST_DEFAULT_PLACEHOLDER = "Paste the secret";
1014

1115
export type SecretRequestDisplay =

‎packages/contracts/src/orchestrationV2.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1391,11 +1391,15 @@ export const OrchestrationV2SecretRequestStatus = Schema.Literals([
13911391
]);
13921392
export type OrchestrationV2SecretRequestStatus = typeof OrchestrationV2SecretRequestStatus.Type;
13931393

1394+
/** `file`: the value goes to an owner-only file the agent's shell commands can read. */
1395+
export const OrchestrationV2SecretRequestDelivery = Schema.Literal("file");
1396+
13941397
const OrchestrationV2SecretRequestFields = {
13951398
type: Schema.Literal("secret_request"),
13961399
label: TrimmedNonEmptyString,
13971400
reason: Schema.String,
13981401
placeholder: Schema.optional(Schema.String),
1402+
delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
13991403
secretStatus: OrchestrationV2SecretRequestStatus,
14001404
} as const;
14011405

@@ -3230,6 +3234,7 @@ const OrchestrationV2InternalCommand = Schema.Union([
32303234
label: TrimmedNonEmptyString,
32313235
reason: Schema.String,
32323236
placeholder: Schema.optional(Schema.String),
3237+
delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
32333238
secretStatus: OrchestrationV2SecretRequestStatus,
32343239
}),
32353240
]);

0 commit comments

Comments
 (0)