Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - checks the host's default Codex directory without writing to it.
2import * as NodeURL from "node:url";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Stream from "effect/Stream";
5import { ChildProcess, ChildProcessSpawner } from "effect/process";
6import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
7import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
11import * as Clock from "effect/Clock";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18import { HttpClient, HttpClientResponse } from "effect/http";
19import * as ServerConfig from "../config.ts";
20import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
21import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
22import * as CodexInstallation from "./CodexInstallation.ts";
23import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts";
24import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
25import { codexAppServerArgs } from "./codexLaunchArgs.ts";
26
27const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
28const decodeSettings = Schema.decodeSync(CodexSettings);
29const decodeCommand = Schema.decodeUnknownSync(
30 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Array(Schema.String)])),
31);
32it.live.each(
33 (["managed", "local"] as const).flatMap((source) =>
34 (["primary", "additional"] as const).map((account) => ({ source, account })),
35 ),
36)(
37 "$source Codex $account account shares home state without routing owned tokens through ambient CLI overrides",
38 ({ source, account }) =>
39 Effect.gen(function* () {
40 const instanceId = ProviderInstanceId.make(
41 account === "primary" ? "codex" : "codex-personal",
42 );
43 const fs = yield* FileSystem.FileSystem;
44 const path = yield* Path.Path;
45 const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-shared-home-" });
46 yield* fs.writeFileString(path.join(sharedHome, "auth.json"), "native-auth-unchanged");
47 yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "# shared config\n");
48 const data = new Map<string, Uint8Array>();
49 let renewals = 0;
50 const secrets = ServerSecretStore.ServerSecretStore.of({
51 get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))),
52 set: (key, value) =>
53 Effect.sync(() => {
54 data.set(key, value);
55 }),
56 remove: (key) =>
57 Effect.sync(() => {
58 data.delete(key);
59 }),
60 create: () => Effect.die("unused"),
61 getOrCreateRandom: () => Effect.die("unused"),
62 });
63 let leases = 0;
64 const executable = {
65 executablePath:
66 source === "managed" ? "/isolated/tools/codex/0.156.1/bin/codex" : "/user/bin/codex",
67 managedVersionDirectory: source === "managed" ? "/isolated/tools/codex/0.156.1" : null,
68 source,
69 version: "0.156.1",
70 };
71 const layerInstaller = Layer.mock(CodexInstallation.CodexInstallation)({
72 managedDirectory: "/isolated/tools/codex",
73 resolve: () => Effect.succeed(executable),
74 acquire: () =>
75 Effect.gen(function* () {
76 leases++;
77 yield* Effect.addFinalizer(() =>
78 Effect.sync(() => {
79 leases--;
80 }),
81 );
82 return executable;
83 }),
84 });
85 yield* Effect.gen(function* () {
86 const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
87 const json = yield* encodeJson({
88 clientId: "oaiapp_test",
89 accessToken: "dummy-owned-access",
90 refreshToken: "dummy-refresh",
91 expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000,
92 earliestRefreshAt: null,
93 scopes: ["chatgpt.tokens.use.direct"],
94 subject: "test-user",
95 email: null,
96 });
97 yield* store.set(new TextEncoder().encode(json));
98 const ambient = {
99 CODEX_HOME: "/user/.codex",
100 ACCESS_TOKEN: "ambient-bearer",
101 T3CODE_HOME: path.join(sharedHome, "wrong-server-home"),
102 OPENAI_API_KEY: "dummy-global-key",
103 OPENAI_BASE_URL: "https://user-proxy.test",
104 T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy",
105 PATH: process.env.PATH,
106 SystemRoot: process.env.SystemRoot,
107 };
108 const runtime = yield* makeCodexManagedRuntime({
109 instanceId,
110 enabled: true,
111 config: decodeSettings({ setupMode: "managed", homePath: sharedHome }),
112 environment: ambient,
113 });
114 yield* Effect.gen(function* () {
115 const effective = yield* runtime.resolve;
116 assert.strictEqual(leases, 1);
117 assert.strictEqual(effective.config.binaryPath, executable.executablePath);
118 assert.notStrictEqual(effective.config.homePath, ambient.CODEX_HOME);
119 assert.equal(runtime.homeLayout.sharedHomePath, sharedHome);
120 if (account === "primary") {
121 assert.equal(effective.config.homePath, sharedHome);
122 assert.equal(runtime.homeLayout.mode, "direct");
123 } else {
124 assert.include(effective.config.homePath, instanceId);
125 assert.include(effective.config.homePath, "userdata/providers/codex");
126 assert.equal(runtime.homeLayout.mode, "authOverlay");
127 assert.equal(
128 yield* fs.readLink(path.join(effective.config.homePath, "sessions")),
129 path.join(sharedHome, "sessions"),
130 );
131 assert.equal(
132 yield* fs.readLink(path.join(effective.config.homePath, "config.toml")),
133 path.join(sharedHome, "config.toml"),
134 );
135 assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json")));
136 }
137 assert.isUndefined(effective.environment.ACCESS_TOKEN);
138 assert.isUndefined(effective.environment.OPENAI_API_KEY);
139 assert.isUndefined(effective.environment.OPENAI_BASE_URL);
140 assert.isUndefined(effective.environment.T3CODE_CODEX_LAUNCH_ARGS);
141 const args = codexAppServerArgs(effective.config.launchArgs);
142 assert.include(args, 'model_provider="openai_token_sharing"');
143 const provider = args.find((arg) =>
144 arg.startsWith("model_providers.openai_token_sharing="),
145 )!;
146 assert.include(provider, 'base_url="https://api.openai.com/v1"');
147 assert.include(provider, 'model_catalog_url="https://api.openai.com/v1/models"');
148 assert.notInclude(provider, "env_key");
149 assert.include(provider, "refresh_interval_ms=0");
150 // regression: #16132 Codex fetches each token through this helper, so a running
151 // session picks up renewals instead of keeping the token it launched with.
152 if (source === "managed" && account === "primary") {
153 const commandMatch = /auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u.exec(provider);
154 assert.isNotNull(commandMatch);
155 const [command, helperArgs] = decodeCommand(
156 `[${commandMatch![1]},${commandMatch![2]}]`,
157 );
158 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
159 const runHelper = Effect.gen(function* () {
160 const child = yield* spawner.spawn(
161 ChildProcess.make(command, helperArgs, {
162 extendEnv: false,
163 env: effective.environment,
164 }),
165 );
166 const [stdout, stderr, code] = yield* Effect.all(
167 [
168 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
169 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
170 child.exitCode,
171 ],
172 { concurrency: "unbounded" },
173 );
174 return { stdout, stderr, code: Number(code) };
175 }).pipe(Effect.scoped);
176 assert.deepEqual(yield* runHelper, {
177 stdout: "dummy-owned-access",
178 stderr: "",
179 code: 0,
180 });
181 const saved = Option.getOrThrow(yield* runtime.auth.read);
182 const expired = yield* encodeJson({ ...saved, expiresAt: 0 });
183 yield* store.set(new TextEncoder().encode(expired));
184 assert.deepEqual(yield* runHelper, { stdout: "renewed-access", stderr: "", code: 0 });
185 assert.equal(renewals, 1);
186 assert.equal(
187 Option.getOrThrow(yield* runtime.auth.read).refreshToken,
188 "renewed-refresh",
189 );
190 assert.equal((yield* runtime.resolve).revision, effective.revision);
191 const replaced = yield* encodeJson({ ...saved, subject: "replacement-user" });
192 yield* store.set(new TextEncoder().encode(replaced));
193 const refused = yield* runHelper;
194 assert.equal(refused.code, 1);
195 assert.equal(refused.stdout, "");
196 assert.isFalse(yield* fs.exists(ambient.T3CODE_HOME));
197 }
198 assert.include(args, "features.api_key_model_discovery=true");
199 assert.include(args, "features.multi_agent=false");
200 assert.include(args, "features.multi_agent_v2=false");
201 assert.notInclude(effective.config.launchArgs, "model_catalog_json");
202 assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test");
203 assert.include(provider, "supports_websockets=false");
204 assert.include(provider, "requires_openai_auth=false");
205 for (const secret of ["dummy-owned-access", "dummy-refresh", "ambient-bearer"]) {
206 assert.notInclude(effective.config.launchArgs, secret);
207 assert.notInclude(JSON.stringify(effective.environment), secret);
208 }
209 assert.strictEqual(ambient.CODEX_HOME, "/user/.codex");
210 }).pipe(Effect.scoped);
211 assert.strictEqual(leases, 0);
212 yield* runtime.auth.controller.logout(Effect.void);
213 assert.equal(
214 yield* fs.readFileString(path.join(sharedHome, "auth.json")),
215 "native-auth-unchanged",
216 );
217 }).pipe(
218 Effect.provide(CodexManagedTokenBroker.layer),
219 Effect.provideService(HostProcess.Arguments, [
220 process.execPath,
221 NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)),
222 ]),
223 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
224 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
225 getEnvironmentId: Effect.succeed(
226 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
227 ),
228 }),
229 Effect.provide(layerInstaller),
230 Effect.provideService(
231 HttpClient.HttpClient,
232 HttpClient.make((request) =>
233 Effect.sync(() => {
234 assert.isTrue(
235 [
236 "https://auth.openai.com/.well-known/openid-configuration",
237 "https://auth.openai.com/revoke",
238 "https://auth.openai.com/api/accounts/oauth/token",
239 ].includes(request.url),
240 );
241 if (request.url.endsWith("/token")) {
242 renewals++;
243 return HttpClientResponse.fromWeb(
244 request,
245 Response.json({
246 access_token: "renewed-access",
247 refresh_token: "renewed-refresh",
248 token_type: "Bearer",
249 expires_in: 3600,
250 scope: "chatgpt.tokens.use.direct",
251 }),
252 );
253 }
254 return HttpClientResponse.fromWeb(
255 request,
256 request.url.endsWith("/revoke")
257 ? new Response(null, { status: 200 })
258 : Response.json({
259 issuer: "https://auth.openai.com",
260 authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
261 token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
262 jwks_uri: "https://auth.openai.com/jwks",
263 revocation_endpoint: "https://auth.openai.com/revoke",
264 }),
265 );
266 }),
267 ),
268 ),
269 );
270 }).pipe(
271 Effect.scoped,
272 Effect.provide(
273 ServerConfig.layerTest(process.cwd(), {
274 prefix: "t3-managed-runtime-",
275 }).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
276 ),
277 ),
278);