@devries-cameron20 / t3code Mirror · read-only / commits / 4a94658ab4
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, 03:15 UTC

feat(settings): Simlock, Antigravity and OpenCode credentials can come from a secret provider (#31652)

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

Julius Marminge committed Nov 5, 2026 at 15:01 UTC 4a94658ab477728787aaa04a4d32773198e795c7
21 files changed +338 -70
apps/server/src/device/DeviceService.ts
+8 -2
@@ -70,6 +70,7 @@ import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
70 import * as ProcessRunner from "../processRunner.ts";
71 import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
72 import * as SecretResolverLayer from "../secrets/SecretResolver.ts";
73 +import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
74 import * as DeviceHost from "./DeviceHost.ts";
75 import * as SshDeviceHost from "./SshDeviceHost.ts";
76 import * as EasDeviceHost from "./EasDeviceHost.ts";
@@ -1594,8 +1595,11 @@ export const make = Effect.gen(function* () {
1595 (host) => host.id === input.hostId,
1596 );
1597 const token = input.agentToken
1597 - ? { agentToken: input.agentToken, source: "entered" as const }
1598 - : SimlockDeviceHost.resolveSimlockToken(gatewayUrl, savedHost, environment);
1598 + ? {
1599 + agentToken: yield* requireSettingsSecret(secrets, input.agentToken),
1600 + source: "entered" as const,
1601 + }
1602 + : yield* SimlockDeviceHost.resolveSimlockToken(secrets, gatewayUrl, savedHost, environment);
1603 if (!token)
1604 return yield* new DeviceSimlockIdentityError({
1605 reason: savedHost?.agentToken
@@ -1623,6 +1627,8 @@ export const make = Effect.gen(function* () {
1627 Effect.catchTags({
1628 ServerSettingsError: () =>
1629 Effect.fail(new DeviceSimlockIdentityError({ reason: "Could not read the saved token." })),
1630 + SettingsSecretUnresolvedError: (error) =>
1631 + Effect.fail(new DeviceSimlockIdentityError({ reason: error.message })),
1632 }),
1633 Effect.provide(simlockContext),
1634 );
apps/server/src/device/SimlockDeviceHost.test.ts
+55 -5
@@ -1,6 +1,7 @@
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import type { SimlockDeviceHostConfig } from "@t3tools/contracts";
3 +import { SecretProviderId, type SimlockDeviceHostConfig } from "@t3tools/contracts";
4 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
@@ -143,9 +144,22 @@ const fakePool = (
144 };
145 });
146
146 -const layer = Layer.mergeAll(
147 - ServerConfig.layerTest(process.cwd(), { prefix: "t3-simlock-host-" }),
148 -).pipe(Layer.provideMerge(NodeServices.layer));
147 +const makeSecretResolver = (values: Record<string, string> = {}) =>
148 + Layer.succeed(SecretResolver.SecretResolver, {
149 + read: (references) =>
150 + Effect.succeed(references.map((reference) => values[reference.reference])),
151 + invalidate: () => Effect.void,
152 + });
153 +
154 +const layerWith = (secrets: Layer.Layer<SecretResolver.SecretResolver>) =>
155 + Layer.mergeAll(
156 + ServerConfig.layerTest(process.cwd(), { prefix: "t3-simlock-host-" }),
157 + secrets,
158 + ).pipe(Layer.provideMerge(NodeServices.layer));
159 +
160 +const layer = layerWith(makeSecretResolver());
161 +
162 +const tokenSource = { provider: SecretProviderId.make("homelab"), reference: "simlock#token" };
163
164 const makeHost = (
165 pool: Effect.Success<ReturnType<typeof fakePool>>,
@@ -296,7 +310,8 @@ describe("Simlock device host", () => {
310 });
311
312 expect(
299 - SimlockDeviceHost.resolveSimlockToken(
313 + yield* SimlockDeviceHost.resolveSimlockToken(
314 + yield* SecretResolver.SecretResolver,
315 "https://elsewhere.example:4700",
316 config({ agentToken: "saved-token" }),
317 {},
@@ -317,6 +332,41 @@ describe("Simlock device host", () => {
332 }).pipe(Effect.scoped, Effect.provide(layer)),
333 );
334
335 + it.effect("reads its agent token from the secret provider the setting names", () =>
336 + Effect.gen(function* () {
337 + const pool = yield* fakePool();
338 + const scope = yield* Scope.make();
339 + const host = yield* makeHost(pool, config({ agentToken: tokenSource }), scope);
340 + const ready = yield* host.ensureReady(() => Effect.void);
341 + const [iphone] = (yield* ready.devices.list).devices;
342 + const leaseId = yield* ready.devices.boot(iphone!);
343 + expect(yield* ready.devices.agentEndpoint!(leaseId)).toMatchObject({ token: "agent-token" });
344 + yield* Scope.close(scope, Exit.void);
345 + expect(pool.ran("close")).toHaveLength(1);
346 + }).pipe(
347 + Effect.scoped,
348 + Effect.provide(layerWith(makeSecretResolver({ "simlock#token": "agent-token" }))),
349 + ),
350 + );
351 +
352 + it.effect("fails instead of using this machine's token when its secret cannot be read", () =>
353 + Effect.gen(function* () {
354 + const pool = yield* fakePool();
355 + const scope = yield* Scope.make();
356 + const host = yield* makeHost(pool, config({ agentToken: tokenSource }), scope).pipe(
357 + Effect.provideService(HostProcess.Environment, {
358 + AGENT_DEVICE_DAEMON_BASE_URL: `${GATEWAY}/v1/agent-device`,
359 + AGENT_DEVICE_DAEMON_AUTH_TOKEN: "agent-token",
360 + }),
361 + );
362 + const availability = yield* host.platformAvailability("ios");
363 + expect(availability.available).toBe(false);
364 + expect(availability.reason).toContain('secret provider "homelab"');
365 + expect(pool.requests).toEqual([]);
366 + yield* Scope.close(scope, Exit.void);
367 + }).pipe(Effect.scoped, Effect.provide(layer)),
368 + );
369 +
370 it.effect("lists a platform again as soon as its workers return", () =>
371 Effect.gen(function* () {
372 const pool = yield* fakePool();
apps/server/src/device/SimlockDeviceHost.ts
+38 -14
@@ -11,6 +11,7 @@ import {
11 DeviceOperationError,
12 type DevicePlatform,
13 type DevicePlatformAvailability,
14 + type SettingsSecretValue,
15 type SimlockDeviceHostConfig,
16 } from "@t3tools/contracts";
17 import * as Cause from "effect/Cause";
@@ -28,8 +29,10 @@ import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } fr
29 import * as HostProcess from "@t3tools/shared/HostProcess";
30 import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
31
32 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
33 import * as ServerConfig from "../config.ts";
34 import * as ProcessRunner from "../processRunner.ts";
35 +import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
36 import { writeAgentDeviceConfig } from "./AgentDeviceTarget.ts";
37 import * as DeviceHost from "./DeviceHost.ts";
38
@@ -75,6 +78,8 @@ interface Lease {
78 readonly dir: string;
79 readonly configPath: string;
80 readonly installDirectory: string;
81 + /** The token the lease was opened with; ending it must not depend on reading the secret again. */
82 + readonly token: string;
83 }
84
85 const catalogId = (platform: DevicePlatform, model: string) => `simlock:${platform}:${model}`;
@@ -108,20 +113,25 @@ export const machineSimlockToken = (environment: NodeJS.ProcessEnv) => {
113
114 /**
115 * The saved token, else this machine's agent-device token; each only for the gateway it belongs to,
111 - * so a URL being edited never receives either.
116 + * so a URL being edited never receives either. A saved secret reference that cannot be read fails
117 + * instead of falling back to this machine's token.
118 */
113 -export const resolveSimlockToken = (
119 +export const resolveSimlockToken = Effect.fn("SimlockDeviceHost.resolveToken")(function* (
120 + secrets: SecretResolver.SecretResolver["Service"],
121 gatewayUrl: string,
115 - saved: { readonly gatewayUrl: string; readonly agentToken: string } | undefined,
122 + saved: { readonly gatewayUrl: string; readonly agentToken: SettingsSecretValue } | undefined,
123 environment: NodeJS.ProcessEnv,
117 -) => {
124 +) {
125 if (saved?.agentToken && sameOrigin(saved.gatewayUrl, gatewayUrl))
119 - return { agentToken: saved.agentToken, source: "settings" as const };
126 + return {
127 + agentToken: yield* requireSettingsSecret(secrets, saved.agentToken),
128 + source: "settings" as const,
129 + };
130 const machine = machineSimlockToken(environment);
131 return machine && sameOrigin(machine.gatewayUrl, gatewayUrl)
132 ? { agentToken: machine.agentToken, source: "env" as const }
133 : null;
124 -};
134 +});
135
136 /** What went wrong talking to a gateway, without the gateway's own text. */
137 export const describeGatewayFailure = (cause: unknown, gatewayUrl: string, tokenOwner: string) => {
@@ -181,9 +191,9 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
191 const server = yield* ServerConfig.ServerConfig;
192 const services = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
193 const environment = yield* HostProcess.Environment;
194 + const secrets = yield* SecretResolver.SecretResolver;
195 const hostId = config.id;
196 const gateway = config.gatewayUrl.replace(/\/$/, "");
186 - const agentToken = resolveSimlockToken(config.gatewayUrl, config, environment)?.agentToken ?? "";
197 const agentDeviceUrl = `${gateway}/v1/agent-device`;
198 const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
199 const leases = new Map<string, Lease>();
@@ -209,7 +219,18 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
219 ...(cause === undefined ? {} : { cause }),
220 });
221
222 + // Read on each use, so a rotated or unlocked secret applies without rebuilding the host.
223 + const currentToken = resolveSimlockToken(secrets, config.gatewayUrl, config, environment).pipe(
224 + Effect.mapError((error) => unavailable(error.message, error)),
225 + Effect.flatMap((token) =>
226 + token
227 + ? Effect.succeed(token.agentToken)
228 + : Effect.fail(unavailable(`Add an agent token for ${config.label} in Settings.`)),
229 + ),
230 + );
231 +
232 const request = (
233 + agentToken: string,
234 method: "GET" | "POST" | "DELETE",
235 route: string,
236 body?: Readonly<Record<string, unknown>>,
@@ -284,10 +305,8 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
305 const fetchCatalog = Effect.gen(function* () {
306 const now = yield* Clock.currentTimeMillis;
307 if (catalog && now - catalog.at < CATALOG_TTL_MS) return catalog.devices;
287 - if (!agentToken) {
288 - return yield* unavailable(`Add an agent token for ${config.label} in Settings.`);
289 - }
290 - const decoded = yield* request("GET", "/v1/catalog").pipe(
308 + const agentToken = yield* currentToken;
309 + const decoded = yield* request(agentToken, "GET", "/v1/catalog").pipe(
310 Effect.flatMap(decodeCatalog),
311 Effect.mapError((cause) =>
312 unavailable(describeGatewayFailure(cause, gateway, config.label), cause),
@@ -357,7 +376,9 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
376 /** Ends the lease through its session, or over HTTP when the session is gone. */
377 const release = Effect.fn("SimlockDeviceHost.release")(function* (lease: Lease) {
378 yield* agentDevice(lease, ["close"]).pipe(
360 - Effect.catch(() => request("DELETE", `/v1/leases/${encodeURIComponent(lease.leaseId)}`)),
379 + Effect.catch(() =>
380 + request(lease.token, "DELETE", `/v1/leases/${encodeURIComponent(lease.leaseId)}`),
381 + ),
382 Effect.tapError((cause) =>
383 Effect.logWarning("Could not release Simlock lease", { leaseId: lease.leaseId, cause }),
384 ),
@@ -376,6 +397,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
397 yield* Effect.sleep(Duration.millis(Math.min(left, Duration.toMillis(RENEW_INTERVAL))));
398 if ((yield* Clock.currentTimeMillis) >= deadline) break;
399 const renewed = yield* request(
400 + lease.token,
401 "POST",
402 `/v1/leases/${encodeURIComponent(lease.leaseId)}/renew`,
403 { ttlMs: LEASE_TTL_MS },
@@ -429,6 +451,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
451 const session = `t3-${suffix}`;
452 const dir = path.join(hostDir, suffix);
453 const configPath = path.join(dir, "agent-device.json");
454 + const agentToken = yield* currentToken;
455 yield* writeAgentDeviceConfig(configPath, {
456 baseUrl: agentDeviceUrl,
457 token: agentToken,
@@ -465,6 +488,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
488 dir,
489 configPath,
490 installDirectory,
491 + token: agentToken,
492 };
493 if (stops !== stopsAtOpen)
494 return yield* unavailable("Device support stopped while the device was opening.");
@@ -557,7 +581,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
581 onSome: (lease) =>
582 Effect.succeed({
583 baseUrl: agentDeviceUrl,
560 - token: agentToken,
584 + token: lease.token,
585 agentDeviceId: null,
586 session: lease.session,
587 stateDir: lease.dir,
@@ -588,7 +612,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
612 if (!lease) return null;
613 return {
614 url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
591 - headers: { authorization: `Bearer ${agentToken}` },
615 + headers: { authorization: `Bearer ${lease.token}` },
616 protocols: [],
617 };
618 });
apps/server/src/provider/Drivers/AntigravityDriver.ts
+8 -2
@@ -1,5 +1,10 @@
1 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
2 -import { AntigravitySettings, ProviderDriverKind, ProviderSetupError } from "@t3tools/contracts";
2 +import {
3 + AntigravitySettings,
4 + ProviderDriverKind,
5 + ProviderSetupError,
6 + settingsSecretLiteral,
7 +} from "@t3tools/contracts";
8 import * as HostProcess from "@t3tools/shared/HostProcess";
9 import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
10 import {
@@ -121,7 +126,8 @@ export const AntigravityDriver: ProviderDriver<
126 const settings = { ...config, enabled } satisfies AntigravitySettings;
127 const auth: AntigravityAuthConfig = {
128 authMethod: settings.authMethod,
124 - apiKey: settings.apiKey,
129 + // The instance registry has already read a referenced key from its secret provider.
130 + apiKey: settingsSecretLiteral(settings.apiKey),
131 gcpProject: settings.gcpProject,
132 gcpLocation: settings.gcpLocation,
133 };
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+24 -2
@@ -8,6 +8,7 @@ import { vi } from "vite-plus/test";
8 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
9 import * as NodeServices from "@effect/platform-node/NodeServices";
10 import {
11 + AntigravitySettings,
12 EnvironmentId,
13 type ClaudeSettings,
14 type CodexSettings,
@@ -20,6 +21,7 @@ import {
21 type SecretReference,
22 } from "@t3tools/contracts";
23 import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
24 +import { OpenCodeSettings } from "@t3tools/provider-opencode/settings";
25 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
26 import * as HostProcess from "@t3tools/shared/HostProcess";
27 import * as DateTime from "effect/DateTime";
@@ -896,8 +898,12 @@ describe("ProviderInstanceRegistry secret environment", () => {
898 }).pipe(Effect.scoped);
899 });
900
899 - it.effect("marks an instance unavailable and names the variable it could not read", () => {
900 - const fixture = setup({});
901 + // An empty secret must not let a driver fall back to a credential the server inherited.
902 + it.effect.each([
903 + ["missing", {}],
904 + ["empty", { [secret.reference]: " " }],
905 + ] as const)("marks an instance unavailable when its secret is %s", ([, initial]) => {
906 + const fixture = setup(initial);
907 return Effect.gen(function* () {
908 const { registry, mutator } = yield* fixture.make;
909 const readsAtStartup = fixture.reads.length;
@@ -970,6 +976,22 @@ describe("ProviderInstanceRegistry secret environment", () => {
976 }).pipe(Effect.scoped);
977 });
978
979 + it.effect.each([
980 + { name: "Antigravity apiKey", schema: AntigravitySettings, field: "apiKey" },
981 + { name: "OpenCode serverPassword", schema: OpenCodeSettings, field: "serverPassword" },
982 + ])("hands the driver the secret its $name names", ({ schema, field }) => {
983 + const reference: SecretReference = { ...secret, reference: "op://Private/Provider/key" };
984 + const fixture = setup(
985 + { [secret.reference]: "sk-live", [reference.reference]: "provider-live" },
986 + schema,
987 + { enabled: true, [field]: reference },
988 + );
989 + return Effect.gen(function* () {
990 + yield* fixture.make;
991 + expect(fixture.configs).toEqual([expect.objectContaining({ [field]: "provider-live" })]);
992 + }).pipe(Effect.scoped);
993 + });
994 +
995 it.effect("keeps a working instance live when a reload cannot read its secret", () => {
996 const fixture = setup({ [secret.reference]: "sk-live" });
997 return Effect.gen(function* () {
apps/server/src/provider/ProviderInstanceRegistry.ts
+7 -2
@@ -106,9 +106,14 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr
106 references.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(references);
107 const unreadable: Array<string> = [];
108 let index = 0;
109 + // An empty secret reads as unreadable, so a driver cannot fall back to an inherited credential.
110 + const next = () => {
111 + const secret = values[index++];
112 + return secret === undefined || secret.trim() === "" ? undefined : secret;
113 + };
114 const environment: ResolvedProviderInstanceEnvironment = variables.flatMap((variable) => {
115 if (typeof variable.value === "string") return [{ ...variable, value: variable.value }];
111 - const secret = values[index++];
116 + const secret = next();
117 if (secret === undefined) {
118 unreadable.push(variable.name);
119 return [];
@@ -116,7 +121,7 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr
121 return [{ ...variable, value: secret, sensitive: true }];
122 });
123 const config = configFields.flatMap(({ field, key }) => {
119 - const secret = values[index++];
124 + const secret = next();
125 if (secret !== undefined) return [{ field, key, value: secret }];
126 unreadable.push(field);
127 return [];
apps/server/src/serverSettings.test.ts
+46
@@ -1626,6 +1626,20 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1626 provider: SecretProviderId.make("personal"),
1627 reference: "op://Private/Expo/token",
1628 };
1629 + const simlockReference = {
1630 + provider: SecretProviderId.make("personal"),
1631 + reference: "op://Private/Simlock/token",
1632 + };
1633 + const antigravityReference = {
1634 + provider: SecretProviderId.make("personal"),
1635 + reference: "op://Private/Gemini/key",
1636 + };
1637 + const openCodeReference = {
1638 + provider: SecretProviderId.make("personal"),
1639 + reference: "op://Private/OpenCode/password",
1640 + };
1641 + const antigravity = ProviderInstanceId.make("antigravity");
1642 + const openCode = ProviderInstanceId.make("opencode");
1643 const hub = UsageLimitSourceId.make("hub");
1644 const withUsage = yield* serverSettings.updateSettings({
1645 usageLimitSources: {
@@ -1647,6 +1661,27 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1661 maxConcurrentSessions: 2,
1662 },
1663 ],
1664 + simlockDeviceHosts: [
1665 + {
1666 + kind: "simlock",
1667 + id: "pool",
1668 + label: "Device pool",
1669 + gatewayUrl: "https://simlock.test:4700",
1670 + agentToken: simlockReference,
1671 + maxLeases: 2,
1672 + maxLeaseMinutes: 60,
1673 + },
1674 + ],
1675 + providerInstances: {
1676 + [antigravity]: {
1677 + driver: ProviderDriverKind.make("antigravity"),
1678 + config: { authMethod: "gemini-api-key", apiKey: antigravityReference },
1679 + },
1680 + [openCode]: {
1681 + driver: ProviderDriverKind.make("opencode"),
1682 + config: { serverUrl: "http://127.0.0.1:4096", serverPassword: openCodeReference },
1683 + },
1684 + },
1685 });
1686 const legacy = ServerSettingsModule.redactServerSettingsForClient(withUsage, {
1687 secretReferences: false,
@@ -1655,10 +1690,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1690 assert.equal(legacy.sourceControlHosts.bitbucket?.accessToken, SECRET_REDACTED);
1691 assert.equal(legacy.usageLimitSources[hub]?.managementKey, SECRET_REDACTED);
1692 assert.equal(legacy.easDeviceHosts[0]?.accessToken, SECRET_REDACTED);
1693 + assert.equal(legacy.simlockDeviceHosts[0]?.agentToken, SECRET_REDACTED);
1694 + const configOf = (settings: ServerSettings, id: ProviderInstanceId) =>
1695 + settings.providerInstances[id]?.config as Record<string, unknown> | undefined;
1696 + assert.equal(configOf(legacy, antigravity)?.apiKey, SECRET_REDACTED);
1697 + assert.equal(configOf(legacy, openCode)?.serverPassword, SECRET_REDACTED);
1698 const echoed = yield* serverSettings.updateSettings({
1699 sourceControlHosts: legacy.sourceControlHosts,
1700 usageLimitSources: legacy.usageLimitSources,
1701 easDeviceHosts: legacy.easDeviceHosts,
1702 + simlockDeviceHosts: legacy.simlockDeviceHosts,
1703 + providerInstances: legacy.providerInstances,
1704 });
1705 assert.deepEqual(echoed.sourceControlHosts.bitbucket?.accessToken, reference);
1706 assert.deepEqual(echoed.sourceControlHosts.github?.tokens, {
@@ -1667,6 +1709,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1709 });
1710 assert.deepEqual(echoed.usageLimitSources[hub]?.managementKey, usageReference);
1711 assert.deepEqual(echoed.easDeviceHosts[0]?.accessToken, easReference);
1712 + assert.deepEqual(echoed.simlockDeviceHosts[0]?.agentToken, simlockReference);
1713 + assert.deepEqual(configOf(echoed, antigravity)?.apiKey, antigravityReference);
1714 + assert.deepEqual(configOf(echoed, openCode)?.serverPassword, openCodeReference);
1715 assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1716 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1717 );
@@ -1676,6 +1721,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1721 // Shipped clients decode these as strings. Each must be covered by the older-client case above.
1722 assert.deepEqual(strictSecretReferencePaths(ServerSettings.ast), [
1723 "easDeviceHosts.[].accessToken",
1724 + "simlockDeviceHosts.[].agentToken",
1725 "usageLimitSources.*.managementKey",
1726 ]);
1727 }),
apps/server/src/sourceControl/sourceControlHostSecrets.test.ts
+19 -1
@@ -150,8 +150,20 @@ it.effect("reads a collected reference again once it is invalidated", () =>
150 accessToken: source("expo#token"),
151 },
152 ];
153 + const simlockDeviceHosts = [
154 + {
155 + kind: "simlock" as const,
156 + id: DeviceHostId.make("pool"),
157 + label: "Pool",
158 + gatewayUrl: "https://simlock.test:4700",
159 + agentToken: source("simlock#token"),
160 + maxLeases: 2,
161 + maxLeaseMinutes: 60,
162 + },
163 + ];
164 cache.set("cliproxy#key", "stale");
165 cache.set("expo#token", "stale");
166 + cache.set("simlock#token", "stale");
167 assert.deepEqual((yield* read()).bitbucket, {
168 email: "me@example.test",
169 accessToken: "stale",
@@ -159,10 +171,16 @@ it.effect("reads a collected reference again once it is invalidated", () =>
171 current = "rotated";
172 yield* invalidateSettingsSecrets(
173 resolver,
162 - Effect.succeed({ sourceControlHosts: hosts, usageLimitSources, easDeviceHosts }),
174 + Effect.succeed({
175 + sourceControlHosts: hosts,
176 + usageLimitSources,
177 + easDeviceHosts,
178 + simlockDeviceHosts,
179 + }),
180 );
181 assert.isFalse(cache.has("cliproxy#key"));
182 assert.isFalse(cache.has("expo#token"));
183 + assert.isFalse(cache.has("simlock#token"));
184 assert.deepEqual((yield* read()).bitbucket, {
185 email: "me@example.test",
186 accessToken: "rotated",
apps/server/src/sourceControl/sourceControlHostSecrets.ts
+11 -5
@@ -104,16 +104,22 @@ const collectUsageLimitSecretReferences = (
104 isSecretReference(managementKey) ? [managementKey] : [],
105 );
106
107 -const collectEasSecretReferences = (
108 - hosts: ServerSettings["easDeviceHosts"],
107 +const collectDeviceHostSecretReferences = (
108 + settings: Pick<ServerSettings, "easDeviceHosts" | "simlockDeviceHosts">,
109 ): ReadonlyArray<SecretReference> =>
110 - hosts.flatMap(({ accessToken }) => (isSecretReference(accessToken) ? [accessToken] : []));
110 + [
111 + ...settings.easDeviceHosts.map(({ accessToken }) => accessToken),
112 + ...settings.simlockDeviceHosts.map(({ agentToken }) => agentToken),
113 + ].filter(isSecretReference);
114
115 /** Settings that cannot be read clear every cached secret, so a refresh never keeps a stale one. */
116 export const invalidateSettingsSecrets = Effect.fn("SettingsSecrets.invalidate")(function* <E>(
117 resolver: SecretResolver.SecretResolver["Service"],
118 settings: Effect.Effect<
116 - Pick<ServerSettings, "sourceControlHosts" | "usageLimitSources" | "easDeviceHosts">,
119 + Pick<
120 + ServerSettings,
121 + "sourceControlHosts" | "usageLimitSources" | "easDeviceHosts" | "simlockDeviceHosts"
122 + >,
123 E
124 >,
125 ) {
@@ -121,7 +127,7 @@ export const invalidateSettingsSecrets = Effect.fn("SettingsSecrets.invalidate")
127 Effect.map((current) => [
128 ...collectSourceControlHostSecretReferences(current.sourceControlHosts),
129 ...collectUsageLimitSecretReferences(current.usageLimitSources),
124 - ...collectEasSecretReferences(current.easDeviceHosts),
130 + ...collectDeviceHostSecretReferences(current),
131 ]),
132 Effect.orElseSucceed(() => undefined),
133 );
apps/web/src/components/settings/SimlockDeviceHostEditor.tsx
+69 -15
@@ -1,6 +1,11 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import { useId, useState, type ReactNode } from "react";
3 -import type { EnvironmentId, SimlockDeviceHostConfig } from "@t3tools/contracts";
3 +import {
4 + isSecretReference,
5 + type EnvironmentId,
6 + type SettingsSecretValue,
7 + type SimlockDeviceHostConfig,
8 +} from "@t3tools/contracts";
9 import * as Cause from "effect/Cause";
10 import * as Option from "effect/Option";
11 import { AsyncResult, Atom } from "effect/reactivity";
@@ -21,7 +26,7 @@ import {
26 } from "../ui/dialog";
27 import { Input } from "../ui/input";
28 import { Spinner } from "../ui/spinner";
24 -import { SecretInput } from "./SecretInput";
29 +import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
30 import {
31 planSimlockDeviceHostSave,
32 simlockDeviceHostProblem,
@@ -67,8 +72,9 @@ export function SimlockDeviceHostEditor(props: {
72 .map((result) => Option.getOrUndefined(AsyncResult.value(result))?.gatewayUrl)
73 .find(Boolean);
74 const gatewayUrl = urlEdited || draft.gatewayUrl ? draft.gatewayUrl : (detectedUrl ?? "");
70 - const savedToken = (environment: SimlockHostEnvironment) =>
71 - environment.hosts.some((host) => host.id === props.host.id && host.agentToken !== "");
75 + const savedValue = (environment: SimlockHostEnvironment) =>
76 + environment.hosts.find((host) => host.id === props.host.id)?.agentToken ?? "";
77 + const savedToken = (environment: SimlockHostEnvironment) => savedValue(environment) !== "";
78 const [tokens, setTokens] = useState<ReadonlyMap<EnvironmentId, SimlockTokenEntry>>(
79 () =>
80 new Map(
@@ -84,8 +90,15 @@ export function SimlockDeviceHostEditor(props: {
90 gatewayUrl: gatewayUrl.trim(),
91 };
92 const checkUrl = simlockDeviceHostProblem(next) === null ? next.gatewayUrl : null;
93 + // Environments whose token field holds a secret reference that cannot be saved yet.
94 + const [invalidTokens, setInvalidTokens] = useState<ReadonlySet<EnvironmentId>>(new Set());
95 const plan = planSimlockDeviceHostSave(props.environments, next, tokens);
88 - const problem = "problem" in plan ? plan.problem : null;
96 + const problem =
97 + "problem" in plan
98 + ? plan.problem
99 + : invalidTokens.size > 0
100 + ? "Enter a valid secret reference."
101 + : null;
102 const several = props.environments.length > 1;
103
104 const limit = (
@@ -171,11 +184,19 @@ export function SimlockDeviceHostEditor(props: {
184 gatewayUrl={checkUrl}
185 label={several ? `Agent token · ${environment.label}` : "Agent token"}
186 token={tokens.get(environment.environmentId) ?? { kind: "cleared" }}
174 - hasSaved={savedToken(environment)}
187 + saved={savedValue(environment)}
188 busy={props.busy}
189 onChange={(token) =>
190 setTokens((current) => new Map(current).set(environment.environmentId, token))
191 }
192 + onValidityChange={(valid) =>
193 + setInvalidTokens((current) => {
194 + const nextInvalid = new Set(current);
195 + if (valid) nextInvalid.delete(environment.environmentId);
196 + else nextInvalid.add(environment.environmentId);
197 + return nextInvalid;
198 + })
199 + }
200 />
201 ))}
202 <p className="text-xs text-muted-foreground">
@@ -220,12 +241,23 @@ function SimlockTokenField(props: {
241 gatewayUrl: string | null;
242 label: ReactNode;
243 token: SimlockTokenEntry;
223 - hasSaved: boolean;
244 + /** This environment's saved token: redacted when a literal, shown when a secret reference. */
245 + saved: SettingsSecretValue;
246 busy: boolean;
247 onChange: (token: SimlockTokenEntry) => void;
248 + onValidityChange: (valid: boolean) => void;
249 }) {
250 const id = useId();
228 - const entered = props.token.kind === "new" ? props.token.value.trim() : "";
251 + const sources = useSecretSources(props.environmentId);
252 + const [inputKey, setInputKey] = useState(0);
253 + // Emptying the field or leaving a reference returns to a saved literal, never to a saved reference.
254 + const savedLiteral = typeof props.saved === "string" && props.saved !== "";
255 + const entered =
256 + props.token.kind !== "new"
257 + ? ""
258 + : typeof props.token.value === "string"
259 + ? props.token.value.trim()
260 + : props.token.value;
261 // A cleared field asks about the machine's own token, which a blank one falls back to.
262 const check = useAtomValue(
263 props.gatewayUrl === null
@@ -265,20 +297,38 @@ function SimlockTokenField(props: {
297 {props.label}
298 </label>
299 <div className="flex items-center gap-2">
268 - <SecretInput
300 + <SecretSourceInput
301 + key={inputKey}
302 id={id}
303 + aria-label="Agent token"
304 className="min-w-0 flex-1"
271 - configured={props.token.kind === "saved"}
272 - value={props.token.kind === "new" ? props.token.value : ""}
305 + configured={props.token.kind === "saved" && typeof props.saved === "string"}
306 + value={
307 + props.token.kind === "new"
308 + ? props.token.value
309 + : props.token.kind === "saved" && isSecretReference(props.saved)
310 + ? props.saved
311 + : ""
312 + }
313 + sources={sources}
314 + onValidityChange={props.onValidityChange}
315 + onSecretChange={(secret) =>
316 + props.onChange(
317 + secret
318 + ? { kind: "new", value: secret }
319 + : savedLiteral
320 + ? { kind: "saved" }
321 + : { kind: "cleared" },
322 + )
323 + }
324 disabled={props.busy}
325 onChange={(event) => {
326 const value = event.target.value;
276 - // Emptying the field is not clearing the saved token; the Clear
277 - // button is, so a saved token comes back here.
327 + // Emptying the field is not clearing the saved token; the Clear button is.
328 props.onChange(
329 value
330 ? { kind: "new", value }
281 - : props.hasSaved
331 + : savedLiteral
332 ? { kind: "saved" }
333 : { kind: "cleared" },
334 );
@@ -291,7 +341,11 @@ function SimlockTokenField(props: {
341 variant="ghost-destructive"
342 aria-label="Clear agent token"
343 disabled={props.busy}
294 - onClick={() => props.onChange({ kind: "cleared" })}
344 + onClick={() => {
345 + props.onChange({ kind: "cleared" });
346 + props.onValidityChange(true);
347 + setInputKey((key) => key + 1);
348 + }}
349 >
350 <XIcon className="size-3.5" />
351 </Button>
apps/web/src/components/settings/simlockDeviceHostsSettings.logic.test.ts
+11 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import type { EnvironmentId } from "@t3tools/contracts";
3 +import { SecretProviderId, type EnvironmentId } from "@t3tools/contracts";
4
5 import {
6 newSimlockDeviceHost,
@@ -68,5 +68,15 @@ describe("Simlock device host settings", () => {
68 { environmentId: cups, hosts: [{ ...draft, agentToken: "cups-token" }] },
69 ],
70 });
71 + const reference = { provider: SecretProviderId.make("homelab"), reference: "simlock#token" };
72 + expect(
73 + planSimlockDeviceHostSave(
74 + environments,
75 + draft,
76 + new Map([[cups, { kind: "new", value: reference }]]),
77 + ),
78 + ).toMatchObject({
79 + patches: [{}, { environmentId: cups, hosts: [{ ...draft, agentToken: reference }] }],
80 + });
81 });
82 });
apps/web/src/components/settings/simlockDeviceHostsSettings.logic.ts
+10 -3
@@ -1,6 +1,7 @@
1 import {
2 SimlockDeviceHostConfig,
3 type EnvironmentId,
4 + type SettingsSecretValue,
5 type SimlockDeviceHostConfig as SimlockDeviceHostConfigType,
6 } from "@t3tools/contracts";
7 import * as Option from "effect/Option";
@@ -54,10 +55,10 @@ export interface SimlockHostEnvironment {
55 readonly hosts: ReadonlyArray<SimlockDeviceHostConfigType>;
56 }
57
57 -/** A token field: the environment's saved token, a replacement, or none. */
58 +/** A token field: the environment's saved token, a replacement or secret reference, or none. */
59 export type SimlockTokenEntry =
60 | { kind: "saved" }
60 - | { kind: "new"; value: string }
61 + | { kind: "new"; value: SettingsSecretValue }
62 | { kind: "cleared" };
63
64 /**
@@ -83,7 +84,13 @@ export function planSimlockDeviceHostSave(
84 const saved = environment.hosts.find((host) => host.id === draft.id)?.agentToken ?? "";
85 const entry = tokens.get(environment.environmentId) ?? { kind: "cleared" };
86 const agentToken =
86 - entry.kind === "saved" ? saved : entry.kind === "new" ? entry.value.trim() : "";
87 + entry.kind === "saved"
88 + ? saved
89 + : entry.kind !== "new"
90 + ? ""
91 + : typeof entry.value === "string"
92 + ? entry.value.trim()
93 + : entry.value;
94 patches.push({
95 environmentId: environment.environmentId,
96 hosts: updateSimlockDeviceHosts(environment.hosts, { ...draft, agentToken }, false),
packages/contracts/src/device.ts
+6 -3
@@ -79,8 +79,11 @@ export const SimlockDeviceHostConfig = Schema.Struct({
79 label: TrimmedNonEmptyString,
80 /** The gateway's origin, such as https://gateway.example.ts.net:4700. */
81 gatewayUrl: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/[^\s/]+\/?$/)),
82 - /** Leases, drives, watches, and takes input on its own leases. Kept in the secret store. */
83 - agentToken: TrimmedString.pipe(
82 + /**
83 + * Leases, drives, watches, and takes input on its own leases. Kept in the secret store, or the
84 + * secret provider to read it from.
85 + */
86 + agentToken: SettingsSecretValue.pipe(
87 Schema.withDecodingDefaultKey(Effect.succeed("")),
88 Schema.annotateKey({ settingsSecret: true }),
89 ),
@@ -133,7 +136,7 @@ export const DeviceSimlockIdentityInput = Schema.Struct({
136 gatewayUrl: Schema.optional(TrimmedString),
137 /** A saved Simlock host whose stored token is checked when no new token is given. */
138 hostId: Schema.optional(DeviceHostId),
136 - agentToken: Schema.optional(TrimmedString),
139 + agentToken: Schema.optional(SettingsSecretValue),
140 });
141 export type DeviceSimlockIdentityInput = typeof DeviceSimlockIdentityInput.Type;
142
packages/contracts/src/settings.ts
+1 -1
@@ -808,7 +808,7 @@ export const AntigravitySettings = makeProviderSettingsSchema(
808 },
809 }),
810 ),
811 - apiKey: TrimmedString.pipe(
811 + apiKey: SettingsSecretValue.pipe(
812 secretSetting,
813 Schema.withDecodingDefault(Effect.succeed("")),
814 Schema.annotateKey({
packages/provider-opencode/src/server/adapter.ts
+3 -2
@@ -35,6 +35,7 @@ import {
35 type ProviderSessionId,
36 type RuntimeRequestId,
37 type ThreadId,
38 + settingsSecretLiteral,
39 } from "@t3tools/contracts";
40 import { OpenCodeSettings } from "../settings.ts";
41 import * as Cause from "effect/Cause";
@@ -947,8 +948,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
948 binaryPath: options.settings.binaryPath,
949 directory: cwd,
950 serverUrl: options.settings.serverUrl,
950 - ...(options.settings.serverPassword
951 - ? { serverPassword: options.settings.serverPassword }
951 + ...(settingsSecretLiteral(options.settings.serverPassword)
952 + ? { serverPassword: settingsSecretLiteral(options.settings.serverPassword) }
953 : {}),
954 environment: options.environment,
955 });
packages/provider-opencode/src/server/driver.ts
+3 -1
@@ -1,4 +1,4 @@
1 -import { ProviderDriverKind } from "@t3tools/contracts";
1 +import { ProviderDriverKind, settingsSecretLiteral } from "@t3tools/contracts";
2 import { OpenCodeSettings } from "../settings.ts";
3 import * as Digest from "effect/crypto/Digest";
4 import * as SecureRandom from "effect/crypto/SecureRandom";
@@ -215,6 +215,8 @@ export const OpenCodeDriver: ProviderDriver<
215 ...config,
216 enabled,
217 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
218 + // The instance registry has already read a referenced password from its secret provider.
219 + serverPassword: settingsSecretLiteral(config.serverPassword),
220 } satisfies OpenCodeSettings;
221 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
222 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
packages/provider-opencode/src/server/status.test.ts
+7 -3
@@ -15,6 +15,7 @@ import * as Tracer from "effect/Tracer";
15 import * as HttpClient from "effect/http/HttpClient";
16 import * as HttpClientResponse from "effect/http/HttpClientResponse";
17 import { beforeEach } from "vite-plus/test";
18 +import { settingsSecretLiteral } from "@t3tools/contracts";
19
20 import { OpenCodeSettings } from "../settings.ts";
21 import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
@@ -481,8 +482,9 @@ const layerTest = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntime
482 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
483 );
484
484 -const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>
485 - decodeOpenCodeSettings({
485 +// As the instance registry hands them to the driver: a referenced password is already read.
486 +const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>) => {
487 + const settings = decodeOpenCodeSettings({
488 enabled: true,
489 binaryPath: "opencode",
490 serverUrl: "",
@@ -490,9 +492,11 @@ const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSe
492 customModels: [],
493 ...overrides,
494 });
495 + return { ...settings, serverPassword: settingsSecretLiteral(settings.serverPassword) };
496 +};
497
498 const checkProvider = Effect.fn("checkProvider")(function* (
495 - settings: OpenCodeSettings,
499 + settings: ReturnType<typeof makeOpenCodeSettings>,
500 cwd = process.cwd(),
501 environment?: NodeJS.ProcessEnv,
502 server = replayOpenCodeServer(OPENCODE_1_RESPONSES, settings.serverPassword),
packages/provider-opencode/src/server/status.ts
+3 -2
@@ -3,6 +3,7 @@ import {
3 type ServerProviderModel,
4 type ServerProviderSkill,
5 type ServerProviderSlashCommand,
6 + settingsSecretLiteral,
7 } from "@t3tools/contracts";
8 import type { OpenCodeSettings } from "../settings.ts";
9 import * as Cause from "effect/Cause";
@@ -801,8 +802,8 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
802 binaryPath: openCodeSettings.binaryPath,
803 directory: cwd,
804 serverUrl: openCodeSettings.serverUrl,
804 - ...(openCodeSettings.serverPassword
805 - ? { serverPassword: openCodeSettings.serverPassword }
805 + ...(settingsSecretLiteral(openCodeSettings.serverPassword)
806 + ? { serverPassword: settingsSecretLiteral(openCodeSettings.serverPassword) }
807 : {}),
808 })
809 .pipe(Effect.flatMap(loadInventory), Effect.scoped)
packages/provider-opencode/src/server/textGeneration.test.ts
+4 -2
@@ -1,4 +1,4 @@
1 -import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
1 +import { ProviderInstanceId, settingsSecretLiteral, TextGenerationError } from "@t3tools/contracts";
2 import { OpenCodeSettings } from "../settings.ts";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { it } from "@effect/vitest";
@@ -227,7 +227,9 @@ function withOpenCodeTextGeneration<A, E, R>(
227 const serverOwner = yield* OpenCodeServerOwner.make({
228 binaryPath: settings.binaryPath,
229 directory: process.cwd(),
230 - ...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
230 + ...(settingsSecretLiteral(settings.serverPassword)
231 + ? { serverPassword: settingsSecretLiteral(settings.serverPassword) }
232 + : {}),
233 ...(environment ? { environment } : {}),
234 });
235 const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe(
packages/provider-opencode/src/server/textGeneration.ts
+3 -3
@@ -1,7 +1,7 @@
1 import * as Effect from "effect/Effect";
2 import * as Schema from "effect/Schema";
3
4 -import { NonNegativeInt, TextGenerationError } from "@t3tools/contracts";
4 +import { NonNegativeInt, settingsSecretLiteral, TextGenerationError } from "@t3tools/contracts";
5 import type { OpenCodeSettings } from "../settings.ts";
6 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
7
@@ -358,8 +358,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
358 binaryPath: openCodeSettings.binaryPath,
359 directory: input.cwd,
360 serverUrl: openCodeSettings.serverUrl,
361 - ...(openCodeSettings.serverPassword
362 - ? { serverPassword: openCodeSettings.serverPassword }
361 + ...(settingsSecretLiteral(openCodeSettings.serverPassword)
362 + ? { serverPassword: settingsSecretLiteral(openCodeSettings.serverPassword) }
363 : {}),
364 })
365 .pipe(Effect.flatMap(runAgainstServer), Effect.scoped)
packages/provider-opencode/src/settings.ts
+2 -1
@@ -4,6 +4,7 @@ import {
4 makeBinaryPathSetting,
5 makeProviderSettingsSchema,
6 secretSetting,
7 + SettingsSecretValue,
8 TrimmedString,
9 } from "@t3tools/contracts";
10 import * as Effect from "effect/Effect";
@@ -36,7 +37,7 @@ export const OpenCodeSettings = makeProviderSettingsSchema(
37 },
38 }),
39 ),
39 - serverPassword: TrimmedString.pipe(
40 + serverPassword: SettingsSecretValue.pipe(
41 secretSetting,
42 Schema.withDecodingDefault(Effect.succeed("")),
43 Schema.annotateKey({