@devries-cameron20 / t3code-1 / commits / 7462b16f36
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(secrets): answer a secret request with a secret provider reference (#31670)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 5, 2026 at 15:26 UTC 7462b16f369d36af51af2e3c50bc35b45cd7284a
21 files changed +549 -92
apps/mobile/src/features/threads/SecretRequestCard.tsx
+94 -22
@@ -5,13 +5,21 @@ import {
5 secretRequestDisplay,
6 secretRequestFailureMessage,
7 secretRequestPrivacyNote,
8 + secretRequestReference,
9 + secretRequestSources,
10 type SecretRequestItem,
11 + type SecretRequestReply,
12 } from "@t3tools/client-runtime/secret-request";
13 import {
14 isAtomCommandInterrupted,
15 squashAtomCommandFailure,
16 } from "@t3tools/client-runtime/state/runtime";
14 -import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
17 +import type {
18 + EnvironmentId,
19 + OrchestrationV2ProjectedTurnItem,
20 + SecretProviderId,
21 +} from "@t3tools/contracts";
22 +import { useAtomValue } from "@effect/atom-react";
23 import { useRef, useState } from "react";
24 import { View, type ColorValue } from "react-native";
25
@@ -20,6 +28,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/
28 import { serverEnvironment } from "../../state/server";
29 import { useAtomCommand } from "../../state/use-atom-command";
30 import { Button } from "../../components/ui/Button";
31 +import { Chip } from "../../components/ui/Chip";
32
33 const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" };
34 const PRIVATE_SYMBOL: AppSymbolName = { ios: "checkmark.shield", android: "lock" };
@@ -69,15 +78,18 @@ function PendingSecretRequestForm(props: {
78 reportFailure: false,
79 reportDefect: false,
80 });
81 + const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
82 + const sources = secretRequestSources(config, config?.settings.secretProviders ?? {});
83 + const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
84 + const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
85 const [secret, setSecret] = useState("");
86 + const [reference, setReference] = useState("");
87 const [submitting, setSubmitting] = useState(false);
88 const [error, setError] = useState<string | null>(null);
89 // Submit then a tap can both run before a re-render; this guard is synchronous.
90 const inFlight = useRef(false);
91
78 - const send = async (
79 - reply: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" },
80 - ) => {
92 + const send = async (reply: SecretRequestReply) => {
93 const input = secretRequestAnswerInput(item, reply);
94 if (input === null || inFlight.current) return;
95 inFlight.current = true;
@@ -89,12 +101,23 @@ function PendingSecretRequestForm(props: {
101 });
102 if (result._tag === "Success") {
103 setSecret("");
104 + setReference("");
105 return;
106 }
107 if (!isAtomCommandInterrupted(result)) {
108 pipe(squashAtomCommandFailure(result), secretRequestFailureMessage, setError);
109 }
110 };
111 + const save = () => {
112 + if (source === null) {
113 + void send({ type: "save", secret });
114 + } else if (secretRequestReference(source, reference) === undefined) {
115 + setError(source.invalidReferenceMessage);
116 + } else {
117 + void send({ type: "reference", source, reference });
118 + }
119 + };
120 + const draft = source === null ? secret : reference;
121
122 return (
123 <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
@@ -106,22 +129,71 @@ function PendingSecretRequestForm(props: {
129 </Text>
130 ) : null}
131 </View>
109 - <TextInput
110 - accessibilityLabel={item.label}
111 - placeholder={item.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER}
112 - value={secret}
113 - onChangeText={setSecret}
114 - editable={!submitting}
115 - secureTextEntry
116 - autoCorrect={false}
117 - autoCapitalize="none"
118 - autoComplete="off"
119 - textContentType="none"
120 - importantForAutofill="no"
121 - spellCheck={false}
122 - returnKeyType="done"
123 - onSubmitEditing={() => void send({ type: "save", secret })}
124 - />
132 + {sources.length > 0 ? (
133 + <View className="flex-row flex-wrap gap-2">
134 + <Chip
135 + label="Value"
136 + size="small"
137 + selected={source === null}
138 + disabled={submitting}
139 + onPress={() => {
140 + setSourceId(null);
141 + setError(null);
142 + }}
143 + />
144 + {sources.map((candidate) => (
145 + <Chip
146 + key={candidate.id}
147 + label={candidate.label}
148 + size="small"
149 + selected={candidate.id === source?.id}
150 + disabled={submitting}
151 + onPress={() => {
152 + setSourceId(candidate.id);
153 + setError(null);
154 + }}
155 + />
156 + ))}
157 + </View>
158 + ) : null}
159 + {source === null ? (
160 + <TextInput
161 + accessibilityLabel={item.label}
162 + placeholder={item.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER}
163 + value={secret}
164 + onChangeText={setSecret}
165 + editable={!submitting}
166 + secureTextEntry
167 + autoCorrect={false}
168 + autoCapitalize="none"
169 + autoComplete="off"
170 + textContentType="none"
171 + importantForAutofill="no"
172 + spellCheck={false}
173 + returnKeyType="done"
174 + onSubmitEditing={save}
175 + />
176 + ) : (
177 + <TextInput
178 + key={source.id}
179 + accessibilityLabel={`${item.label} reference in ${source.label}`}
180 + placeholder={source.referencePlaceholder}
181 + value={reference}
182 + onChangeText={(next) => {
183 + setReference(next);
184 + setError(null);
185 + }}
186 + editable={!submitting}
187 + autoCorrect={false}
188 + autoCapitalize="none"
189 + autoComplete="off"
190 + textContentType="none"
191 + importantForAutofill="no"
192 + spellCheck={false}
193 + returnKeyType="done"
194 + onSubmitEditing={save}
195 + />
196 + )}
197 {error !== null ? (
198 <Text
199 accessibilityRole="alert"
@@ -135,8 +207,8 @@ function PendingSecretRequestForm(props: {
207 label="Save securely"
208 tone="primary"
209 fullWidth
138 - disabled={submitting || secret.trim().length === 0}
139 - onPress={() => void send({ type: "save", secret })}
210 + disabled={submitting || draft.trim().length === 0}
211 + onPress={save}
212 />
213 <View className="flex-row items-center justify-between gap-2">
214 <View className="flex-1 flex-row items-center gap-1.5">
apps/server/src/device/DeviceService.test.ts
+1
@@ -595,6 +595,7 @@ describe("device setup consent", () => {
595 });
596
597 const layerSecretResolver = Layer.succeed(SecretResolver.SecretResolver, {
598 + label: (provider) => Effect.succeed(provider),
599 read: (references) => Effect.succeed(references.map(() => undefined)),
600 invalidate: () => Effect.void,
601 });
apps/server/src/device/EasDeviceHost.test.ts
+2
@@ -231,6 +231,7 @@ const fakeExpo = (
231
232 const makeSecretResolver = (values: Record<string, string> = {}) =>
233 Layer.succeed(SecretResolver.SecretResolver, {
234 + label: (provider) => Effect.succeed(provider),
235 read: (references) =>
236 Effect.succeed(references.map((reference) => values[reference.reference])),
237 invalidate: () => Effect.void,
@@ -364,6 +365,7 @@ describe("EAS Simulator host", () => {
365 Effect.provide(
366 layerWith(
367 Layer.succeed(SecretResolver.SecretResolver, {
368 + label: (provider) => Effect.succeed(provider),
369 read: (references) =>
370 Effect.succeed(references.map(() => (readable.value ? "expo-token" : undefined))),
371 invalidate: () => Effect.void,
apps/server/src/device/SimlockDeviceHost.test.ts
+1
@@ -149,6 +149,7 @@ const makeSecretResolver = (values: Record<string, string> = {}) =>
149 read: (references) =>
150 Effect.succeed(references.map((reference) => values[reference.reference])),
151 invalidate: () => Effect.void,
152 + label: (provider) => Effect.succeed(provider),
153 });
154
155 const layerWith = (secrets: Layer.Layer<SecretResolver.SecretResolver>) =>
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+2
@@ -36,6 +36,7 @@ import * as ThreadManagementService from "../orchestration-v2/ThreadManagementSe
36 import * as ServerSettings from "../serverSettings.ts";
37 import * as SqlitePersistence from "../persistence/Sqlite.ts";
38 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
39 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
40 import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
41 import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
42 import {
@@ -250,6 +251,7 @@ describe("orchestrator MCP toolkit", () => {
251 Layer.provideMerge(
252 SecretRequests.layer.pipe(
253 Layer.provide(layerMemorySecretStore),
254 + Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
255 Layer.provide(layerOrchestration),
256 ),
257 ),
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+1
@@ -845,6 +845,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
845 };
846 const gate = Deferred.makeUnsafe<void>();
847 const resolver = Layer.succeed(SecretResolver.SecretResolver, {
848 + label: (provider) => Effect.succeed(provider),
849 read: (references) =>
850 Deferred.await(gate).pipe(
851 Effect.andThen(
apps/server/src/secrets/SecretRequests.test.ts
+106
@@ -6,10 +6,15 @@ import {
6 OrchestratorMcpRequestSecretInput,
7 ProjectId,
8 type OrchestrationV2ServerCommand,
9 + SecretProviderId,
10 + SecretProviderKind,
11 SecretRef,
12 ThreadId,
13 TurnItemId,
14 } from "@t3tools/contracts";
15 +import { defineSecretProviderDriver } from "@t3tools/secret-provider-core/server/driver";
16 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
17 +import { defineSecretProvider } from "@t3tools/secret-provider-core/shared/definition";
18 import * as Effect from "effect/Effect";
19 import * as Exit from "effect/Exit";
20 import * as FileSystem from "effect/FileSystem";
@@ -32,6 +37,35 @@ const projectId = ProjectId.make("project-1");
37 const decodeSecretInput = Schema.decodeUnknownEffect(OrchestratorMcpRequestSecretInput);
38 const decodeSecretInputExit = Schema.decodeUnknownExit(OrchestratorMcpRequestSecretInput);
39
40 +const FAKE_KIND = SecretProviderKind.make("fake");
41 +const vault = SecretProviderId.make("vault");
42 +/** Reads `fake://` references from `values` while unlocked, as a password manager would. */
43 +const fakeVault = () => {
44 + const state = { unlocked: true, values: new Map([["fake://github/token", "ghp_from_vault"]]) };
45 + const driver = defineSecretProviderDriver({
46 + kind: FAKE_KIND,
47 + definition: defineSecretProvider({
48 + kind: FAKE_KIND,
49 + label: "Fake",
50 + configSchema: Schema.Struct({}),
51 + isReference: (reference) => reference.startsWith("fake://"),
52 + referencePlaceholder: "fake://item",
53 + invalidReferenceMessage: "Use fake://item.",
54 + }),
55 + read: (_config, references) =>
56 + Effect.sync(() =>
57 + references.map((reference) => (state.unlocked ? state.values.get(reference) : undefined)),
58 + ),
59 + });
60 + return {
61 + state,
62 + layer: SecretResolver.layer({
63 + drivers: [driver],
64 + secretProviders: Effect.succeed({ [vault]: { kind: FAKE_KIND, label: "Vault", config: {} } }),
65 + }).pipe(Layer.provide(Layer.merge(NodeServices.layer, NodeCrypto.layer))),
66 + };
67 +};
68 +
69 const withService = <A, E>(
70 body: (input: {
71 readonly service: SecretRequests.SecretRequests["Service"];
@@ -46,6 +80,7 @@ const withService = <A, E>(
80 readonly removeFails?: boolean;
81 readonly closedFirst?: boolean;
82 readonly failedRecords?: number;
83 + readonly resolver?: Layer.Layer<SecretResolver.SecretResolver>;
84 } = {},
85 ) =>
86 Effect.gen(function* () {
@@ -57,6 +92,7 @@ const withService = <A, E>(
92 const layerDependencies = Layer.mergeAll(
93 NodeCrypto.layer,
94 NodeServices.layer,
95 + options.resolver ?? fakeVault().layer,
96 Layer.succeed(
97 ServerSecretStore.ServerSecretStore,
98 ServerSecretStore.ServerSecretStore.of({
@@ -168,6 +204,76 @@ it.effect("a saved answer becomes a one-use ref, and the thread only learns it w
204 ),
205 );
206
207 +it.effect("a secret provider reference is read once and saved like a typed value", () =>
208 + withService(({ service, dispatched }) =>
209 + Effect.gen(function* () {
210 + yield* service.answer({
211 + threadId,
212 + turnItemId,
213 + answer: {
214 + type: "reference",
215 + reference: { provider: vault, reference: "fake://github/token" },
216 + },
217 + });
218 + assert.include(dispatched[0] as object, { secretStatus: "saved" });
219 + assert.notInclude(JSON.stringify(dispatched), "fake://");
220 + const ref = Option.getOrThrow(yield* service.savedRef({ threadId, turnItemId }));
221 + assert.equal(yield* service.consume({ ref, projectId }), "ghp_from_vault");
222 + }),
223 + ),
224 +);
225 +
226 +it.effect(
227 + "an unreadable reference leaves the request pending, and a retry after unlocking works",
228 + () => {
229 + const { state, layer } = fakeVault();
230 + state.unlocked = false;
231 + return withService(
232 + ({ service, stored, dispatched }) =>
233 + Effect.gen(function* () {
234 + const reference = { provider: vault, reference: "fake://github/token" };
235 + const locked = yield* service
236 + .answer({ threadId, turnItemId, answer: { type: "reference", reference } })
237 + .pipe(Effect.flip);
238 + assert.equal(locked.reason, "reference_unreadable");
239 + assert.include(locked.message, '"Vault"');
240 + assert.deepEqual(dispatched, []);
241 + assert.deepEqual(valuesOf(stored), []);
242 +
243 + state.unlocked = true;
244 + yield* service.answer({ threadId, turnItemId, answer: { type: "reference", reference } });
245 + const ref = Option.getOrThrow(yield* service.savedRef({ threadId, turnItemId }));
246 + assert.equal(yield* service.consume({ ref, projectId }), "ghp_from_vault");
247 + }),
248 + { resolver: layer },
249 + );
250 + },
251 +);
252 +
253 +it.effect("a reference to a secret provider that is not configured fails", () =>
254 + withService(({ service, dispatched }) =>
255 + Effect.gen(function* () {
256 + const error = yield* service
257 + .answer({
258 + threadId,
259 + turnItemId,
260 + answer: {
261 + type: "reference",
262 + reference: {
263 + // Also an Object.prototype key, which must not pass for a configured provider.
264 + provider: SecretProviderId.make("constructor"),
265 + reference: "fake://github/token",
266 + },
267 + },
268 + })
269 + .pipe(Effect.flip);
270 + assert.equal(error.reason, "reference_unreadable");
271 + assert.include(error.message, '"constructor"');
272 + assert.deepEqual(dispatched, []);
273 + }),
274 + ),
275 +);
276 +
277 it.effect("two concurrent uses of one ref hand the value out once", () =>
278 withService(({ service }) =>
279 Effect.gen(function* () {
apps/server/src/secrets/SecretRequests.ts
+29 -5
@@ -7,9 +7,11 @@ import {
7 SecretRef,
8 SecretRequestError,
9 type ProjectId,
10 + type SecretReference,
11 type SecretRequestAnswerInput,
12 type ThreadId,
13 } from "@t3tools/contracts";
14 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
15
16 import * as Clock from "effect/Clock";
17 import * as Context from "effect/Context";
@@ -74,6 +76,7 @@ const make = Effect.gen(function* () {
76 const fileSystem = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
79 + const resolver = yield* SecretResolver.SecretResolver;
80 // Beside the store's own files so the same owner-only directory and cleanup rules apply.
81 const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files");
82
@@ -91,6 +94,21 @@ const make = Effect.gen(function* () {
94 Effect.map((tag) => SecretRef.make(`${SECRET_REF_PREFIX}${Hex.encode(tag).slice(0, 32)}`)),
95 );
96
97 + const readReference = Effect.fn("SecretRequests.readReference")(function* (
98 + reference: SecretReference,
99 + ) {
100 + // The resolver keeps failed reads for the server's life; a retry after unlocking must re-read.
101 + yield* resolver.invalidate([reference]);
102 + const [value] = yield* resolver.read([reference]);
103 + if (value === undefined || value.trim() === "") {
104 + return yield* new SecretRequestError({
105 + reason: "reference_unreadable",
106 + provider: yield* resolver.label(reference.provider),
107 + });
108 + }
109 + return value;
110 + });
111 +
112 const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(
113 function* (input) {
114 yield* Effect.annotateCurrentSpan({
@@ -114,12 +132,18 @@ const make = Effect.gen(function* () {
132 if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) {
133 return yield* new SecretRequestError({ reason: "agent_stopped" });
134 }
135 + const secret =
136 + input.answer.type === "save"
137 + ? input.answer.secret
138 + : input.answer.type === "reference"
139 + ? yield* readReference(input.answer.reference)
140 + : undefined;
141 // Create before recording so racing answers cannot overwrite values or show saved before storage.
142 // Existing values on pending cards finish earlier saves whose recording failed.
119 - if (input.answer.type === "save") {
143 + if (secret !== undefined) {
144 const encoded = yield* encodeStored({
145 projectId: records.thread.projectId,
122 - value: input.answer.secret,
146 + value: secret,
147 savedAt: yield* Clock.currentTimeMillis,
148 }).pipe(Effect.orDie);
149 yield* store
@@ -134,7 +158,7 @@ const make = Effect.gen(function* () {
158 ),
159 );
160 }
137 - const secretStatus = input.answer.type === "save" ? "saved" : "declined";
161 + const secretStatus = secret === undefined ? "declined" : "saved";
162 yield* threadManagement
163 .dispatch({
164 type: "secret_request.record",
@@ -153,14 +177,14 @@ const make = Effect.gen(function* () {
177 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
178 // Clear failed saves so the pending card can be answered again.
179 Effect.tapError(() =>
156 - input.answer.type === "save"
180 + secret !== undefined
181 ? refFor(input.threadId, item.id).pipe(
182 Effect.flatMap((ref) => removeLogged(storeName(ref))),
183 )
184 : Effect.void,
185 ),
186 );
163 - if (input.answer.type !== "save") return;
187 + if (secret === undefined) return;
188 // The wait may have closed the card; delete unrecorded answers because no one receives their refs.
189 const recorded = yield* threadManagement
190 .getThreadRecords(input.threadId, ["turnItems"], {
apps/server/src/secrets/settingsSecretValue.ts
+3 -1
@@ -41,7 +41,9 @@ export const requireSettingsSecret = Effect.fn("SettingsSecrets.require")(functi
41 if (!isSecretReference(value)) return value;
42 const [secret] = yield* resolver.read([value]);
43 if (secret === undefined || secret.trim() === "") {
44 - return yield* new SettingsSecretUnresolvedError({ provider: value.provider });
44 + return yield* new SettingsSecretUnresolvedError({
45 + provider: yield* resolver.label(value.provider),
46 + });
47 }
48 return secret;
49 });
apps/server/src/sourceControl/sourceControlHostSecrets.test.ts
+2
@@ -32,6 +32,7 @@ const hosts = {
32 function countingResolver() {
33 const reads: Array<string> = [];
34 const resolver = SecretResolver.SecretResolver.of({
35 + label: (provider) => Effect.succeed(provider),
36 read: (references) =>
37 Effect.sync(() =>
38 references.map((reference) => {
@@ -109,6 +110,7 @@ it.effect("reads a collected reference again once it is invalidated", () =>
110 let current = "stale";
111 const cache = new Map<string, string>();
112 const resolver = SecretResolver.SecretResolver.of({
113 + label: (provider) => Effect.succeed(provider),
114 read: (references) =>
115 Effect.sync(() =>
116 references.map((reference) => {
apps/server/src/usage/UsageLimitSources.test.ts
+2
@@ -39,6 +39,7 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () =>
39 }).pipe(
40 Effect.provide([
41 Layer.succeed(SecretResolver.SecretResolver, {
42 + label: (provider) => Effect.succeed(provider),
43 read: (references) => Effect.succeed(references.map(() => undefined)),
44 invalidate: () => Effect.void,
45 }),
@@ -133,6 +134,7 @@ it.effect("reads a management key from its secret provider", () => {
134 shouldRunScopeWork: () => Effect.succeed(false),
135 }),
136 Layer.succeed(SecretResolver.SecretResolver, {
137 + label: (provider) => Effect.succeed(provider),
138 read: (references) =>
139 Effect.succeed(
140 references.map((reference) =>
apps/server/src/ws.ts
+1
@@ -1938,6 +1938,7 @@ export const layerWsRpc = (
1938 threadFindProgressive: true,
1939 secretProviderSettings: true,
1940 secretReferences: true,
1941 + secretRequestReferences: true,
1942 ...Option.match(scratchWorkspaceRoot, {
1943 onNone: () => ({}),
1944 onSome: (root) => ({ scratchWorkspaceRoot: root }),
apps/web/src/components/chat/SecretRequestCard.tsx
+86 -23
@@ -5,20 +5,31 @@ import {
5 secretRequestDisplay,
6 secretRequestFailureMessage,
7 secretRequestPrivacyNote,
8 + secretRequestReference,
9 + secretRequestSources,
10 type SecretRequestItem,
11 + type SecretRequestReply,
12 + type SecretRequestSource,
13 } from "@t3tools/client-runtime/secret-request";
14 import {
15 isAtomCommandInterrupted,
16 squashAtomCommandFailure,
17 } from "@t3tools/client-runtime/state/runtime";
14 -import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
18 +import type {
19 + EnvironmentId,
20 + OrchestrationV2ProjectedTurnItem,
21 + SecretProviderId,
22 +} from "@t3tools/contracts";
23 +import { useAtomValue } from "@effect/atom-react";
24 import { CheckIcon, LockIcon, MinusIcon, ShieldCheckIcon } from "lucide-react";
25 import { useId, useRef, useState, type FormEvent } from "react";
26
27 +import { isSecretsFeatureEnabled } from "../../env";
28 import { serverEnvironment } from "../../state/server";
29 import { useAtomCommand } from "../../state/use-atom-command";
30 import { Button } from "../ui/button";
31 import { Input } from "../ui/input";
32 +import { SecretSourceSelect } from "../settings/SecretSourceInput";
33 import { WorkLogRow } from "./WorkLog";
34
35 export function SecretRequestCard(props: {
@@ -50,6 +61,15 @@ export function SecretRequestCard(props: {
61 return <PendingSecretRequestForm environmentId={props.environmentId} item={item} />;
62 }
63
64 +const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
65 +
66 +function useSecretRequestSources(environmentId: EnvironmentId) {
67 + const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
68 + return isSecretsFeatureEnabled
69 + ? secretRequestSources(config, config?.settings.secretProviders ?? {})
70 + : NO_SOURCES;
71 +}
72 +
73 function PendingSecretRequestForm(props: {
74 readonly environmentId: EnvironmentId;
75 readonly item: SecretRequestItem;
@@ -64,15 +84,17 @@ function PendingSecretRequestForm(props: {
84 reportFailure: false,
85 reportDefect: false,
86 });
87 + const sources = useSecretRequestSources(props.environmentId);
88 + const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
89 + const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
90 const [secret, setSecret] = useState("");
91 + const [reference, setReference] = useState("");
92 const [submitting, setSubmitting] = useState(false);
93 const [error, setError] = useState<string | null>(null);
94 // Enter and click can both submit before a render.
95 const inFlight = useRef(false);
96
73 - const send = async (
74 - reply: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" },
75 - ) => {
97 + const send = async (reply: SecretRequestReply) => {
98 const input = secretRequestAnswerInput(item, reply);
99 if (input === null || inFlight.current) return;
100 inFlight.current = true;
@@ -84,6 +106,7 @@ function PendingSecretRequestForm(props: {
106 });
107 if (result._tag === "Success") {
108 setSecret("");
109 + setReference("");
110 return;
111 }
112 if (!isAtomCommandInterrupted(result)) {
@@ -93,8 +116,16 @@ function PendingSecretRequestForm(props: {
116
117 const onSubmit = (event: FormEvent<HTMLFormElement>) => {
118 event.preventDefault();
96 - void send({ type: "save", secret });
119 + if (source === null) {
120 + void send({ type: "save", secret });
121 + } else if (secretRequestReference(source, reference) === undefined) {
122 + setError(source.invalidReferenceMessage);
123 + } else {
124 + void send({ type: "reference", source, reference });
125 + }
126 };
127 + const draft = source === null ? secret : reference;
128 + const describedBy = error !== null ? `${privacyId} ${errorId}` : privacyId;
129
130 return (
131 <form
@@ -121,27 +152,59 @@ function PendingSecretRequestForm(props: {
152 ) : null}
153 </div>
154 <div className="flex min-w-0 items-center gap-2">
124 - <div className="min-w-0 flex-1">
125 - <Input
126 - id={inputId}
127 - // A CSS-masked text field still exposes its value to screen readers.
128 - type="password"
129 - autoComplete="off"
130 - autoCorrect="off"
131 - autoCapitalize="off"
132 - spellCheck={false}
133 - data-1p-ignore
134 - data-lpignore="true"
135 - data-bwignore
136 - placeholder={item.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER}
137 - value={secret}
155 + {sources.length > 0 ? (
156 + <SecretSourceSelect
157 + value={source?.id ?? null}
158 + sources={sources}
159 + label={item.label}
160 disabled={submitting}
139 - aria-invalid={error !== null || undefined}
140 - aria-describedby={error !== null ? `${privacyId} ${errorId}` : privacyId}
141 - onChange={(event) => setSecret(event.currentTarget.value)}
161 + onValueChange={(next) => {
162 + setSourceId(next);
163 + setError(null);
164 + }}
165 />
166 + ) : null}
167 + <div className="min-w-0 flex-1">
168 + {source === null ? (
169 + <Input
170 + id={inputId}
171 + // A CSS-masked text field still exposes its value to screen readers.
172 + type="password"
173 + autoComplete="off"
174 + autoCorrect="off"
175 + autoCapitalize="off"
176 + spellCheck={false}
177 + data-1p-ignore
178 + data-lpignore="true"
179 + data-bwignore
180 + placeholder={item.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER}
181 + value={secret}
182 + disabled={submitting}
183 + aria-invalid={error !== null || undefined}
184 + aria-describedby={describedBy}
185 + onChange={(event) => setSecret(event.currentTarget.value)}
186 + />
187 + ) : (
188 + <Input
189 + id={inputId}
190 + font="mono"
191 + autoComplete="off"
192 + autoCorrect="off"
193 + autoCapitalize="off"
194 + spellCheck={false}
195 + placeholder={source.referencePlaceholder}
196 + value={reference}
197 + disabled={submitting}
198 + aria-invalid={error !== null || undefined}
199 + aria-describedby={describedBy}
200 + onChange={(event) => {
201 + setReference(event.currentTarget.value);
202 + setError(null);
203 + }}
204 + />
205 + )}
206 </div>
144 - <Button type="submit" disabled={submitting || secret.trim().length === 0}>
207 + <Button type="submit" disabled={submitting || draft.trim().length === 0}>
208 Save securely
209 </Button>
210 </div>
apps/web/src/components/settings/SecretSourceInput.tsx
+58 -37
@@ -60,6 +60,57 @@ function SourceLabel(props: {
60 );
61 }
62
63 +/** Picks Value (`null`) or one of `sources`; a `value` no longer among them stays listed. */
64 +export function SecretSourceSelect(props: {
65 + readonly value: SecretProviderId | null;
66 + readonly sources: ReadonlyArray<Pick<SecretSource, "id" | "label">>;
67 + readonly label: string;
68 + readonly disabled?: boolean;
69 + readonly onValueChange: (provider: SecretProviderId | null) => void;
70 +}) {
71 + const { value, sources } = props;
72 + const known = value === null || sources.some((source) => source.id === value);
73 + const title =
74 + value === null ? "Value" : (sources.find((source) => source.id === value)?.label ?? value);
75 + return (
76 + <Select
77 + value={value ?? STORED_VALUE}
78 + onValueChange={(next) =>
79 + props.onValueChange(
80 + next === STORED_VALUE || next === null ? null : (next as SecretProviderId),
81 + )
82 + }
83 + {...(props.disabled === undefined ? {} : { disabled: props.disabled })}
84 + >
85 + <SelectTrigger
86 + size="sm"
87 + className="w-auto min-w-0 shrink-0"
88 + aria-label={`${props.label} source`}
89 + title={title}
90 + >
91 + <SelectValue>
92 + <SourceIcon icon={value === null ? TypeIcon : known ? OnePasswordIcon : KeyRoundIcon} />
93 + </SelectValue>
94 + </SelectTrigger>
95 + <SelectPopup align="start" alignItemWithTrigger={false}>
96 + <SelectItem value={STORED_VALUE}>
97 + <SourceLabel icon={TypeIcon} label="Value" />
98 + </SelectItem>
99 + {sources.map((source) => (
100 + <SelectItem key={source.id} value={source.id}>
101 + <SourceLabel icon={OnePasswordIcon} label={source.label} />
102 + </SelectItem>
103 + ))}
104 + {known ? null : (
105 + <SelectItem value={value}>
106 + <SourceLabel icon={KeyRoundIcon} label={value} />
107 + </SelectItem>
108 + )}
109 + </SelectPopup>
110 + </Select>
111 + );
112 +}
113 +
114 type SecretSourceInputProps = Omit<ComponentProps<typeof SecretInput>, "value" | "children"> & {
115 readonly value: string | SecretReference;
116 readonly sources: ReadonlyArray<SecretSource>;
@@ -92,54 +143,24 @@ export function SecretSourceInput({
143 const providerSource = sources.find((source) => source.id === provider);
144 const definition = providerSource && builtInSecretProviderDefinitions.find(providerSource.kind);
145 const label = input["aria-label"] ?? "Secret";
95 - const providerLabel = (id: SecretProviderId) =>
96 - sources.find((source) => source.id === id)?.label ?? id;
97 - const providerIcon = (id: SecretProviderId) =>
98 - sources.some((source) => source.id === id) ? OnePasswordIcon : KeyRoundIcon;
99 -
146 const source =
147 sources.length === 0 && provider === null ? null : (
102 - <Select
103 - value={provider ?? STORED_VALUE}
104 - onValueChange={(value) => {
148 + <SecretSourceSelect
149 + value={provider}
150 + sources={sources}
151 + label={label}
152 + onValueChange={(next) => {
153 setRejectedReference(null);
106 - if (value === STORED_VALUE || value === null) {
154 + if (next === null) {
155 setPendingProvider(null);
156 onValidityChange?.(true);
157 if (secret !== undefined) onSecretChange(undefined);
158 return;
159 }
112 - const next = value as SecretProviderId;
160 onValidityChange?.(next === secret?.provider);
161 setPendingProvider(next === secret?.provider ? null : next);
162 }}
116 - >
117 - <SelectTrigger
118 - size="sm"
119 - className="w-auto min-w-0 shrink-0"
120 - aria-label={`${label} source`}
121 - title={provider === null ? "Value" : providerLabel(provider)}
122 - >
123 - <SelectValue>
124 - <SourceIcon icon={provider === null ? TypeIcon : providerIcon(provider)} />
125 - </SelectValue>
126 - </SelectTrigger>
127 - <SelectPopup align="start" alignItemWithTrigger={false}>
128 - <SelectItem value={STORED_VALUE}>
129 - <SourceLabel icon={TypeIcon} label="Value" />
130 - </SelectItem>
131 - {sources.map((source) => (
132 - <SelectItem key={source.id} value={source.id}>
133 - <SourceLabel icon={OnePasswordIcon} label={source.label} />
134 - </SelectItem>
135 - ))}
136 - {provider !== null && !sources.some((source) => source.id === provider) ? (
137 - <SelectItem value={provider}>
138 - <SourceLabel icon={KeyRoundIcon} label={provider} />
139 - </SelectItem>
140 - ) : null}
141 - </SelectPopup>
142 - </Select>
163 + />
164 );
165
166 const valueField =
packages/client-runtime/package.json
+1
@@ -552,6 +552,7 @@
552 "@t3tools/provider-muse": "workspace:*",
553 "@t3tools/provider-opencode": "workspace:*",
554 "@t3tools/provider-pi": "workspace:*",
555 + "@t3tools/secret-provider-definitions": "workspace:*",
556 "@t3tools/shared": "workspace:*",
557 "@t3tools/source-control-core": "workspace:*",
558 "@t3tools/source-control-definitions": "workspace:*",
packages/client-runtime/src/secretRequest.test.ts
+52 -1
@@ -1,10 +1,18 @@
1 -import { SecretRequestError } from "@t3tools/contracts";
1 +import {
2 + SecretProviderId,
3 + SecretProviderKind,
4 + SecretRequestError,
5 + ThreadId,
6 + TurnItemId,
7 +} from "@t3tools/contracts";
8 import { describe, expect, it } from "vite-plus/test";
9
10 import {
11 + secretRequestAnswerInput,
12 secretRequestDisplay,
13 secretRequestFailureMessage,
14 secretRequestPrivacyNote,
15 + secretRequestSources,
16 } from "./secretRequest.ts";
17
18 describe("secretRequestDisplay", () => {
@@ -37,3 +45,46 @@ describe("secretRequestFailureMessage", () => {
45 expect(secretRequestFailureMessage(undefined)).toBe("Could not answer the request. Try again.");
46 });
47 });
48 +
49 +describe("secretRequestSources", () => {
50 + const onePassword = SecretProviderId.make("1password");
51 + const providers = {
52 + [onePassword]: {
53 + kind: SecretProviderKind.make("one_password"),
54 + label: "1Password",
55 + config: { account: "my" },
56 + },
57 + [SecretProviderId.make("later")]: {
58 + kind: SecretProviderKind.make("from_a_newer_build"),
59 + label: "Later",
60 + config: {},
61 + },
62 + };
63 +
64 + it("offers configured providers only when the server accepts reference answers", () => {
65 + expect(secretRequestSources({ secretRequestReferences: true }, providers)).toMatchObject([
66 + { id: onePassword, label: "1Password" },
67 + ]);
68 + expect(secretRequestSources({}, providers)).toEqual([]);
69 + expect(secretRequestSources({ secretRequestReferences: true }, {})).toEqual([]);
70 + });
71 +
72 + it("answers with a reference only in the provider's syntax", () => {
73 + const [source] = secretRequestSources({ secretRequestReferences: true }, providers);
74 + if (source === undefined) throw new Error("expected a source");
75 + const item = { id: TurnItemId.make("item-1"), threadId: ThreadId.make("thread-1") };
76 + expect(
77 + secretRequestAnswerInput(item, {
78 + type: "reference",
79 + source,
80 + reference: " op://vault/item/field ",
81 + })?.answer,
82 + ).toEqual({
83 + type: "reference",
84 + reference: { provider: onePassword, reference: "op://vault/item/field" },
85 + });
86 + expect(
87 + secretRequestAnswerInput(item, { type: "reference", source, reference: "vault/item" }),
88 + ).toBeNull();
89 + });
90 +});
packages/client-runtime/src/secretRequest.ts
+82 -2
@@ -1,4 +1,14 @@
1 -import type { OrchestrationV2TurnItem, SecretRequestAnswerInput } from "@t3tools/contracts";
1 +import {
2 + SecretReference,
3 + type OrchestrationV2TurnItem,
4 + type SecretProviderId,
5 + type SecretRequestAnswerInput,
6 + type ServerConfig,
7 + type ServerSettings,
8 +} from "@t3tools/contracts";
9 +import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry";
10 +import * as Option from "effect/Option";
11 +import * as Schema from "effect/Schema";
12
13 export type SecretRequestItem = Extract<
14 OrchestrationV2TurnItem,
@@ -62,13 +72,83 @@ export function secretRequestDisplay(
72 }
73 }
74
75 +/** A configured secret provider a pending card can read its answer from. */
76 +export interface SecretRequestSource {
77 + readonly id: SecretProviderId;
78 + readonly label: string;
79 + readonly isReference: (reference: string) => boolean;
80 + readonly referencePlaceholder: string;
81 + readonly invalidReferenceMessage: string;
82 +}
83 +
84 +const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
85 +const decodeConfigByKind = new Map(
86 + builtInSecretProviderDefinitions.definitions.map((definition) => [
87 + definition.kind,
88 + Schema.decodeUnknownOption(definition.configSchema),
89 + ]),
90 +);
91 +
92 +/** Empty unless the server accepts reference answers; providers this build cannot read are left out. */
93 +export function secretRequestSources(
94 + config: Pick<ServerConfig, "secretRequestReferences"> | null | undefined,
95 + providers: ServerSettings["secretProviders"],
96 +): ReadonlyArray<SecretRequestSource> {
97 + if (config?.secretRequestReferences !== true) return NO_SOURCES;
98 + return (Object.keys(providers) as Array<SecretProviderId>).flatMap((id) => {
99 + const provider = providers[id];
100 + const definition =
101 + provider === undefined ? undefined : builtInSecretProviderDefinitions.find(provider.kind);
102 + if (
103 + provider === undefined ||
104 + definition === undefined ||
105 + decodeConfigByKind.get(definition.kind)?.(provider.config)._tag !== "Some"
106 + ) {
107 + return [];
108 + }
109 + return [
110 + {
111 + id,
112 + label: provider.label,
113 + isReference: definition.isReference,
114 + referencePlaceholder: definition.referencePlaceholder,
115 + invalidReferenceMessage: definition.invalidReferenceMessage,
116 + },
117 + ];
118 + });
119 +}
120 +
121 +const decodeSecretReference = Schema.decodeUnknownOption(SecretReference);
122 +
123 +/** The reference `text` names, or undefined when it is not `source`'s syntax. */
124 +export function secretRequestReference(
125 + source: SecretRequestSource,
126 + text: string,
127 +): SecretReference | undefined {
128 + const decoded = decodeSecretReference({ provider: source.id, reference: text.trim() });
129 + return Option.isSome(decoded) && source.isReference(decoded.value.reference)
130 + ? decoded.value
131 + : undefined;
132 +}
133 +
134 +export type SecretRequestReply =
135 + | { readonly type: "save"; readonly secret: string }
136 + | { readonly type: "reference"; readonly source: SecretRequestSource; readonly reference: string }
137 + | { readonly type: "decline" };
138 +
139 export function secretRequestAnswerInput(
140 item: Pick<SecretRequestItem, "id" | "threadId">,
67 - answer: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" },
141 + answer: SecretRequestReply,
142 ): SecretRequestAnswerInput | null {
143 if (answer.type === "decline") {
144 return { threadId: item.threadId, turnItemId: item.id, answer: { type: "decline" } };
145 }
146 + if (answer.type === "reference") {
147 + const reference = secretRequestReference(answer.source, answer.reference);
148 + return reference === undefined
149 + ? null
150 + : { threadId: item.threadId, turnItemId: item.id, answer: { type: "reference", reference } };
151 + }
152 const secret = answer.secret.trim();
153 if (secret.length === 0) return null;
154 return { threadId: item.threadId, turnItemId: item.id, answer: { type: "save", secret } };
packages/contracts/src/secretRequest.ts
+9
@@ -1,6 +1,7 @@
1 import * as Schema from "effect/Schema";
2
3 import { ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
4 +import { SecretReference } from "./secretReference.ts";
5
6 /** Server stores the value under a one-use SecretRef; the thread learns only status. */
7 export const SecretRequestAnswerInput = Schema.Struct({
@@ -9,6 +10,8 @@ export const SecretRequestAnswerInput = Schema.Struct({
10 answer: Schema.Union([
11 Schema.Struct({ type: Schema.Literal("save"), secret: TrimmedNonEmptyString }),
12 Schema.Struct({ type: Schema.Literal("decline") }),
13 + /** Read once through a configured secret provider; only servers advertising `secretRequestReferences` accept it. */
14 + Schema.Struct({ type: Schema.Literal("reference"), reference: SecretReference }),
15 ]),
16 });
17 export type SecretRequestAnswerInput = typeof SecretRequestAnswerInput.Type;
@@ -29,6 +32,7 @@ const SECRET_REQUEST_FAILURE_MESSAGES = {
32 already_answered: "This secret request was already answered.",
33 agent_stopped: "The agent that asked has stopped, so this secret can't be used.",
34 store_failed: "Could not store the secret.",
35 + reference_unreadable: "Could not read the secret from the secret provider.",
36 record_failed: "Saved the secret, but could not update the request.",
37 invalid_ref: "That secretRef is not valid.",
38 read_failed: "Could not read the secret.",
@@ -51,10 +55,15 @@ export class SecretRequestError extends Schema.TaggedError<SecretRequestError>()
55 "SecretRequestError",
56 {
57 reason: SecretRequestFailureReason,
58 + /** The secret provider a `reference_unreadable` answer named. */
59 + provider: Schema.optionalKey(Schema.String),
60 cause: Schema.optionalKey(Schema.Defect()),
61 },
62 ) {
63 override get message(): string {
64 + if (this.reason === "reference_unreadable" && this.provider !== undefined) {
65 + return `Could not read the secret from the secret provider "${this.provider}". Unlock it and try again, or enter the value.`;
66 + }
67 return SECRET_REQUEST_FAILURE_MESSAGES[this.reason];
68 }
69 }
packages/contracts/src/server.ts
+2
@@ -645,6 +645,8 @@ export const ServerConfig = Schema.Struct({
645 secretProviderSettings: Schema.optionalKey(Schema.Boolean),
646 /** Secret settings may point at a secret provider; older servers drop the reference. */
647 secretReferences: Schema.optionalKey(Schema.Boolean),
648 + /** A secret request card may be answered with a secret provider reference. */
649 + secretRequestReferences: Schema.optionalKey(Schema.Boolean),
650 scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString),
651 newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString),
652 /**
packages/secret-provider-core/src/server/SecretResolver.ts
+12 -1
@@ -20,6 +20,8 @@ export class SecretResolver extends Context.Service<
20 ) => Effect.Effect<ReadonlyArray<string | undefined>>;
21 /** Forgets the given references, or every reference, so the next read asks the provider again. */
22 readonly invalidate: (references?: ReadonlyArray<SecretReference>) => Effect.Effect<void>;
23 + /** The name the user gave a secret provider, or its id when it has none or is gone. */
24 + readonly label: (provider: SecretReference["provider"]) => Effect.Effect<string>;
25 }
26 >()("@t3tools/secret-provider-core/server/SecretResolver") {}
27
@@ -137,7 +139,16 @@ export const make = Effect.fn("SecretResolver.make")(function* (options: {
139 }),
140 );
141
140 - return SecretResolver.of({ read, invalidate });
142 + const label: SecretResolver["Service"]["label"] = (provider) =>
143 + options.secretProviders.pipe(
144 + Effect.map(
145 + (providers) =>
146 + (Object.hasOwn(providers, provider) ? providers[provider]?.label.trim() : undefined) ||
147 + provider,
148 + ),
149 + );
150 +
151 + return SecretResolver.of({ read, invalidate, label });
152 });
153
154 export const layer = (options: Parameters<typeof make>[0]) =>
pnpm-lock.yaml
+3
@@ -1506,6 +1506,9 @@ importers:
1506 '@t3tools/provider-pi':
1507 specifier: workspace:*
1508 version: link:../provider-pi
1509 + '@t3tools/secret-provider-definitions':
1510 + specifier: workspace:*
1511 + version: link:../secret-provider-definitions
1512 '@t3tools/shared':
1513 specifier: workspace:*
1514 version: link:../shared