Skip to content

Commit 4a94658

Browse files
feat(settings): Simlock, Antigravity and OpenCode credentials can come from a secret provider (#31652)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 4bfb896 commit 4a94658

21 files changed

Lines changed: 338 additions & 70 deletions

‎apps/server/src/device/DeviceService.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
7070
import * as ProcessRunner from "../processRunner.ts";
7171
import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
7272
import * as SecretResolverLayer from "../secrets/SecretResolver.ts";
73+
import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
7374
import * as DeviceHost from "./DeviceHost.ts";
7475
import * as SshDeviceHost from "./SshDeviceHost.ts";
7576
import * as EasDeviceHost from "./EasDeviceHost.ts";
@@ -1594,8 +1595,11 @@ export const make = Effect.gen(function* () {
15941595
(host) => host.id === input.hostId,
15951596
);
15961597
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);
15991603
if (!token)
16001604
return yield* new DeviceSimlockIdentityError({
16011605
reason: savedHost?.agentToken
@@ -1623,6 +1627,8 @@ export const make = Effect.gen(function* () {
16231627
Effect.catchTags({
16241628
ServerSettingsError: () =>
16251629
Effect.fail(new DeviceSimlockIdentityError({ reason: "Could not read the saved token." })),
1630+
SettingsSecretUnresolvedError: (error) =>
1631+
Effect.fail(new DeviceSimlockIdentityError({ reason: error.message })),
16261632
}),
16271633
Effect.provide(simlockContext),
16281634
);

‎apps/server/src/device/SimlockDeviceHost.test.ts‎

Lines changed: 55 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it } from "@effect/vitest";
22
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";
45
import * as HostProcess from "@t3tools/shared/HostProcess";
56
import * as Effect from "effect/Effect";
67
import * as Fiber from "effect/Fiber";
@@ -143,9 +144,22 @@ const fakePool = (
143144
};
144145
});
145146

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" };
149163

150164
const makeHost = (
151165
pool: Effect.Success<ReturnType<typeof fakePool>>,
@@ -296,7 +310,8 @@ describe("Simlock device host", () => {
296310
});
297311

298312
expect(
299-
SimlockDeviceHost.resolveSimlockToken(
313+
yield* SimlockDeviceHost.resolveSimlockToken(
314+
yield* SecretResolver.SecretResolver,
300315
"https://elsewhere.example:4700",
301316
config({ agentToken: "saved-token" }),
302317
{},
@@ -317,6 +332,41 @@ describe("Simlock device host", () => {
317332
}).pipe(Effect.scoped, Effect.provide(layer)),
318333
);
319334

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+
320370
it.effect("lists a platform again as soon as its workers return", () =>
321371
Effect.gen(function* () {
322372
const pool = yield* fakePool();

‎apps/server/src/device/SimlockDeviceHost.ts‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
DeviceOperationError,
1212
type DevicePlatform,
1313
type DevicePlatformAvailability,
14+
type SettingsSecretValue,
1415
type SimlockDeviceHostConfig,
1516
} from "@t3tools/contracts";
1617
import * as Cause from "effect/Cause";
@@ -28,8 +29,10 @@ import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } fr
2829
import * as HostProcess from "@t3tools/shared/HostProcess";
2930
import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
3031

32+
import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
3133
import * as ServerConfig from "../config.ts";
3234
import * as ProcessRunner from "../processRunner.ts";
35+
import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
3336
import { writeAgentDeviceConfig } from "./AgentDeviceTarget.ts";
3437
import * as DeviceHost from "./DeviceHost.ts";
3538

@@ -75,6 +78,8 @@ interface Lease {
7578
readonly dir: string;
7679
readonly configPath: string;
7780
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;
7883
}
7984

8085
const catalogId = (platform: DevicePlatform, model: string) => `simlock:${platform}:${model}`;
@@ -108,20 +113,25 @@ export const machineSimlockToken = (environment: NodeJS.ProcessEnv) => {
108113

109114
/**
110115
* 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.
112118
*/
113-
export const resolveSimlockToken = (
119+
export const resolveSimlockToken = Effect.fn("SimlockDeviceHost.resolveToken")(function* (
120+
secrets: SecretResolver.SecretResolver["Service"],
114121
gatewayUrl: string,
115-
saved: { readonly gatewayUrl: string; readonly agentToken: string } | undefined,
122+
saved: { readonly gatewayUrl: string; readonly agentToken: SettingsSecretValue } | undefined,
116123
environment: NodeJS.ProcessEnv,
117-
) => {
124+
) {
118125
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+
};
120130
const machine = machineSimlockToken(environment);
121131
return machine && sameOrigin(machine.gatewayUrl, gatewayUrl)
122132
? { agentToken: machine.agentToken, source: "env" as const }
123133
: null;
124-
};
134+
});
125135

126136
/** What went wrong talking to a gateway, without the gateway's own text. */
127137
export const describeGatewayFailure = (cause: unknown, gatewayUrl: string, tokenOwner: string) => {
@@ -181,9 +191,9 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
181191
const server = yield* ServerConfig.ServerConfig;
182192
const services = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
183193
const environment = yield* HostProcess.Environment;
194+
const secrets = yield* SecretResolver.SecretResolver;
184195
const hostId = config.id;
185196
const gateway = config.gatewayUrl.replace(/\/$/, "");
186-
const agentToken = resolveSimlockToken(config.gatewayUrl, config, environment)?.agentToken ?? "";
187197
const agentDeviceUrl = `${gateway}/v1/agent-device`;
188198
const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
189199
const leases = new Map<string, Lease>();
@@ -209,7 +219,18 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
209219
...(cause === undefined ? {} : { cause }),
210220
});
211221

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+
212232
const request = (
233+
agentToken: string,
213234
method: "GET" | "POST" | "DELETE",
214235
route: string,
215236
body?: Readonly<Record<string, unknown>>,
@@ -284,10 +305,8 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
284305
const fetchCatalog = Effect.gen(function* () {
285306
const now = yield* Clock.currentTimeMillis;
286307
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(
291310
Effect.flatMap(decodeCatalog),
292311
Effect.mapError((cause) =>
293312
unavailable(describeGatewayFailure(cause, gateway, config.label), cause),
@@ -357,7 +376,9 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
357376
/** Ends the lease through its session, or over HTTP when the session is gone. */
358377
const release = Effect.fn("SimlockDeviceHost.release")(function* (lease: Lease) {
359378
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+
),
361382
Effect.tapError((cause) =>
362383
Effect.logWarning("Could not release Simlock lease", { leaseId: lease.leaseId, cause }),
363384
),
@@ -376,6 +397,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
376397
yield* Effect.sleep(Duration.millis(Math.min(left, Duration.toMillis(RENEW_INTERVAL))));
377398
if ((yield* Clock.currentTimeMillis) >= deadline) break;
378399
const renewed = yield* request(
400+
lease.token,
379401
"POST",
380402
`/v1/leases/${encodeURIComponent(lease.leaseId)}/renew`,
381403
{ ttlMs: LEASE_TTL_MS },
@@ -429,6 +451,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
429451
const session = `t3-${suffix}`;
430452
const dir = path.join(hostDir, suffix);
431453
const configPath = path.join(dir, "agent-device.json");
454+
const agentToken = yield* currentToken;
432455
yield* writeAgentDeviceConfig(configPath, {
433456
baseUrl: agentDeviceUrl,
434457
token: agentToken,
@@ -465,6 +488,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
465488
dir,
466489
configPath,
467490
installDirectory,
491+
token: agentToken,
468492
};
469493
if (stops !== stopsAtOpen)
470494
return yield* unavailable("Device support stopped while the device was opening.");
@@ -557,7 +581,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
557581
onSome: (lease) =>
558582
Effect.succeed({
559583
baseUrl: agentDeviceUrl,
560-
token: agentToken,
584+
token: lease.token,
561585
agentDeviceId: null,
562586
session: lease.session,
563587
stateDir: lease.dir,
@@ -588,7 +612,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
588612
if (!lease) return null;
589613
return {
590614
url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
591-
headers: { authorization: `Bearer ${agentToken}` },
615+
headers: { authorization: `Bearer ${lease.token}` },
592616
protocols: [],
593617
};
594618
});

‎apps/server/src/provider/Drivers/AntigravityDriver.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
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";
38
import * as HostProcess from "@t3tools/shared/HostProcess";
49
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
510
import {
@@ -121,7 +126,8 @@ export const AntigravityDriver: ProviderDriver<
121126
const settings = { ...config, enabled } satisfies AntigravitySettings;
122127
const auth: AntigravityAuthConfig = {
123128
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),
125131
gcpProject: settings.gcpProject,
126132
gcpLocation: settings.gcpLocation,
127133
};

‎apps/server/src/provider/ProviderInstanceRegistry.test.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { vi } from "vite-plus/test";
88
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
99
import * as NodeServices from "@effect/platform-node/NodeServices";
1010
import {
11+
AntigravitySettings,
1112
EnvironmentId,
1213
type ClaudeSettings,
1314
type CodexSettings,
@@ -20,6 +21,7 @@ import {
2021
type SecretReference,
2122
} from "@t3tools/contracts";
2223
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
24+
import { OpenCodeSettings } from "@t3tools/provider-opencode/settings";
2325
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
2426
import * as HostProcess from "@t3tools/shared/HostProcess";
2527
import * as DateTime from "effect/DateTime";
@@ -896,8 +898,12 @@ describe("ProviderInstanceRegistry secret environment", () => {
896898
}).pipe(Effect.scoped);
897899
});
898900

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);
901907
return Effect.gen(function* () {
902908
const { registry, mutator } = yield* fixture.make;
903909
const readsAtStartup = fixture.reads.length;
@@ -970,6 +976,22 @@ describe("ProviderInstanceRegistry secret environment", () => {
970976
}).pipe(Effect.scoped);
971977
});
972978

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+
973995
it.effect("keeps a working instance live when a reload cannot read its secret", () => {
974996
const fixture = setup({ [secret.reference]: "sk-live" });
975997
return Effect.gen(function* () {

‎apps/server/src/provider/ProviderInstanceRegistry.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,17 +106,22 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr
106106
references.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(references);
107107
const unreadable: Array<string> = [];
108108
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+
};
109114
const environment: ResolvedProviderInstanceEnvironment = variables.flatMap((variable) => {
110115
if (typeof variable.value === "string") return [{ ...variable, value: variable.value }];
111-
const secret = values[index++];
116+
const secret = next();
112117
if (secret === undefined) {
113118
unreadable.push(variable.name);
114119
return [];
115120
}
116121
return [{ ...variable, value: secret, sensitive: true }];
117122
});
118123
const config = configFields.flatMap(({ field, key }) => {
119-
const secret = values[index++];
124+
const secret = next();
120125
if (secret !== undefined) return [{ field, key, value: secret }];
121126
unreadable.push(field);
122127
return [];

0 commit comments

Comments
 (0)