@devries-cameron20 / t3code Mirror · read-only / commits / a10490937d
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 05:45 UTC

feat(server): read usage limit source keys from a secret provider (#27760)

Signed-off-by: Yordis Prieto <yordis.prieto@gmail.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Yordis Prieto committed Nov 3, 2026 at 16:01 UTC a10490937dbd8a9e441b0518a77a60117f3ecf5a
18 files changed +462 -96
apps/server/src/serverSettings.test.ts
+94 -11
@@ -27,6 +27,7 @@ import * as Path from "effect/Path";
27 import * as PlatformError from "effect/PlatformError";
28 import * as Schema from "effect/Schema";
29 import * as Stream from "effect/Stream";
30 +import * as SchemaAST from "effect/SchemaAST";
31 import * as SqlClient from "effect/sql/SqlClient";
32 import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
33 import { sourceControlHostSecretName } from "./sourceControl/sourceControlHostSecrets.ts";
@@ -34,6 +35,7 @@ import * as ServerConfig from "./config.ts";
35 import * as SqlitePersistence from "./persistence/Sqlite.ts";
36 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
37 import * as ServerSettingsModule from "./serverSettings.ts";
38 +import { SECRET_REDACTED } from "./settingsSecrets.ts";
39 import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
40 import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
41
@@ -102,6 +104,36 @@ const recordProviderUsage = (provider: string, instanceId: string | null = provi
104 `;
105 });
106
107 +/** Paths of fields typed `SettingsSecretValue` that clients decode with the settings schema itself. */
108 +function strictSecretReferencePaths(
109 + ast: SchemaAST.AST,
110 + path = "",
111 + seen = new Set<SchemaAST.AST>(),
112 +): ReadonlyArray<string> {
113 + if (seen.has(ast)) return [];
114 + seen.add(ast);
115 + const walk = (type: SchemaAST.AST, at: string): ReadonlyArray<string> =>
116 + type.context?.annotations?.settingsSecretReference === true
117 + ? [at]
118 + : strictSecretReferencePaths(type, `${at}.`, seen);
119 + if (SchemaAST.isObjects(ast)) {
120 + return [
121 + ...ast.propertySignatures.flatMap((property) =>
122 + walk(property.type, `${path}${String(property.name)}`),
123 + ),
124 + ...ast.indexSignatures.flatMap((signature) => walk(signature.type, `${path}*`)),
125 + ];
126 + }
127 + if (SchemaAST.isArrays(ast)) {
128 + return [...ast.elements, ...ast.rest].flatMap((element) => walk(element, `${path}[]`));
129 + }
130 + if (SchemaAST.isUnion(ast)) {
131 + return ast.types.flatMap((member) => strictSecretReferencePaths(member, path, seen));
132 + }
133 + if (SchemaAST.isSuspend(ast)) return strictSecretReferencePaths(ast.thunk(), path, seen);
134 + return [];
135 +}
136 +
137 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings", (it) => {
138 it.effect("serializes concurrent model preference edits without cancelling duplicate adds", () =>
139 Effect.gen(function* () {
@@ -278,7 +310,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
310 },
311 });
312 assert.deepStrictEqual<unknown>(
281 - ServerSettingsModule.redactServerSettingsForClient(settings).secretProviders,
313 + ServerSettingsModule.redactServerSettingsForClient(settings, { secretReferences: true })
314 + .secretProviders,
315 {
316 personal: { kind: "one_password", label: "Personal", config: { account: "my" } },
317 vault: { kind: "openbao", label: "Vault" },
@@ -1331,7 +1364,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1364 "quota-secret",
1365 "expo-secret",
1366 ];
1334 - const client = ServerSettingsModule.redactServerSettingsForClient(saved);
1367 + const client = ServerSettingsModule.redactServerSettingsForClient(saved, {
1368 + secretReferences: true,
1369 + });
1370 const disk = yield* fs.readFileString(config.settingsPath);
1371 for (const value of values) {
1372 assert.include(JSON.stringify(saved), value);
@@ -1365,7 +1400,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1400 instance: { ...client.providerInstances[instanceId]!, config: { apiKey } },
1401 });
1402 assert.propertyVal(changed.providerInstances[instanceId]?.config, "apiKey", apiKey);
1368 - const redacted = ServerSettingsModule.redactServerSettingsForClient(changed);
1403 + const redacted = ServerSettingsModule.redactServerSettingsForClient(changed, {
1404 + secretReferences: true,
1405 + });
1406 assert.propertyVal(
1407 redacted.providerInstances[instanceId]?.config,
1408 "apiKey",
@@ -1414,9 +1451,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1451 });
1452 assert.isTrue(Option.isNone(yield* store.get(secretNames[1]!)));
1453 assert.deepEqual(
1417 - ServerSettingsModule.redactServerSettingsForClient(referenced).providerInstances[
1418 - instanceId
1419 - ]?.environment,
1454 + ServerSettingsModule.redactServerSettingsForClient(referenced, { secretReferences: true })
1455 + .providerInstances[instanceId]?.environment,
1456 [{ name: "API_TOKEN", value: secret, sensitive: true }],
1457 );
1458 yield* service.updateSettings({
@@ -1463,7 +1499,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1499 "serverPassword",
1500 "legacy-password",
1501 );
1466 - const client = ServerSettingsModule.redactServerSettingsForClient(saved);
1502 + const client = ServerSettingsModule.redactServerSettingsForClient(saved, {
1503 + secretReferences: true,
1504 + });
1505 for (const value of ["legacy-api-key", "legacy-password"]) {
1506 assert.notInclude(yield* fs.readFileString(config.settingsPath), value);
1507 assert.notInclude(JSON.stringify(client), value);
@@ -1507,8 +1545,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1545 for (const secret of ["bb-access", "ghp_dotcom", "ghp_ghe"]) assert.notInclude(raw, secret);
1546 assert.include(raw, "me@example.com");
1547
1510 - const forClient =
1511 - ServerSettingsModule.redactServerSettingsForClient(saved).sourceControlHosts;
1548 + const forClient = ServerSettingsModule.redactServerSettingsForClient(saved, {
1549 + secretReferences: true,
1550 + }).sourceControlHosts;
1551 assert.equal(forClient.bitbucket?.email, "me@example.com");
1552 assert.notInclude(String(forClient.bitbucket?.accessToken), "bb-access");
1553 assert.isAbove(String(forClient.bitbucket?.accessToken).length, 0);
@@ -1570,15 +1609,59 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1609 assert.isTrue(Option.isNone(yield* stored("bitbucket", "accessToken", null)));
1610 assert.isTrue(Option.isNone(yield* stored("github", "tokens", "github.com")));
1611 assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1573 - const redacted =
1574 - ServerSettingsModule.redactServerSettingsForClient(referenced).sourceControlHosts;
1612 + const redacted = ServerSettingsModule.redactServerSettingsForClient(referenced, {
1613 + secretReferences: true,
1614 + }).sourceControlHosts;
1615 assert.deepEqual(redacted.bitbucket?.accessToken, reference);
1616 const tokens = redacted.github?.tokens as Record<string, unknown>;
1617 assert.deepEqual(tokens["github.com"], gitHubReference);
1618 assert.notEqual(tokens["ghe.acme.test"], "ghp_ghe");
1619 +
1620 + // A client that cannot decode references sees saved secrets and can send them back.
1621 + const usageReference = {
1622 + provider: SecretProviderId.make("personal"),
1623 + reference: "op://Private/Hub/key",
1624 + };
1625 + const hub = UsageLimitSourceId.make("hub");
1626 + const withUsage = yield* serverSettings.updateSettings({
1627 + usageLimitSources: {
1628 + [hub]: {
1629 + kind: "cliproxy",
1630 + url: "https://hub.test",
1631 + managementKey: usageReference,
1632 + enabled: true,
1633 + },
1634 + },
1635 + });
1636 + const legacy = ServerSettingsModule.redactServerSettingsForClient(withUsage, {
1637 + secretReferences: false,
1638 + });
1639 + assert.notInclude(JSON.stringify(legacy), "op://");
1640 + assert.equal(legacy.sourceControlHosts.bitbucket?.accessToken, SECRET_REDACTED);
1641 + assert.equal(legacy.usageLimitSources[hub]?.managementKey, SECRET_REDACTED);
1642 + const echoed = yield* serverSettings.updateSettings({
1643 + sourceControlHosts: legacy.sourceControlHosts,
1644 + usageLimitSources: legacy.usageLimitSources,
1645 + });
1646 + assert.deepEqual(echoed.sourceControlHosts.bitbucket?.accessToken, reference);
1647 + assert.deepEqual(echoed.sourceControlHosts.github?.tokens, {
1648 + "github.com": gitHubReference,
1649 + "ghe.acme.test": "ghp_ghe",
1650 + });
1651 + assert.deepEqual(echoed.usageLimitSources[hub]?.managementKey, usageReference);
1652 + assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1653 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1654 );
1655
1656 + it.effect("knows every strictly decoded field that can hold a secret reference", () =>
1657 + Effect.sync(() => {
1658 + // Shipped clients decode these as strings. Each must be covered by the older-client case above.
1659 + assert.deepEqual(strictSecretReferencePaths(ServerSettings.ast), [
1660 + "usageLimitSources.*.managementKey",
1661 + ]);
1662 + }),
1663 + );
1664 +
1665 it.effect("keeps the retired keys for another load when a token cannot be copied", () => {
1666 const cause = new ServerSecretStore.SecretStoreReadError({
1667 resource: "bitbucket-access-token",
apps/server/src/serverSettings.ts
+33 -4
@@ -18,6 +18,8 @@ import {
18 type ServerSettingsPatch,
19 type ManagedPolicySummary,
20 globalIdleCompaction,
21 + isSecretReference,
22 + type SecretReference,
23 withIdleCompaction,
24 } from "@t3tools/contracts";
25 import * as Cache from "effect/Cache";
@@ -60,7 +62,12 @@ import {
62 sourceControlHostSecretName,
63 } from "./sourceControl/sourceControlHostSecrets.ts";
64
63 -import { mapSettingsSecrets, SECRET_REDACTED, type SettingsSecret } from "./settingsSecrets.ts";
65 +import {
66 + mapSettingsSecrets,
67 + mapSettingsSecretValues,
68 + SECRET_REDACTED,
69 + type SettingsSecret,
70 +} from "./settingsSecrets.ts";
71
72 export {
73 resolveReviewGuideModelSelection,
@@ -131,13 +138,35 @@ const normalizeServerSettings = (
138 ),
139 );
140
134 -export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {
141 +export function redactServerSettingsForClient(
142 + settings: ServerSettings,
143 + client: { readonly secretReferences: boolean },
144 +): ServerSettings {
145 const redacted = mapSettingsSecrets(settings, (secret) =>
146 secret.sensitive
147 ? { value: "", redacted: secret.redacted || secret.value.length > 0 }
148 : { value: secret.value, redacted: false },
149 );
140 - return { ...redacted, secretProviders: withoutUnknownSecretProviderConfigs(redacted) };
150 + // Older clients decode secret fields as strings and fail on a reference, so they see a saved secret.
151 + const shaped = client.secretReferences
152 + ? redacted
153 + : mapSettingsSecretValues(redacted, (value) =>
154 + isSecretReference(value) ? SECRET_REDACTED : value,
155 + );
156 + return { ...shaped, secretProviders: withoutUnknownSecretProviderConfigs(shaped) };
157 +}
158 +
159 +/** A client shown a reference as a saved secret sends that marker back; it keeps the reference. */
160 +function withEchoedSecretReferences(current: ServerSettings, next: ServerSettings): ServerSettings {
161 + const references = new Map<string, SecretReference>();
162 + mapSettingsSecretValues(current, (value, secretName) => {
163 + if (isSecretReference(value)) references.set(secretName, value);
164 + return value;
165 + });
166 + if (references.size === 0) return next;
167 + return mapSettingsSecretValues(next, (value, secretName) =>
168 + value === SECRET_REDACTED ? (references.get(secretName) ?? value) : value,
169 + );
170 }
171
172 // A newer kind's config may hold credentials this build cannot recognize, so it never leaves the server.
@@ -1004,7 +1033,7 @@ const make = Effect.gen(function* () {
1033 });
1034 const changes: SecretChange[] = [];
1035 const nextSecretNames = new Set<string>();
1007 - const settings = mapSettingsSecrets(next, (secret) => {
1036 + const settings = mapSettingsSecrets(withEchoedSecretReferences(current, next), (secret) => {
1037 const metadata = {
1038 secretName: secret.secretName,
1039 ...(secret.providerInstanceId !== undefined
apps/server/src/settingsSecrets.ts
+75 -27
@@ -3,7 +3,9 @@ import {
3 ClaudeSettings,
4 CodexSettings,
5 EasDeviceHostConfig,
6 + type ProviderInstanceConfig,
7 type ServerSettings,
8 + type SettingsSecretValue,
9 SimlockDeviceHostConfig,
10 UsageLimitSourceConfig,
11 isSecretReference,
@@ -58,16 +60,19 @@ export interface SettingsSecret {
60 }
61
62 type SecretValue = Pick<SettingsSecret, "value" | "redacted">;
63 +type SecretSlotName = (field: string, serverHost: string | null) => string;
64 +type SecretFieldsMapper = (
65 + fields: Readonly<Record<string, unknown>>,
66 + secretFields: ReadonlyArray<string>,
67 + name: SecretSlotName,
68 +) => Record<string, unknown>;
69 +type ProviderEnvironment = NonNullable<ProviderInstanceConfig["environment"]>;
70
71 export function mapSettingsSecrets(
72 settings: ServerSettings,
73 map: (secret: SettingsSecret) => SecretValue,
74 ): ServerSettings {
66 - const mapFields = (
67 - fields: Readonly<Record<string, unknown>>,
68 - secretFields: ReadonlyArray<string>,
69 - name: (field: string, serverHost: string | null) => string,
70 - ) => {
75 + const mapFields: SecretFieldsMapper = (fields, secretFields, name) => {
76 const next = { ...fields };
77 for (const field of secretFields) {
78 if (!(field in next) || isSecretReference(next[field])) continue;
@@ -88,6 +93,70 @@ export function mapSettingsSecrets(
93 return next;
94 };
95
96 + return mapSecretFieldGroups(settings, mapFields, (instanceId, environment) =>
97 + environment.map((variable) => {
98 + const { valueRedacted: _omit, ...rest } = variable;
99 + // A secret reference is not itself secret; storage sees the value cleared.
100 + const reference = typeof variable.value === "string" ? undefined : variable.value;
101 + const result = map({
102 + secretName: `provider-env-${encode(instanceId)}-${encode(variable.name)}`,
103 + kind: "environment",
104 + value: typeof variable.value === "string" ? variable.value : "",
105 + redacted: reference === undefined && variable.valueRedacted === true,
106 + sensitive: variable.sensitive,
107 + providerInstanceId: instanceId,
108 + environmentVariable: variable.name,
109 + });
110 + if (reference !== undefined) return { ...rest, value: reference };
111 + return {
112 + ...rest,
113 + value: result.value,
114 + ...(result.redacted ? { valueRedacted: true } : {}),
115 + };
116 + }),
117 + );
118 +}
119 +
120 +/**
121 + * Maps each value a secret field holds, literal or reference, with the secret name of its slot.
122 + * Provider environment variables are left as they are.
123 + */
124 +export function mapSettingsSecretValues(
125 + settings: ServerSettings,
126 + map: (value: SettingsSecretValue, secretName: string) => SettingsSecretValue,
127 +): ServerSettings {
128 + const mapValue = (value: unknown, secretName: string) =>
129 + typeof value === "string" || isSecretReference(value) ? map(value, secretName) : value;
130 + return mapSecretFieldGroups(settings, (fields, secretFields, name) => {
131 + const next = { ...fields };
132 + for (const field of secretFields) {
133 + if (!(field in next)) continue;
134 + const value = next[field];
135 + next[field] =
136 + value !== null &&
137 + typeof value === "object" &&
138 + !Array.isArray(value) &&
139 + !isSecretReference(value)
140 + ? Object.fromEntries(
141 + Object.entries(value).map(([serverHost, entry]) => [
142 + serverHost,
143 + mapValue(entry, name(field, serverHost.trim().toLowerCase())),
144 + ]),
145 + )
146 + : mapValue(value, name(field, null));
147 + }
148 + return next;
149 + });
150 +}
151 +
152 +function mapSecretFieldGroups(
153 + settings: ServerSettings,
154 + mapFields: SecretFieldsMapper,
155 + mapEnvironment: (instanceId: string, environment: ProviderEnvironment) => ProviderEnvironment = (
156 + _instanceId,
157 + environment,
158 + ) => environment,
159 +): ServerSettings {
160 const providerInstances = Object.fromEntries(
161 Object.entries(settings.providerInstances).map(([instanceId, instance]) => {
162 const config = instance.config;
@@ -107,28 +176,7 @@ export function mapSettingsSecrets(
176 }
177 : {}),
178 ...(instance.environment
110 - ? {
111 - environment: instance.environment.map((variable) => {
112 - const { valueRedacted: _omit, ...rest } = variable;
113 - // A secret reference is not itself secret; storage sees the value cleared.
114 - const reference = typeof variable.value === "string" ? undefined : variable.value;
115 - const result = map({
116 - secretName: `provider-env-${encode(instanceId)}-${encode(variable.name)}`,
117 - kind: "environment",
118 - value: typeof variable.value === "string" ? variable.value : "",
119 - redacted: reference === undefined && variable.valueRedacted === true,
120 - sensitive: variable.sensitive,
121 - providerInstanceId: instanceId,
122 - environmentVariable: variable.name,
123 - });
124 - if (reference !== undefined) return { ...rest, value: reference };
125 - return {
126 - ...rest,
127 - value: result.value,
128 - ...(result.redacted ? { valueRedacted: true } : {}),
129 - };
130 - }),
131 - }
179 + ? { environment: mapEnvironment(instanceId, instance.environment) }
180 : {}),
181 },
182 ];
apps/server/src/sourceControl/sourceControlHostSecrets.test.ts
+21 -2
@@ -1,5 +1,5 @@
1 import { assert, it } from "@effect/vitest";
2 -import { SecretProviderId } from "@t3tools/contracts";
2 +import { SecretProviderId, UsageLimitSourceId } from "@t3tools/contracts";
3 import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
4 import * as Effect from "effect/Effect";
5
@@ -125,12 +125,31 @@ it.effect("reads a collected reference again once it is invalidated", () =>
125 }),
126 });
127 const read = () => resolveSourceControlHostSecrets(resolver, hosts, "bitbucket");
128 + const usageLimitSources = {
129 + [UsageLimitSourceId.make("referenced")]: {
130 + kind: "cliproxy",
131 + url: "https://hub.test",
132 + managementKey: source("cliproxy#key"),
133 + enabled: true,
134 + },
135 + [UsageLimitSourceId.make("literal")]: {
136 + kind: "cliproxy",
137 + url: "https://hub.test",
138 + managementKey: "plain-key",
139 + enabled: true,
140 + },
141 + } as const;
142 + cache.set("cliproxy#key", "stale");
143 assert.deepEqual((yield* read()).bitbucket, {
144 email: "me@example.test",
145 accessToken: "stale",
146 });
147 current = "rotated";
133 - yield* invalidateSettingsSecrets(resolver, Effect.succeed({ sourceControlHosts: hosts }));
148 + yield* invalidateSettingsSecrets(
149 + resolver,
150 + Effect.succeed({ sourceControlHosts: hosts, usageLimitSources }),
151 + );
152 + assert.isFalse(cache.has("cliproxy#key"));
153 assert.deepEqual((yield* read()).bitbucket, {
154 email: "me@example.test",
155 accessToken: "rotated",
apps/server/src/sourceControl/sourceControlHostSecrets.ts
+12 -2
@@ -97,13 +97,23 @@ export const resolveSourceControlHostSecrets = Effect.fn("SourceControlHost.reso
97 },
98 );
99
100 +const collectUsageLimitSecretReferences = (
101 + sources: ServerSettings["usageLimitSources"],
102 +): ReadonlyArray<SecretReference> =>
103 + Object.values(sources).flatMap(({ managementKey }) =>
104 + isSecretReference(managementKey) ? [managementKey] : [],
105 + );
106 +
107 /** Settings that cannot be read clear every cached secret, so a refresh never keeps a stale one. */
108 export const invalidateSettingsSecrets = Effect.fn("SettingsSecrets.invalidate")(function* <E>(
109 resolver: SecretResolver.SecretResolver["Service"],
103 - settings: Effect.Effect<Pick<ServerSettings, "sourceControlHosts">, E>,
110 + settings: Effect.Effect<Pick<ServerSettings, "sourceControlHosts" | "usageLimitSources">, E>,
111 ) {
112 const references = yield* settings.pipe(
106 - Effect.map((current) => collectSourceControlHostSecretReferences(current.sourceControlHosts)),
113 + Effect.map((current) => [
114 + ...collectSourceControlHostSecretReferences(current.sourceControlHosts),
115 + ...collectUsageLimitSecretReferences(current.usageLimitSources),
116 + ]),
117 Effect.orElseSucceed(() => undefined),
118 );
119 yield* resolver.invalidate(references);
apps/server/src/usage/UsageLimitSources.test.ts
+70 -2
@@ -1,10 +1,11 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import { expect, it } from "@effect/vitest";
3 -import { ServerConfigStreamEvent, UsageLimitSourceId } from "@t3tools/contracts";
3 +import { SecretProviderId, ServerConfigStreamEvent, UsageLimitSourceId } from "@t3tools/contracts";
4 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
7 -import { HttpClient } from "effect/http";
8 +import { HttpClient, HttpClientResponse } from "effect/http";
9
10 import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
11 import * as ServerSettings from "../serverSettings.ts";
@@ -36,6 +37,10 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () =>
37 );
38 }).pipe(
39 Effect.provide([
40 + Layer.succeed(SecretResolver.SecretResolver, {
41 + read: (references) => Effect.succeed(references.map(() => undefined)),
42 + invalidate: () => Effect.void,
43 + }),
44 ServerSettings.layerTest({
45 usageLimitSources: {
46 [UsageLimitSourceId.make("local-hub")]: {
@@ -83,3 +88,66 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () =>
88 Effect.scoped,
89 ),
90 );
91 +
92 +it.effect("reads a management key from its secret provider", () => {
93 + const authorizations: Array<string | undefined> = [];
94 + const keySource = (reference: string) => ({
95 + provider: SecretProviderId.make("homelab"),
96 + reference,
97 + });
98 + return Effect.gen(function* () {
99 + const sources = yield* UsageLimitSources.make;
100 + yield* sources.refresh;
101 + const snapshots = yield* sources.current;
102 + expect(snapshots.map(({ id, error }) => ({ id, error }))).toEqual([
103 + { id: "resolved-hub", error: undefined },
104 + {
105 + id: "unresolved-hub",
106 + error: "Could not read the management key from its secret provider.",
107 + },
108 + ]);
109 + expect(authorizations).toEqual(["Bearer resolved-key"]);
110 + }).pipe(
111 + Effect.provide([
112 + ServerSettings.layerTest({
113 + usageLimitSources: {
114 + [UsageLimitSourceId.make("resolved-hub")]: {
115 + kind: "cliproxy",
116 + url: "https://resolved.test",
117 + managementKey: keySource("cliproxy#key"),
118 + enabled: true,
119 + },
120 + [UsageLimitSourceId.make("unresolved-hub")]: {
121 + kind: "cliproxy",
122 + url: "https://unresolved.test",
123 + managementKey: keySource("missing#key"),
124 + enabled: true,
125 + },
126 + },
127 + }),
128 + Layer.mock(BackgroundPolicy.BackgroundPolicy)({
129 + shouldRunScopeWork: () => Effect.succeed(false),
130 + }),
131 + Layer.succeed(SecretResolver.SecretResolver, {
132 + read: (references) =>
133 + Effect.succeed(
134 + references.map((reference) =>
135 + reference.reference === "cliproxy#key" ? "resolved-key" : undefined,
136 + ),
137 + ),
138 + invalidate: () => Effect.void,
139 + }),
140 + Layer.succeed(
141 + HttpClient.HttpClient,
142 + HttpClient.make((request) =>
143 + Effect.sync(() => {
144 + authorizations.push(request.headers.authorization);
145 + return HttpClientResponse.fromWeb(request, Response.json({ files: [] }));
146 + }),
147 + ),
148 + ),
149 + NodeCrypto.layer,
150 + ]),
151 + Effect.scoped,
152 + );
153 +});
apps/server/src/usage/UsageLimitSources.ts
+37 -7
@@ -4,7 +4,8 @@ import {
4 type UsageLimitSourceConsumeResetCreditInput,
5 type ProviderConsumeResetCreditResult,
6 type ServerSettings,
7 - type UsageLimitSourceConfig,
7 + UsageLimitSourceConfig,
8 + settingsSecretLiteral,
9 type UsageLimitSourceId,
10 type UsageLimitSourceSnapshot,
11 } from "@t3tools/contracts";
@@ -21,6 +22,9 @@ import * as Semaphore from "effect/Semaphore";
22 import * as Stream from "effect/Stream";
23
24 import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
25 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
26 +import * as SecretResolverLayer from "../secrets/SecretResolver.ts";
27 +import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts";
28 import * as Settings from "../serverSettings.ts";
29 import { makeCliproxyApi } from "./cliproxyApi.ts";
30
@@ -46,11 +50,24 @@ function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
50 }
51 }
52
53 +function missingManagementKey(config: UsageLimitSourceConfig): string {
54 + return typeof config.managementKey === "string"
55 + ? "No management key configured."
56 + : "Could not read the management key from its secret provider.";
57 +}
58 +
59 /** @public */
60 export const make = Effect.gen(function* () {
61 const api = yield* makeCliproxyApi;
62 const settingsService = yield* Settings.ServerSettingsService;
63 + const secrets = yield* SecretResolver.SecretResolver;
64 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
65 + const readManagementKey = Effect.fn("UsageLimitSources.readManagementKey")(function* (
66 + config: UsageLimitSourceConfig,
67 + ) {
68 + const resolved = yield* resolveSettingsSecrets(secrets, UsageLimitSourceConfig, config);
69 + return settingsSecretLiteral(resolved.managementKey);
70 + });
71 const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
72 const changes = yield* Effect.acquireRelease(
73 PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),
@@ -63,10 +80,13 @@ export const make = Effect.gen(function* () {
80 ) {
81 const checkedAt = DateTime.formatIso(yield* DateTime.now);
82 const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const;
66 - if (config.managementKey.length === 0) {
67 - return { ...base, accounts: [], error: "No management key configured." };
83 + const managementKey = yield* readManagementKey(config);
84 + if (managementKey.length === 0) {
85 + return { ...base, accounts: [], error: missingManagementKey(config) };
86 }
69 - const accounts = yield* api.readAccounts(config).pipe(Effect.result);
87 + const accounts = yield* api
88 + .readAccounts({ url: config.url, managementKey })
89 + .pipe(Effect.result);
90 if (accounts._tag === "Failure") {
91 yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
92 return { ...base, accounts: [], error: accounts.failure.detail };
@@ -108,12 +128,20 @@ export const make = Effect.gen(function* () {
128 Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),
129 );
130 const config = settings.usageLimitSources[input.sourceId];
111 - if (!config?.enabled || !config.managementKey) {
131 + if (!config?.enabled) {
132 return yield* new UsageLimitSourceError({
133 detail: "The usage limit source is missing or disabled.",
134 });
135 }
116 - const result = yield* api.consume(config, input.accountId, input.creditId);
136 + const managementKey = yield* readManagementKey(config);
137 + if (managementKey.length === 0) {
138 + return yield* new UsageLimitSourceError({ detail: missingManagementKey(config) });
139 + }
140 + const result = yield* api.consume(
141 + { url: config.url, managementKey },
142 + input.accountId,
143 + input.creditId,
144 + );
145 const snapshot = yield* readSource(input.sourceId, config);
146 const previous = yield* Ref.get(stateRef);
147 yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
@@ -167,4 +195,6 @@ export const make = Effect.gen(function* () {
195 } satisfies UsageLimitSources["Service"];
196 });
197
170 -export const layer = Layer.effect(UsageLimitSources, make);
198 +export const layer = Layer.effect(UsageLimitSources, make).pipe(
199 + Layer.provide(SecretResolverLayer.layer),
200 +);
apps/server/src/usage/cliproxyApi.ts
+26 -20
@@ -18,6 +18,12 @@ import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
18 import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts";
19 import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
20
21 +/** A hub with its management key already read from wherever the setting keeps it. */
22 +export interface CliproxyHub {
23 + readonly url: UsageLimitSourceConfig["url"];
24 + readonly managementKey: string;
25 +}
26 +
27 const AuthFile = Schema.Struct({
28 id: Schema.String,
29 auth_index: Schema.String,
@@ -173,7 +179,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
179 const digest = yield* Digest.Digest;
180
181 const management = Effect.fn("CliproxyApi.management")(function* (
176 - config: UsageLimitSourceConfig,
182 + hub: CliproxyHub,
183 path: string,
184 body?: unknown,
185 ) {
@@ -181,13 +187,13 @@ export const makeCliproxyApi = Effect.gen(function* () {
187 try: () =>
188 new URL(
189 `v0/management/${path}`,
184 - config.url.endsWith("/") ? config.url : `${config.url}/`,
190 + hub.url.endsWith("/") ? hub.url : `${hub.url}/`,
191 ).toString(),
192 catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
193 });
194 const request = (
195 body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
190 - ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${config.managementKey}`));
196 + ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${hub.managementKey}`));
197 const response = yield* client
198 .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
199 .pipe(
@@ -201,13 +207,13 @@ export const makeCliproxyApi = Effect.gen(function* () {
207 return response;
208 });
209
204 - const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (config: UsageLimitSourceConfig) {
205 - const response = yield* management(config, "auth-files");
210 + const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (hub: CliproxyHub) {
211 + const response = yield* management(hub, "auth-files");
212 return (yield* decodeAuthFiles(response)).files;
213 });
214
215 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
210 - config: UsageLimitSourceConfig,
216 + hub: CliproxyHub,
217 account: typeof AuthFile.Type,
218 url: string,
219 data?: unknown,
@@ -229,7 +235,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
235 // The OAuth usage endpoint can return 429 without a Claude Code user agent.
236 "User-Agent": "claude-code/2.1.273",
237 };
232 - const raw = yield* management(config, "api-call", {
238 + const raw = yield* management(hub, "api-call", {
239 auth_index: account.auth_index,
240 method: data === undefined ? "GET" : "POST",
241 url,
@@ -246,10 +252,10 @@ export const makeCliproxyApi = Effect.gen(function* () {
252 });
253
254 const credits = Effect.fn("CliproxyApi.credits")(function* (
249 - config: UsageLimitSourceConfig,
255 + hub: CliproxyHub,
256 account: typeof AuthFile.Type,
257 ) {
252 - const body = yield* apiCall(config, account, CREDIT_URL);
258 + const body = yield* apiCall(hub, account, CREDIT_URL);
259 const response = yield* decodeCreditList(body);
260 const now = DateTime.toEpochMillis(yield* DateTime.now);
261 return response.credits
@@ -263,7 +269,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
269 });
270
271 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
266 - config: UsageLimitSourceConfig,
272 + hub: CliproxyHub,
273 account: typeof AuthFile.Type,
274 ) {
275 const checkedAt = DateTime.formatIso(yield* DateTime.now);
@@ -277,7 +283,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
283 };
284 const read = Effect.gen(function* () {
285 if (account.provider === "claude") {
280 - const body = yield* apiCall(config, account, "https://api.anthropic.com/api/oauth/usage");
286 + const body = yield* apiCall(hub, account, "https://api.anthropic.com/api/oauth/usage");
287 const usage = yield* decodeClaudeUsage(body);
288 const model_scoped = (usage.limits ?? []).flatMap((limit) =>
289 limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
@@ -309,7 +315,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
315 }).limits,
316 };
317 }
312 - const body = yield* apiCall(config, account, `${CODEX_BASE}/usage`);
318 + const body = yield* apiCall(hub, account, `${CODEX_BASE}/usage`);
319 const usage = yield* decodeCodexUsage(body);
320 const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
321 window
@@ -321,7 +327,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
327 : { windowDurationMins: window.limit_window_seconds / 60 }),
328 }
329 : null;
324 - const available = yield* credits(config, account).pipe(Effect.orElseSucceed(() => undefined));
330 + const available = yield* credits(hub, account).pipe(Effect.orElseSucceed(() => undefined));
331 const next = available?.[0];
332 const planType =
333 usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type;
@@ -366,9 +372,9 @@ export const makeCliproxyApi = Effect.gen(function* () {
372 });
373
374 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
369 - config: UsageLimitSourceConfig,
375 + hub: CliproxyHub,
376 ): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
371 - const accounts = yield* authFiles(config).pipe(
377 + const accounts = yield* authFiles(hub).pipe(
378 Effect.mapError((error) =>
379 isUsageLimitSourceError(error)
380 ? error
@@ -380,24 +386,24 @@ export const makeCliproxyApi = Effect.gen(function* () {
386 (account) =>
387 !account.disabled && (account.provider === "codex" || account.provider === "claude"),
388 ),
383 - (account) => readAccount(config, account),
389 + (account) => readAccount(hub, account),
390 { concurrency: 4 },
391 );
392 });
393
394 const consume = Effect.fn("CliproxyApi.consume")(function* (
389 - config: UsageLimitSourceConfig,
395 + hub: CliproxyHub,
396 accountId: string,
397 creditId: string,
398 ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
399 const operation = Effect.gen(function* () {
394 - const account = (yield* authFiles(config)).find((account) => account.id === accountId);
400 + const account = (yield* authFiles(hub)).find((account) => account.id === accountId);
401 if (!account || account.disabled || account.provider !== "codex") {
402 return yield* new UsageLimitSourceError({
403 detail: "The Codex hub account is missing or disabled.",
404 });
405 }
400 - const body = yield* apiCall(config, account, `${CREDIT_URL}/consume`, {
406 + const body = yield* apiCall(hub, account, `${CREDIT_URL}/consume`, {
407 redeem_request_id: yield* creditRedeemRequestId(
408 account.id_token?.chatgpt_account_id ?? account.id,
409 creditId,
@@ -414,7 +420,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
420 } as const
421 )[response.code];
422 if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
417 - const cleared = yield* management(config, "reset-quota", {
423 + const cleared = yield* management(hub, "reset-quota", {
424 auth_index: account.auth_index,
425 }).pipe(Effect.result);
426 return {
apps/server/src/ws.test.ts
+8 -4
@@ -886,6 +886,7 @@ it.effect.each([
886 {},
887 yield* ServerBrowser.ServerBrowser,
888 () => Effect.void,
889 + { secretReferences: true },
890 ).pipe(Layer.provide(configRpcServices)),
891 ),
892 );
@@ -930,8 +931,8 @@ it.effect.each([
931 key: "mod+alt+z",
932 command: "terminal.split",
933 });
933 - const expectedSettings = [duringDiscovery, latestSettings].map(
934 - ServerSettings.redactServerSettingsForClient,
934 + const expectedSettings = [duringDiscovery, latestSettings].map((value) =>
935 + ServerSettings.redactServerSettingsForClient(value, { secretReferences: true }),
936 );
937 const expectedKeybindings = [duringAck.keybindings, latestKeybindings.keybindings];
938 // The two sources can interleave, but each must retain its own publication order.
@@ -959,7 +960,7 @@ it.effect.each([
960 assert.deepEqual(resolved.config.remoteOpenTargets, targets);
961 assert.deepEqual(
962 resolved.config.settings,
962 - ServerSettings.redactServerSettingsForClient(latestSettings),
963 + ServerSettings.redactServerSettingsForClient(latestSettings, { secretReferences: true }),
964 );
965 assert.deepEqual(resolved.config.keybindings, latestKeybindings.keybindings);
966 yield* acknowledge;
@@ -974,7 +975,9 @@ it.effect.each([
975 assert.deepEqual(resolved.config.directEndpoints, endpoints);
976 assert.deepEqual(
977 resolved.config.settings,
977 - ServerSettings.redactServerSettingsForClient(latestSettings),
978 + ServerSettings.redactServerSettingsForClient(latestSettings, {
979 + secretReferences: true,
980 + }),
981 );
982 assert.deepEqual(resolved.config.keybindings, latestKeybindings.keybindings);
983 yield* acknowledge;
@@ -1104,6 +1107,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", (
1107 {},
1108 yield* ServerBrowser.ServerBrowser,
1109 () => Effect.void,
1110 + { secretReferences: true },
1111 ).pipe(Layer.provide(configRpcServices)),
1112 ),
1113 );
apps/server/src/ws.ts
+23 -6
@@ -55,6 +55,8 @@ import {
55 OrchestrationGetTurnDiffError,
56 ORCHESTRATION_V2_WS_METHODS,
57 ORCHESTRATION_PROTOCOL_QUERY_PARAM,
58 + CLIENT_CAPABILITIES_QUERY_PARAM,
59 + SETTINGS_SECRET_REFERENCES_CAPABILITY,
60 ORCHESTRATION_PROTOCOL_VERSION,
61 OrchestrationV2DispatchCommandError,
62 OrchestrationV2GetShellSnapshotError,
@@ -695,6 +697,11 @@ function hasCompatibleOrchestrationProtocol(url: URL): boolean {
697 );
698 }
699
700 +function readSettingsClient(url: URL) {
701 + const capabilities = url.searchParams.get(CLIENT_CAPABILITIES_QUERY_PARAM)?.split(",") ?? [];
702 + return { secretReferences: capabilities.includes(SETTINGS_SECRET_REFERENCES_CAPABILITY) };
703 +}
704 +
705 function shouldUseBoundedThreadSnapshot(input: {
706 readonly acceptBoundedSnapshot?: boolean;
707 readonly acceptDeferredWork?: boolean;
@@ -1341,6 +1348,7 @@ export const layerWsRpc = (
1348 clientAnalyticsProps: Readonly<Record<string, unknown>>,
1349 serverBrowser: ServerBrowser.ServerBrowser["Service"],
1350 reportProfiles: ServerBrowser.ProfileReporter,
1351 + settingsClient: { readonly secretReferences: boolean },
1352 ) =>
1353 Layer.effectContext(
1354 Effect.gen(function* () {
@@ -1854,6 +1862,7 @@ export const layerWsRpc = (
1862 : commandProviders;
1863 const settings = ServerSettings.redactServerSettingsForClient(
1864 yield* serverSettings.getSettings,
1865 + settingsClient,
1866 );
1867 const environment = yield* serverEnvironment.getDescriptor;
1868 const auth = yield* serverAuth.getDescriptor();
@@ -2415,13 +2424,13 @@ export const layerWsRpc = (
2424 fresh: input.fresh,
2425 });
2426 }
2427 + if (input.reloadSecrets === true && input.instanceId === undefined) {
2428 + yield* invalidateSettingsSecrets(secretResolver, serverSettings.getSettings);
2429 + }
2430 // Await refresh; RPC scope closure would interrupt a fork before the hub answered.
2431 if (input.instanceId === undefined) {
2432 yield* usageLimitSources.refresh;
2433 }
2422 - if (input.reloadSecrets === true && input.instanceId === undefined) {
2423 - yield* invalidateSettingsSecrets(secretResolver, serverSettings.getSettings);
2424 - }
2434 let providers = yield* input.cwd !== undefined && input.instanceId !== undefined
2435 ? providerRegistry.refreshWorkspaceSnapshot({
2436 instanceId: input.instanceId,
@@ -2629,7 +2638,7 @@ export const layerWsRpc = (
2638 const settings = yield* providerInstanceMutation === undefined
2639 ? serverSettings.updateSettings(nextPatch)
2640 : serverSettings.updateProviderInstance(providerInstanceMutation, nextPatch);
2632 - return ServerSettings.redactServerSettingsForClient(settings);
2641 + return ServerSettings.redactServerSettingsForClient(settings, settingsClient);
2642 }),
2643 [WS_METHODS.serverDiscoverSourceControl]: (_input) => sourceControlDiscovery.discover,
2644 [WS_METHODS.serverGetTraceDiagnostics]: (_input) =>
@@ -3288,7 +3297,9 @@ export const layerWsRpc = (
3297 )
3298 : Stream.empty;
3299 const settingsUpdates = settingsChanges.pipe(
3291 - Stream.map((settings) => ServerSettings.redactServerSettingsForClient(settings)),
3300 + Stream.map((settings) =>
3301 + ServerSettings.redactServerSettingsForClient(settings, settingsClient),
3302 + ),
3303 Stream.map((settings) => ({
3304 version: 1 as const,
3305 type: "settingsUpdated" as const,
@@ -3475,7 +3486,13 @@ export const layer = Layer.unwrap(
3486 return httpEffect;
3487 }).pipe(
3488 Effect.provide(
3478 - layerWsRpc(session, clientAnalyticsProps, serverBrowser, reportProfiles).pipe(
3489 + layerWsRpc(
3490 + session,
3491 + clientAnalyticsProps,
3492 + serverBrowser,
3493 + reportProfiles,
3494 + readSettingsClient(url.value),
3495 + ).pipe(
3496 Layer.provideMerge(RpcSerialization.layerJson),
3497 // Handler-context reporters see only request defects, not server-wide defects.
3498 Layer.provide(DefectReporter.layer),
apps/web/src/components/settings/AddUsageLimitSourceDialog.tsx
+16 -9
@@ -1,4 +1,4 @@
1 -import type { EnvironmentId, UnifiedSettings } from "@t3tools/contracts";
1 +import type { EnvironmentId, SecretReference, UnifiedSettings } from "@t3tools/contracts";
2 import { useState } from "react";
3
4 import { useUpdateEnvironmentSettings } from "../../hooks/useSettings";
@@ -14,7 +14,7 @@ import {
14 } from "../ui/dialog";
15 import { Input } from "../ui/input";
16 import { sourceIdFromUrl } from "./AddUsageLimitSourceDialog.logic";
17 -import { SecretInput } from "./SecretInput";
17 +import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
18 import { Label } from "../ui/label";
19
20 /** Send the management key once to server secret storage; settings retain only a redaction marker. */
@@ -34,14 +34,16 @@ export function AddUsageLimitSourceDialog({
34 const updateSettings = useUpdateEnvironmentSettings(environmentId);
35 const [label, setLabel] = useState("");
36 const [url, setUrl] = useState("");
37 - const [managementKey, setManagementKey] = useState("");
37 + const secretSources = useSecretSources(environmentId);
38 + const [keyDraft, setKeyDraft] = useState<string | SecretReference>("");
39 + const managementKey = typeof keyDraft === "string" ? keyDraft.trim() : keyDraft;
40 const trimmedUrl = url.trim();
39 - const canSave = trimmedUrl.length > 0 && managementKey.trim().length > 0;
41 + const canSave = trimmedUrl.length > 0 && managementKey !== "";
42
43 const reset = () => {
44 setLabel("");
45 setUrl("");
44 - setManagementKey("");
46 + setKeyDraft("");
47 };
48
49 const save = () => {
@@ -53,7 +55,7 @@ export function AddUsageLimitSourceDialog({
55 kind: "cliproxy",
56 ...(label.trim() ? { label: label.trim() } : {}),
57 url: trimmedUrl,
56 - managementKey: managementKey.trim(),
58 + managementKey,
59 enabled: true,
60 },
61 },
@@ -98,10 +100,15 @@ export function AddUsageLimitSourceDialog({
100 </div>
101 <div className="grid gap-1.5">
102 <Label htmlFor="usage-source-key">Management key</Label>
101 - <SecretInput
103 + <SecretSourceInput
104 id="usage-source-key"
103 - value={managementKey}
104 - onChange={(event) => setManagementKey(event.target.value)}
105 + aria-label="Management key"
106 + value={keyDraft}
107 + sources={secretSources}
108 + onChange={(event) => setKeyDraft(event.target.value)}
109 + onSecretChange={(secret) => setKeyDraft(secret ?? "")}
110 + onProviderPick={() => setKeyDraft("")}
111 + onReferenceReject={() => setKeyDraft("")}
112 />
113 </div>
114 <div className="grid gap-1.5">
apps/web/src/components/settings/SecretSourceInput.browser.test.tsx
+23
@@ -23,6 +23,7 @@ async function commitReference(screen: Screen, value: string) {
23 describe("SecretSourceInput", () => {
24 it("moves a reference to another provider only once one is committed for it", async () => {
25 const onSecretChange = vi.fn();
26 + const onProviderPick = vi.fn();
27 await using screen = await render(
28 <SecretSourceInput
29 aria-label="API key"
@@ -30,12 +31,14 @@ describe("SecretSourceInput", () => {
31 sources={sources}
32 onCommit={() => {}}
33 onSecretChange={onSecretChange}
34 + onProviderPick={onProviderPick}
35 />,
36 );
37
38 await userEvent.click(screen.getByRole("combobox", { name: "API key source" }));
39 await userEvent.click(screen.getByRole("option", { name: "Work" }));
40 expect(onSecretChange).not.toHaveBeenCalled();
41 + expect(onProviderPick).toHaveBeenCalledOnce();
42 await expect.element(reference(screen)).toHaveValue("");
43
44 await commitReference(screen, "op://Shared/OpenAI/credential");
@@ -57,6 +60,8 @@ describe("SecretSourceInput", () => {
60 />,
61 );
62
63 + await commitReference(screen, "invalid-reference");
64 + await expect.element(reference(screen)).toHaveAttribute("aria-invalid", "true");
65 await userEvent.clear(reference(screen));
66 await userEvent.keyboard("{Enter}");
67 expect(onSecretChange).toHaveBeenCalledExactlyOnceWith(undefined);
@@ -64,6 +69,7 @@ describe("SecretSourceInput", () => {
69
70 it("rejects a reference 1Password cannot read", async () => {
71 const onSecretChange = vi.fn();
72 + const onReferenceReject = vi.fn();
73 await using screen = await render(
74 <SecretSourceInput
75 aria-label="API key"
@@ -71,12 +77,29 @@ describe("SecretSourceInput", () => {
77 sources={sources}
78 onCommit={() => {}}
79 onSecretChange={onSecretChange}
80 + onReferenceReject={onReferenceReject}
81 />,
82 );
83
84 await commitReference(screen, "Private/OpenAI/credential");
85 expect(onSecretChange).not.toHaveBeenCalled();
86 + expect(onReferenceReject).toHaveBeenCalledOnce();
87 + await screen.rerender(
88 + <SecretSourceInput
89 + aria-label="API key"
90 + value=""
91 + sources={sources}
92 + onCommit={() => {}}
93 + onSecretChange={onSecretChange}
94 + onReferenceReject={onReferenceReject}
95 + />,
96 + );
97 await expect.element(reference(screen)).toHaveAttribute("aria-invalid", "true");
98 await expect.element(reference(screen)).toHaveValue("Private/OpenAI/credential");
99 + await commitReference(screen, "op://Private/OpenAI/corrected");
100 + expect(onSecretChange).toHaveBeenCalledExactlyOnceWith({
101 + provider: personal,
102 + reference: "op://Private/OpenAI/corrected",
103 + });
104 });
105 });
apps/web/src/components/settings/SecretSourceInput.tsx
+9
@@ -64,6 +64,10 @@ type SecretSourceInputProps = Omit<ComponentProps<typeof SecretInput>, "value" |
64 readonly value: string | SecretReference;
65 readonly sources: ReadonlyArray<SecretSource>;
66 readonly onSecretChange: (secret: SecretReference | undefined) => void;
67 + /** Called when a provider is picked, before a reference for it exists. */
68 + readonly onProviderPick?: () => void;
69 + /** Called when an edited reference is rejected, so the committed one no longer matches the field. */
70 + readonly onReferenceReject?: () => void;
71 /** Places the parts in the caller's layout; `source` is null when there is nothing to pick. */
72 readonly children?: (parts: {
73 readonly source: ReactNode;
@@ -76,6 +80,8 @@ export function SecretSourceInput({
80 value,
81 sources,
82 onSecretChange,
83 + onProviderPick,
84 + onReferenceReject,
85 children,
86 ...rest
87 }: SecretSourceInputProps) {
@@ -106,6 +112,7 @@ export function SecretSourceInput({
112 return;
113 }
114 const next = value as SecretProviderId;
115 + if (next !== secret?.provider) onProviderPick?.();
116 setPendingProvider(next === secret?.provider ? null : next);
117 }}
118 >
@@ -159,6 +166,8 @@ export function SecretSourceInput({
166 definition?.isReference(decoded.value.reference) === false
167 ) {
168 setRejectedReference(next);
169 + if (onReferenceReject !== undefined) setPendingProvider(provider);
170 + onReferenceReject?.();
171 return;
172 }
173 setRejectedReference(null);
packages/client-runtime/src/connection/compatibility.test.ts
+1
@@ -31,6 +31,7 @@ describe("orchestration protocol compatibility", () => {
31 expect(socketUrl.searchParams.get("orchestrationProtocol")).toBe(
32 String(ORCHESTRATION_PROTOCOL_VERSION),
33 );
34 + expect(socketUrl.searchParams.get("clientCapabilities")).toBe("settingsSecretReferences");
35 expect(socketUrl.searchParams.get("wsTicket")).toBe("secret");
36 expect(socketUrl.searchParams.get("connectionMethod")).toBe("relay");
37 });
packages/client-runtime/src/connection/compatibility.ts
+3
@@ -1,6 +1,8 @@
1 import {
2 + CLIENT_CAPABILITIES_QUERY_PARAM,
3 ORCHESTRATION_PROTOCOL_QUERY_PARAM,
4 ORCHESTRATION_PROTOCOL_VERSION,
5 + SETTINGS_SECRET_REFERENCES_CAPABILITY,
6 type ExecutionEnvironmentDescriptor,
7 } from "@t3tools/contracts";
8
@@ -37,5 +39,6 @@ function canSelfUpdate(descriptor: ExecutionEnvironmentDescriptor): boolean {
39 export function appendOrchestrationProtocol(socketUrl: string): string {
40 const url = new URL(socketUrl);
41 url.searchParams.set(ORCHESTRATION_PROTOCOL_QUERY_PARAM, String(ORCHESTRATION_PROTOCOL_VERSION));
42 + url.searchParams.set(CLIENT_CAPABILITIES_QUERY_PARAM, SETTINGS_SECRET_REFERENCES_CAPABILITY);
43 return url.toString();
44 }
packages/client-runtime/src/connection/resolver.test.ts
+1 -1
@@ -202,7 +202,7 @@ describe("ConnectionResolver", () => {
202 label: "Primary",
203 httpBaseUrl: "http://127.0.0.1:3777",
204 socketUrl:
205 - "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2",
205 + "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2&clientCapabilities=settingsSecretReferences",
206 httpAuthorization: null,
207 target,
208 });
packages/contracts/src/environment.ts
+5
@@ -15,6 +15,11 @@ export const ORCHESTRATION_PROTOCOL_VERSION_TEXT = "2";
15 export const ORCHESTRATION_PROTOCOL_QUERY_PARAM = "orchestrationProtocol";
16 export const ORCHESTRATION_PROTOCOL_HEADER = "x-t3-orchestration-protocol";
17
18 +/** Wire shapes a client understands, comma-separated; a client that omits one gets the older shape. */
19 +export const CLIENT_CAPABILITIES_QUERY_PARAM = "clientCapabilities";
20 +/** Secret fields may hold a secret provider reference instead of a string. */
21 +export const SETTINGS_SECRET_REFERENCES_CAPABILITY = "settingsSecretReferences";
22 +
23 export const ExecutionEnvironmentPlatformOs = Schema.Literals([
24 "darwin",
25 "linux",
packages/contracts/src/settings.ts
+5 -1
@@ -22,6 +22,7 @@ import {
22 import { UsageLimitSourceId } from "./usageLimitSourceId.ts";
23 import { UsageModelFilter } from "./usage.ts";
24 import { SecretProviderId, SecretProviderSlug } from "./secretReference.ts";
25 +import { SettingsSecretValue } from "./settingsSecretValue.ts";
26 import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts";
27 import { KeybindingShortcut } from "./keybindings.ts";
28 import {
@@ -858,7 +859,10 @@ export const UsageLimitSourceConfig = Schema.Struct({
859 kind: Schema.Literal("cliproxy"),
860 label: Schema.optional(TrimmedNonEmptyString),
861 url: TrimmedNonEmptyString,
861 - managementKey: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed("")), secretSetting),
862 + managementKey: SettingsSecretValue.pipe(
863 + Schema.withDecodingDefault(Effect.succeed("")),
864 + secretSetting,
865 + ),
866 enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
867 });
868 export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type;