The best way to control Claude Code, Codex and more from any computer or phone
fix(server): saved secrets only reach the destination they were saved for (#38037)
Julius Marminge committed
Nov 17, 2026 at 01:32 UTC
42a5aade8485122a09b5f4feda9e9fb275dee675
10 files changed
+153
-4
apps/server/src/auth/RpcAuthorization.test.ts
+69
@@ -355,9 +355,78 @@ describe("settings mutation authorization", () => {
355
patch: { requireConnectDeviceApproval: false },
356
}).pipe(Effect.flip),
357
).toMatchObject({ requiredPermission: AuthAccessWriteScope });
358
+ // A reference names any secret the store holds, and the host entry names where it goes.
359
+ expect(
360
+ yield* client[WS_METHODS.serverUpdateSettings]({
361
+ patch: {
362
+ simlockDeviceHosts: [
363
+ {
364
+ kind: "simlock",
365
+ id: "simlock_evil",
366
+ label: "Gateway",
367
+ gatewayUrl: "https://attacker.example",
368
+ agentToken: {
369
+ provider: SecretProviderId.make("personal"),
370
+ reference: "op://Private/OpenAI/credential",
371
+ },
372
+ maxLeases: 2,
373
+ maxLeaseMinutes: 60,
374
+ },
375
+ ],
376
+ },
377
+ }).pipe(Effect.flip),
378
+ ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
379
expect(handled).toBe(false);
380
}),
381
);
382
+
383
+ it.effect("does not let a settings grant send a named secret to a gateway it picks", () =>
384
+ Effect.gen(function* () {
385
+ const group = WsRpcGroup.omit(
386
+ ...[...WsRpcGroup.requests.keys()].filter(
387
+ (
388
+ tag,
389
+ ): tag is Exclude<
390
+ keyof typeof RPC_REQUIRED_SCOPES,
391
+ typeof WS_METHODS.deviceSimlockIdentity
392
+ > => tag !== WS_METHODS.deviceSimlockIdentity,
393
+ ),
394
+ );
395
+ let handled = 0;
396
+ const client = yield* RpcTest.makeClient(group).pipe(
397
+ Effect.provide(
398
+ Layer.mergeAll(
399
+ group.toLayerHandler(WS_METHODS.deviceSimlockIdentity, () =>
400
+ Effect.sync(() => {
401
+ handled++;
402
+ return {
403
+ gatewayUrl: "https://attacker.example",
404
+ signedInAs: "agent",
405
+ tokenSource: "entered" as const,
406
+ };
407
+ }),
408
+ ),
409
+ RpcAuthorization.layer([AuthSettingsWriteScope]),
410
+ ),
411
+ ),
412
+ );
413
+ yield* client[WS_METHODS.deviceSimlockIdentity]({
414
+ gatewayUrl: "https://attacker.example",
415
+ agentToken: "typed-token",
416
+ });
417
+ expect(handled).toBe(1);
418
+ expect(
419
+ yield* client[WS_METHODS.deviceSimlockIdentity]({
420
+ gatewayUrl: "https://attacker.example",
421
+ agentToken: {
422
+ provider: SecretProviderId.make("personal"),
423
+ reference: "op://Private/OpenAI/credential",
424
+ },
425
+ }).pipe(Effect.flip),
426
+ ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
427
+ expect(handled).toBe(1);
428
+ }),
429
+ );
430
});
431
432
it.effect("requires task permission before attaching a prepared worktree to a thread", () =>
apps/server/src/auth/RpcAuthorization.ts
+10
@@ -2,6 +2,7 @@ import {
2
CLIENT_GUARDED_RPC_SCOPES,
3
type DeviceListInput,
4
clientRpcRequiredScopes,
5
+ containsSecretReference,
6
authScopeRequiredResponse,
7
AssetCreateUrlInput,
8
AuthAccessReadScope,
@@ -282,6 +283,15 @@ const requiredScopesForRpcCall = (
283
];
284
}
285
if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
286
+ // These send the credential they are given to a URL the caller names, as a saved setting would.
287
+ if (
288
+ (method === WS_METHODS.deviceSimlockIdentity ||
289
+ method === WS_METHODS.deviceEasAccount ||
290
+ method === WS_METHODS.serverListTextGeneratorModels) &&
291
+ containsSecretReference(payload)
292
+ ) {
293
+ return [AuthSettingsWriteScope, AuthProvidersManageScope];
294
+ }
295
if (method === WS_METHODS.projectsMutate) {
296
return requiredScopesForProjectMutation(decodeProjectMutation(payload));
297
}
apps/server/src/serverSettings.test.ts
+19
@@ -16,6 +16,7 @@ import {
16
ServerSettings,
17
ServerSettingsPatch,
18
UsageLimitSourceId,
19
+ type SimlockDeviceHostConfig,
20
} from "@t3tools/contracts";
21
import { createModelSelection } from "@t3tools/shared/model";
22
import { assert, it } from "@effect/vitest";
@@ -1859,6 +1860,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1860
assert.deepEqual(configOf(echoed, antigravity)?.apiKey, antigravityReference);
1861
assert.deepEqual(configOf(echoed, openCode)?.serverPassword, openCodeReference);
1862
assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1863
+ // A saved token goes only to the gateway it was saved for, however it is echoed.
1864
+ const moved = (agentToken: SimlockDeviceHostConfig["agentToken"]) =>
1865
+ serverSettings.updateSettings({
1866
+ simlockDeviceHosts: [
1867
+ {
1868
+ ...echoed.simlockDeviceHosts[0]!,
1869
+ gatewayUrl: "https://elsewhere.test",
1870
+ agentToken,
1871
+ },
1872
+ ],
1873
+ });
1874
+ assert.equal((yield* moved(SECRET_REDACTED)).simlockDeviceHosts[0]?.agentToken, "");
1875
+ yield* serverSettings.updateSettings({ simlockDeviceHosts: echoed.simlockDeviceHosts });
1876
+ assert.equal((yield* moved(simlockReference)).simlockDeviceHosts[0]?.agentToken, "");
1877
+ assert.equal(
1878
+ (yield* moved("typed-token")).simlockDeviceHosts[0]?.agentToken,
1879
+ "typed-token",
1880
+ );
1881
}).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1882
);
1883
apps/server/src/serverSettings.ts
+5
-1
@@ -66,6 +66,7 @@ import {
66
mapSettingsSecrets,
67
mapSettingsSecretValues,
68
withoutRemovedSecretProviderReferences,
69
+ withoutRedirectedSimlockTokens,
70
SECRET_REDACTED,
71
type SettingsSecret,
72
} from "./settingsSecrets.ts";
@@ -1203,7 +1204,10 @@ const make = Effect.gen(function* () {
1204
}
1205
// An older client echoes a reference as the redacted marker; restore it before vetting so
1206
// a removed provider's reference is cleared below rather than restored by persistence.
1206
- const updated = withEchoedSecretReferences(current, yield* update(current));
1207
+ const updated = withoutRedirectedSimlockTokens(
1208
+ current,
1209
+ withEchoedSecretReferences(current, yield* update(current)),
1210
+ );
1211
// Vet before secrets: a variable the policy hides from clients is not one they removed.
1212
const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch);
1213
if (vetted._tag === "Locked") {
apps/server/src/settingsSecrets.ts
+30
@@ -292,3 +292,33 @@ export function withoutRemovedSecretProviderReferences(
292
),
293
};
294
}
295
+
296
+const gatewayOrigin = (url: string) => (URL.canParse(url) ? new URL(url).origin : url);
297
+
298
+/**
299
+ * `next` with a Simlock host's kept token cleared when its gateway moved to another origin: a
300
+ * saved token goes only to the gateway it was saved for. A newly entered token stays.
301
+ */
302
+export function withoutRedirectedSimlockTokens(
303
+ current: ServerSettings,
304
+ next: ServerSettings,
305
+): ServerSettings {
306
+ const saved = new Map(current.simlockDeviceHosts.map((host) => [host.id, host]));
307
+ const kept = (token: SettingsSecretValue, savedToken: SettingsSecretValue) =>
308
+ token === SECRET_REDACTED ||
309
+ (isSecretReference(token) &&
310
+ isSecretReference(savedToken) &&
311
+ token.provider === savedToken.provider &&
312
+ token.reference === savedToken.reference);
313
+ return {
314
+ ...next,
315
+ simlockDeviceHosts: next.simlockDeviceHosts.map((host) => {
316
+ const previous = saved.get(host.id);
317
+ return previous &&
318
+ gatewayOrigin(previous.gatewayUrl) !== gatewayOrigin(host.gatewayUrl) &&
319
+ kept(host.agentToken, previous.agentToken)
320
+ ? { ...host, agentToken: "" }
321
+ : host;
322
+ }),
323
+ };
324
+}
apps/server/src/textGeneration/TextGenerators.test.ts
+4
-1
@@ -182,10 +182,13 @@ it.effect("checks unsaved settings, keeping the saved key behind a redaction mar
182
expect((yield* list("draft", { apiKey: "typed-key" })).models).toEqual([
183
{ id: "model-a", name: "model-a" },
184
]);
185
+ yield* list(ID, { apiKey: SECRET_REDACTED, baseUrl: "https://api.test/v1" });
186
+ // The saved key goes only to the endpoint it was saved for.
187
yield* list(ID, { apiKey: SECRET_REDACTED });
188
expect(seen).toEqual([
189
{ url: "https://new.test/v1/models", auth: "Bearer typed-key" },
188
- { url: "https://new.test/v1/models", auth: "Bearer saved-key" },
190
+ { url: "https://api.test/v1/models", auth: "Bearer saved-key" },
191
+ { url: "https://new.test/v1/models", auth: null },
192
]);
193
194
// Listing alone proves nothing about the key on some APIs; a test asks the model itself.
apps/server/src/textGeneration/TextGenerators.ts
+5
-1
@@ -134,7 +134,11 @@ export const make = Effect.gen(function* () {
134
input.config === undefined
135
? saved
136
: input.config.apiKey === SECRET_REDACTED
137
- ? { ...input.config, apiKey: saved?.apiKey ?? "" }
137
+ ? // The saved key goes only to the endpoint it was saved for.
138
+ {
139
+ ...input.config,
140
+ apiKey: saved?.baseUrl === input.config.baseUrl ? saved.apiKey : "",
141
+ }
142
: input.config;
143
if (config === undefined) {
144
return yield* new TextGeneratorRequestError({
packages/contracts/src/auth.ts
+1
@@ -31,6 +31,7 @@ export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;
31
export const AuthOrchestrationReadScope = "orchestration:read" as const;
32
export const AuthOrchestrationOperateScope = "orchestration:operate" as const;
33
export const AuthSettingsWriteScope = "settings:write" as const;
34
+// Also decides where credentials go: secret providers, references, and key-bearing endpoints.
35
export const AuthProvidersManageScope = "providers:manage" as const;
36
export const AuthEnvironmentMaintainScope = "environment:maintain" as const;
37
export const AuthPreviewOperateScope = "preview:operate" as const;
packages/contracts/src/settings.ts
+3
-1
@@ -25,7 +25,7 @@ import {
25
import { UsageLimitSourceId } from "./usageLimitSourceId.ts";
26
import { UsageModelFilter } from "./usage.ts";
27
import { SecretProviderId, SecretProviderSlug } from "./secretReference.ts";
28
-import { SettingsSecretValue } from "./settingsSecretValue.ts";
28
+import { containsSecretReference, SettingsSecretValue } from "./settingsSecretValue.ts";
29
import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts";
30
import { KeybindingShortcut } from "./keybindings.ts";
31
import {
@@ -2020,6 +2020,8 @@ export function requiredScopesForServerSettingsPatch(
2020
changesSettings = true;
2021
}
2022
}
2023
+ // A reference can name any secret the store holds; choosing where one goes is provider authority.
2024
+ if (containsSecretReference(patch)) changesProviders = true;
2025
// Removing a secret provider also clears the settings fields that read from it.
2026
if (Object.values(patch.secretProviders ?? {}).some((entry) => entry === null)) {
2027
changesSettings = true;
packages/contracts/src/settingsSecretValue.ts
+7
@@ -18,6 +18,13 @@ export type SettingsSecretValue = typeof SettingsSecretValue.Type;
18
19
export const isSecretReference = Schema.is(SecretReference);
20
21
+/** Whether a reference appears anywhere in `value`, such as a settings patch or an RPC payload. */
22
+export function containsSecretReference(value: unknown): boolean {
23
+ if (value === null || typeof value !== "object") return false;
24
+ if (isSecretReference(value)) return true;
25
+ return Object.values(value).some(containsSecretReference);
26
+}
27
+
28
/** The literal a credential setting holds, or `""` when it names a secret instead. */
29
export function settingsSecretLiteral(value: SettingsSecretValue | undefined): string {
30
return typeof value === "string" ? value : "";