Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

settingsSecrets.ts

379 lines13.3 KB

1import {
2 AntigravitySettings,
3 ClaudeSettings,
4 CloudSpeechCredentials,
5 CodexSettings,
6 EasDeviceHostConfig,
7 type ProviderInstanceConfig,
8 type ProviderInstanceId,
9 type ServerSettings,
10 type SettingsSecretValue,
11 SimlockDeviceHostConfig,
12 TextGeneratorConfig,
13 UsageLimitSourceConfig,
14 type UsageLimitSourceId,
15 isSecretReference,
16 secretSettingsFields,
17} from "@t3tools/contracts";
18import * as Predicate from "effect/Predicate";
19import { acpRegistryClient } from "@t3tools/provider-acp-registry/client";
20import { cursorClient } from "@t3tools/provider-cursor/client";
21import { grokClient } from "@t3tools/provider-grok/client";
22import { kiroClient } from "@t3tools/provider-kiro/client";
23import { museClient } from "@t3tools/provider-muse/client";
24import { openCodeClient } from "@t3tools/provider-opencode/client";
25import { piClient } from "@t3tools/provider-pi/client";
26import {
27 readSecretFieldValues,
28 SOURCE_CONTROL_HOST_SECRET_FIELDS,
29 sourceControlHostSecretName,
30 writeSecretFieldValues,
31} from "./sourceControl/sourceControlHostSecrets.ts";
32​
33export const SECRET_REDACTED = "\u2022\u2022\u2022\u2022\u2022\u2022";
34​
35const providerSecretFields = new Map([
36 ["codex", secretSettingsFields(CodexSettings)],
37 ["claudeAgent", secretSettingsFields(ClaudeSettings)],
38 ["antigravity", secretSettingsFields(AntigravitySettings)],
39 ...[
40 cursorClient,
41 grokClient,
42 kiroClient,
43 museClient,
44 openCodeClient,
45 piClient,
46 acpRegistryClient,
47 ].map(
48 (definition) =>
49 [definition.driverKind, secretSettingsFields(definition.settingsSchema)] as const,
50 ),
51]);
52const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig);
53const textGeneratorSecretFields = secretSettingsFields(TextGeneratorConfig);
54const voiceSecretFields = secretSettingsFields(CloudSpeechCredentials);
55const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig);
56const simlockDeviceHostSecretFields = secretSettingsFields(SimlockDeviceHostConfig);
57const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url");
58​
59export interface SettingsSecret {
60 readonly secretName: string;
61 readonly kind: "field" | "environment";
62 readonly value: string;
63 readonly redacted: boolean;
64 readonly sensitive: boolean;
65 readonly providerInstanceId?: string;
66 readonly environmentVariable?: string;
68​
69type SecretValue = Pick<SettingsSecret, "value" | "redacted">;
70type SecretSlotName = (field: string, serverHost: string | null) => string;
71type SecretFieldsMapper = (
72 fields: Readonly<Record<string, unknown>>,
73 secretFields: ReadonlyArray<string>,
74 name: SecretSlotName,
75) => Record<string, unknown>;
76type ProviderEnvironment = NonNullable<ProviderInstanceConfig["environment"]>;
77​
78export function mapSettingsSecrets(
79 settings: ServerSettings,
80 map: (secret: SettingsSecret) => SecretValue,
81): ServerSettings {
82 const mapFields: SecretFieldsMapper = (fields, secretFields, name) => {
83 const next = { ...fields };
84 for (const field of secretFields) {
85 if (!(field in next) || isSecretReference(next[field])) continue;
86 next[field] = writeSecretFieldValues(
87 next[field],
88 readSecretFieldValues(next[field]).map(([serverHost, value]) => {
89 const result = map({
90 secretName: name(field, serverHost),
91 kind: "field",
92 value,
93 redacted: value === SECRET_REDACTED,
94 sensitive: true,
95 });
96 return [serverHost, result.redacted ? SECRET_REDACTED : result.value] as const;
97 }),
98 );
99 }
100 return next;
101 };
102​
103 return mapSecretFieldGroups(settings, mapFields, (instanceId, environment) =>
104 environment.map((variable) => {
105 const { valueRedacted: _omit, ...rest } = variable;
106 // A secret reference is not itself secret; storage sees the value cleared.
107 const reference = typeof variable.value === "string" ? undefined : variable.value;
108 const result = map({
109 secretName: `provider-env-${encode(instanceId)}-${encode(variable.name)}`,
110 kind: "environment",
111 value: typeof variable.value === "string" ? variable.value : "",
112 redacted: reference === undefined && variable.valueRedacted === true,
113 sensitive: variable.sensitive,
114 providerInstanceId: instanceId,
115 environmentVariable: variable.name,
116 });
117 if (reference !== undefined) return { ...rest, value: reference };
118 return {
119 ...rest,
120 value: result.value,
121 ...(result.redacted ? { valueRedacted: true } : {}),
122 };
123 }),
124 );
126​
127/**
128 * Maps each value a secret field holds, literal or reference, with the secret name of its slot.
129 * Provider environment variables are left as they are.
130 */
131export function mapSettingsSecretValues(
132 settings: ServerSettings,
133 map: (value: SettingsSecretValue, secretName: string) => SettingsSecretValue,
134): ServerSettings {
135 const mapValue = (value: unknown, secretName: string) =>
136 typeof value === "string" || isSecretReference(value) ? map(value, secretName) : value;
137 return mapSecretFieldGroups(settings, (fields, secretFields, name) => {
138 const next = { ...fields };
139 for (const field of secretFields) {
140 if (!(field in next)) continue;
141 const value = next[field];
142 next[field] =
143 value !== null &&
144 typeof value === "object" &&
145 !Array.isArray(value) &&
146 !isSecretReference(value)
147 ? Object.fromEntries(
148 Object.entries(value).map(([serverHost, entry]) => [
149 serverHost,
150 mapValue(entry, name(field, serverHost.trim().toLowerCase())),
151 ]),
152 )
153 : mapValue(value, name(field, null));
154 }
155 return next;
156 });
158​
159function mapSecretFieldGroups(
160 settings: ServerSettings,
161 mapFields: SecretFieldsMapper,
162 mapEnvironment: (instanceId: string, environment: ProviderEnvironment) => ProviderEnvironment = (
163 _instanceId,
164 environment,
165 ) => environment,
166): ServerSettings {
167 const providerInstances = Object.fromEntries(
168 Object.entries(settings.providerInstances).map(([instanceId, instance]) => {
169 const config = instance.config;
170 return [
171 instanceId,
172 {
173 ...instance,
174 ...(config !== null && typeof config === "object" && !Array.isArray(config)
175 ? {
176 config: mapFields(
177 config as Record<string, unknown>,
178 providerSecretFields.get(instance.driver) ?? [],
179 (field, serverHost) =>
180 `provider-config-${encode(instanceId)}-${encode(instance.driver)}-${encode(field)}` +
181 (serverHost === null ? "" : `-${encode(serverHost)}`),
182 ),
183 }
184 : {}),
185 ...(instance.environment
186 ? { environment: mapEnvironment(instanceId, instance.environment) }
187 : {}),
188 },
189 ];
190 }),
191 );
192​
193 const sourceControlHosts = Object.fromEntries(
194 Object.entries(settings.sourceControlHosts).map(([kind, fields]) => [
195 kind,
196 mapFields(fields, SOURCE_CONTROL_HOST_SECRET_FIELDS.get(kind) ?? [], (field, serverHost) =>
197 sourceControlHostSecretName({ kind, field, serverHost }),
198 ),
199 ]),
200 ) as ServerSettings["sourceControlHosts"];
201​
202 const usageLimitSources = Object.fromEntries(
203 Object.entries(settings.usageLimitSources).map(([id, source]) => [
204 id,
205 mapFields(
206 source,
207 usageLimitSecretFields,
208 (field, serverHost) =>
209 `usage-limit-source-${encode(id)}` +
210 (field === "managementKey" && serverHost === null
211 ? ""
212 : `-${encode(field)}${serverHost === null ? "" : `-${encode(serverHost)}`}`),
213 ),
214 ]),
215 ) as ServerSettings["usageLimitSources"];
216​
217 const textGenerators = Object.fromEntries(
218 Object.entries(settings.textGenerators).map(([id, generator]) => [
219 id,
220 mapFields(
221 generator,
222 textGeneratorSecretFields,
223 (field, serverHost) =>
224 `text-generator-${encode(id)}-${encode(field)}` +
225 (serverHost === null ? "" : `-${encode(serverHost)}`),
226 ),
227 ]),
228 ) as ServerSettings["textGenerators"];
229​
230 const easDeviceHosts = settings.easDeviceHosts.map(
231 (host) =>
232 mapFields(
233 host,
234 easDeviceHostSecretFields,
235 (field, serverHost) =>
236 `device-host-${encode(host.id)}-${encode(field)}` +
237 (serverHost === null ? "" : `-${encode(serverHost)}`),
238 ) as EasDeviceHostConfig,
239 );
240​
241 // Its own prefix: an Expo and a Simlock host may share an id.
242 const simlockDeviceHosts = settings.simlockDeviceHosts.map(
243 (host) =>
244 mapFields(
245 host,
246 simlockDeviceHostSecretFields,
247 (field, serverHost) =>
248 `simlock-device-host-${encode(host.id)}-${encode(field)}` +
249 (serverHost === null ? "" : `-${encode(serverHost)}`),
250 ) as SimlockDeviceHostConfig,
251 );
252​
253 return {
254 ...settings,
255 cloudSpeechCredentials: mapFields(
256 settings.cloudSpeechCredentials,
257 voiceSecretFields,
258 (provider) => `voice-cloud-${provider}`,
259 ) as ServerSettings["cloudSpeechCredentials"],
260 providerInstances,
261 sourceControlHosts,
262 usageLimitSources,
263 textGenerators,
264 easDeviceHosts,
265 simlockDeviceHosts,
266 };
268​
269/**
270 * `next` with every secret reference to a secret provider that `current` has and `next` dropped
271 * unset: a credential field becomes empty, and a provider variable holding one is removed.
272 */
273export function withoutRemovedSecretProviderReferences(
274 current: ServerSettings,
275 next: ServerSettings,
276): ServerSettings {
277 const removed = new Set(
278 Object.keys(current.secretProviders).filter((id) => !Object.hasOwn(next.secretProviders, id)),
279 );
280 if (removed.size === 0) return next;
281 const isRemoved = (value: unknown) => isSecretReference(value) && removed.has(value.provider);
282 const fields = mapSettingsSecretValues(next, (value) => (isRemoved(value) ? "" : value));
283 return {
284 ...fields,
285 providerInstances: Object.fromEntries(
286 Object.entries(fields.providerInstances).map(([instanceId, instance]) => [
287 instanceId,
288 instance.environment?.some((variable) => isRemoved(variable.value))
289 ? {
290 ...instance,
291 environment: instance.environment.filter((variable) => !isRemoved(variable.value)),
292 }
293 : instance,
294 ]),
295 ),
296 };
298​
299/** A URL in the form two spellings of one address share: `URL` normalization, no trailing slash on the path. */
300const destination = (url: unknown) => {
301 if (typeof url !== "string" || !URL.canParse(url)) return url;
302 const parsed = new URL(url);
303 parsed.pathname = parsed.pathname.replace(/\/+$/, "");
304 return parsed.href;
305};
306​
307/** Per provider driver, the config field holding a secret and the one naming where it is sent. */
308const providerSecretDestinations = new Map<string, readonly [secret: string, url: string]>([
309 [openCodeClient.driverKind, ["serverPassword", "serverUrl"]],
310]);
311​
312/**
313 * `next` with a kept secret cleared when the address it is sent to changed: a saved secret goes
314 * only to the address it was saved for. A newly entered secret stays.
315 */
316export function withoutRedirectedSecrets(
317 current: ServerSettings,
318 next: ServerSettings,
319): ServerSettings {
320 const kept = (secret: unknown, saved: unknown) =>
321 secret === SECRET_REDACTED ||
322 (isSecretReference(secret) &&
323 isSecretReference(saved) &&
324 secret.provider === saved.provider &&
325 secret.reference === saved.reference);
326 const rebound = <T extends object>(
327 entry: T,
328 previous: object | null | undefined,
329 secret: string,
330 url: string,
331 ): T => {
332 if (previous === null || previous === undefined) return entry;
333 const fields = entry as Readonly<Record<string, unknown>>;
334 const saved = previous as Readonly<Record<string, unknown>>;
335 return destination(saved[url]) !== destination(fields[url]) &&
336 kept(fields[secret], saved[secret])
337 ? { ...entry, [secret]: "" }
338 : entry;
339 };
340 const simlockHosts = new Map(current.simlockDeviceHosts.map((host) => [host.id, host]));
341 return {
342 ...next,
343 providerInstances: Object.fromEntries(
344 Object.entries(next.providerInstances).map(([instanceId, instance]) => {
345 const fields = providerSecretDestinations.get(instance.driver);
346 const previous = current.providerInstances[instanceId as ProviderInstanceId];
347 return [
348 instanceId,
349 fields !== undefined &&
350 previous?.driver === instance.driver &&
351 Predicate.isObject(instance.config) &&
352 Predicate.isObject(previous.config)
353 ? { ...instance, config: rebound(instance.config, previous.config, ...fields) }
354 : instance,
355 ];
356 }),
357 ) as ServerSettings["providerInstances"],
358 usageLimitSources: Object.fromEntries(
359 Object.entries(next.usageLimitSources).map(([id, source]) => [
360 id,
361 rebound(
362 source,
363 current.usageLimitSources[id as UsageLimitSourceId],
364 "managementKey",
365 "url",
366 ),
367 ]),
368 ) as ServerSettings["usageLimitSources"],
369 textGenerators: Object.fromEntries(
370 Object.entries(next.textGenerators).map(([id, generator]) => [
371 id,
372 rebound(generator, current.textGenerators[id as ProviderInstanceId], "apiKey", "baseUrl"),
373 ]),
374 ) as ServerSettings["textGenerators"],
375 simlockDeviceHosts: next.simlockDeviceHosts.map((host) =>
376 rebound(host, simlockHosts.get(host.id), "agentToken", "gatewayUrl"),
377 ),
378 };