@devries-cameron20 / t3code Mirror · read-only
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 21, 04:45 UTC

main
ts 476 lines 18.4 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6
7 import {
8 DEFAULT_SERVER_SETTINGS,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 } from "@t3tools/contracts";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13
14 import { BUILT_IN_DRIVERS } from "../provider/builtInDrivers.ts";
15 import * as ManagedPolicy from "./ManagedPolicy.ts";
16 import { disallowedDriverReason, providerHostEnvironment } from "./managedProviders.ts";
17
18 it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => {
19 const loadFrom = (contents: string | undefined) =>
20 Effect.gen(function* () {
21 const fs = yield* FileSystem.FileSystem;
22 const path = yield* Path.Path;
23 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-managed-policy-" });
24 const file = path.join(dir, "policy.json");
25 if (contents !== undefined) yield* fs.writeFileString(file, contents);
26 return yield* ManagedPolicy.load(file);
27 }).pipe(Effect.scoped);
28
29 it.effect("means no policy when the file is missing", () =>
30 Effect.gen(function* () {
31 const policy = yield* loadFrom(undefined);
32 assert.isUndefined(policy.summary);
33 }),
34 );
35
36 it.effect("summarizes locked settings for clients", () =>
37 Effect.gen(function* () {
38 const policy = yield* loadFrom(
39 JSON.stringify({
40 schemaVersion: 1,
41 organization: "Example Corp",
42 supportUrl: "https://it.example/t3",
43 settings: {
44 "storageCleanup.logsAfterDays": { value: 30, locked: true },
45 defaultRuntimeMode: { value: "approval-required", locked: false },
46 },
47 }),
48 );
49 assert.deepEqual(policy.summary, {
50 organization: "Example Corp",
51 supportUrl: "https://it.example/t3",
52 lockedSettings: ["storageCleanup.logsAfterDays"],
53 });
54 }),
55 );
56
57 it.effect("tells clients which capabilities the policy switches off", () =>
58 Effect.gen(function* () {
59 const policy = yield* loadFrom(
60 JSON.stringify({
61 schemaVersion: 1,
62 organization: "Example Corp",
63 limits: { webhookTasks: false, telemetry: true, previewTunnel: false },
64 }),
65 );
66 assert.deepEqual(policy.summary?.limits, {
67 webhookTasks: false,
68 telemetry: true,
69 previewTunnel: false,
70 });
71 assert.equal(ManagedPolicy.deniedBy(policy, "webhookTasks"), "Example Corp");
72 assert.equal(ManagedPolicy.deniedBy(policy, "previewTunnel"), "Example Corp");
73 assert.isUndefined(ManagedPolicy.deniedBy(policy, "telemetry"));
74 }),
75 );
76
77 it.effect("refuses files it cannot fully enforce", () =>
78 Effect.gen(function* () {
79 const base = { schemaVersion: 1, organization: "Example Corp" };
80 const reasons = yield* Effect.forEach(
81 [
82 "{ not json",
83 // An unknown key may be a restriction from a newer release.
84 JSON.stringify({ ...base, limits: { connect: false, futureLimit: true } }),
85 JSON.stringify({ ...base, settings: { notASetting: { value: 1, locked: true } } }),
86 JSON.stringify({
87 ...base,
88 settings: { "storageCleanup.logsAfterDayz": { value: 30, locked: true } },
89 }),
90 JSON.stringify({
91 ...base,
92 settings: { defaultRuntimeMode: { value: "yolo", locked: true } },
93 }),
94 JSON.stringify({
95 ...base,
96 settings: { projectSettingsOverrides: { value: {}, locked: true } },
97 }),
98 // The user could never remove a provider instance a default keeps adding back.
99 JSON.stringify({
100 ...base,
101 settings: {
102 "providerInstances.codex_work": {
103 value: { driver: "codex", enabled: true },
104 locked: false,
105 },
106 },
107 }),
108 JSON.stringify({
109 ...base,
110 settings: {
111 providerInstances: { value: { codex_work: { driver: "codex" } }, locked: false },
112 },
113 }),
114 // A user's stored null would leave the lock building half a model selection.
115 JSON.stringify({
116 ...base,
117 settings: { "defaultModelSelection.model": { value: "gpt-5.4", locked: true } },
118 }),
119 // The server derives it from idleCompaction on every write.
120 JSON.stringify({
121 ...base,
122 settings: { compactIdleThreads: { value: false, locked: true } },
123 }),
124 // It would look locked while worktreeCleanup, which overrides it, stays the user's.
125 JSON.stringify({
126 ...base,
127 settings: { "storageCleanup.worktreeAfterDays": { value: 7, locked: true } },
128 }),
129 // An instance's own variables, home paths, and setup mode would override the lock.
130 JSON.stringify({
131 ...base,
132 settings: {
133 "providerInstances.codex.driver": { value: "codex", locked: true },
134 "providerInstances.codex.config.launchArgs": {
135 value: "-c model_provider=corp",
136 locked: true,
137 },
138 },
139 }),
140 // The server would move it into the user's secret store, past the policy's removal.
141 JSON.stringify({
142 ...base,
143 settings: {
144 providerInstances: {
145 value: { gemini: { driver: "antigravity", config: { apiKey: "corp-key" } } },
146 locked: true,
147 },
148 },
149 }),
150 // Startup reads OTLP endpoints before the policy, and environment variables outrank them.
151 JSON.stringify({
152 ...base,
153 settings: { "observability.otlpTracesUrl": { value: "", locked: true } },
154 }),
155 ],
156 (contents) =>
157 loadFrom(contents).pipe(
158 Effect.flip,
159 Effect.map((error) => error.reason),
160 ),
161 );
162 assert.lengthOf(reasons, 14);
163 assert.include(reasons[3], "storageCleanup.logsAfterDayz");
164 assert.include(reasons[6], "adds entries users could not remove");
165 assert.include(reasons[7], "adds entries users could not remove");
166 assert.include(reasons[8], 'manage "defaultModelSelection" as a whole');
167 assert.include(reasons[9], 'manage "idleCompaction" instead');
168 assert.include(reasons[10], 'lock "worktreeCleanup" too');
169 assert.include(reasons[11], 'lock "providerInstances.codex" as a whole');
170 assert.include(reasons[12], "holds a credential");
171 assert.include(reasons[13], "a policy cannot override");
172 }),
173 );
174
175 it.effect("tells clients the runtime mode ceiling", () =>
176 Effect.gen(function* () {
177 const policy = yield* loadFrom(
178 JSON.stringify({
179 schemaVersion: 1,
180 organization: "Example Corp",
181 settings: { defaultRuntimeMode: { value: "approval-required", locked: true } },
182 limits: { maxRuntimeMode: "auto-accept-edits" },
183 }),
184 );
185 const { providers, ...limits } = policy.summary?.limits ?? {};
186 assert.deepEqual(limits, { maxRuntimeMode: "auto-accept-edits" });
187 // Under a ceiling, each driver's launch configuration is the administrator's.
188 assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("claudeAgent")], [
189 "config.binaryPath",
190 "config.launchArgs",
191 "config.homePath",
192 "environment",
193 ]);
194 assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("acpRegistry")], [
195 "config.commandPath",
196 "config.commandArgs",
197 "environment",
198 ]);
199 // The host variable that replaces Codex's launch arguments is ignored too.
200 const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "-c mcp_servers.x.command=sh" };
201 const managedHost = providerHostEnvironment(policy.summary, host);
202 assert.deepEqual(managedHost, { PATH: "/usr/bin" });
203 // A PATH refresh after launch reaches drivers that hold the managed copy.
204 host.PATH = "/opt/new/bin:/usr/bin";
205 assert.strictEqual(managedHost.PATH, "/opt/new/bin:/usr/bin");
206 assert.strictEqual(providerHostEnvironment(undefined, host), host);
207 }),
208 );
209
210 it.effect(
211 "locks a variable in every spelling on Windows only, and drops a Codex launch override",
212 () =>
213 Effect.gen(function* () {
214 const codex = ProviderDriverKind.make("codex");
215 const variable = (name: string, value: string) => ({ name, value, sensitive: false });
216 const settings = {
217 ...DEFAULT_SERVER_SETTINGS,
218 providerInstances: {
219 codex: {
220 driver: codex,
221 environment: [
222 variable("HTTPS_PROXY", "http://mine"),
223 variable("T3CODE_CODEX_LAUNCH_ARGS", "--dangerously-bypass-approvals-and-sandbox"),
224 ],
225 },
226 },
227 };
228 const policyOn = (platform: NodeJS.Platform) =>
229 ManagedPolicy.fromDocument("/test/policy.json", {
230 schemaVersion: 1,
231 organization: "Example Corp",
232 limits: {
233 providers: {
234 instances: {
235 [codex]: {
236 locked: true,
237 launchArgs: "--strict-config",
238 environment: [{ name: "Https_Proxy", value: "http://gateway" }],
239 },
240 },
241 },
242 },
243 }).pipe(Effect.provideService(HostProcess.Platform, platform));
244 const environmentOn = (platform: NodeJS.Platform) =>
245 Effect.map(
246 policyOn(platform),
247 (policy) =>
248 policy.providers.applyLimits(settings).providerInstances[
249 ProviderInstanceId.make("codex")
250 ]?.environment,
251 );
252 assert.deepEqual(yield* environmentOn("win32"), [
253 variable("Https_Proxy", "http://gateway"),
254 ]);
255 assert.deepEqual(yield* environmentOn("linux"), [
256 variable("HTTPS_PROXY", "http://mine"),
257 variable("Https_Proxy", "http://gateway"),
258 ]);
259 // Saving what the client was shown keeps the override it never saw.
260 const linux = yield* policyOn("linux");
261 const shown = linux.providers.applyLimits(settings);
262 const codexId = ProviderInstanceId.make("codex");
263 const saved = linux.providers.vetWrite(settings, {
264 ...shown,
265 providerInstances: {
266 ...shown.providerInstances,
267 [codexId]: { ...shown.providerInstances[codexId]!, displayName: "Codex (work)" },
268 },
269 });
270 assert.equal(saved._tag, "Allowed");
271 const savedEnvironment =
272 saved._tag === "Allowed"
273 ? (saved.settings.providerInstances[codexId]?.environment ?? [])
274 : [];
275 assert.isTrue(savedEnvironment.some((entry) => entry.name === "T3CODE_CODEX_LAUNCH_ARGS"));
276 // A home path setting would rewrite a locked home variable at launch, so the lock owns it.
277 const claude = ProviderDriverKind.make("claudeAgent");
278 const homeLocked = yield* ManagedPolicy.fromDocument("/test/policy.json", {
279 schemaVersion: 1,
280 organization: "Example Corp",
281 limits: {
282 providers: {
283 instances: {
284 [claude]: {
285 locked: true,
286 environment: [{ name: "CLAUDE_CONFIG_DIR", value: "/opt/claude-home" }],
287 },
288 },
289 },
290 },
291 });
292 const claudeId = ProviderInstanceId.make("claudeAgent");
293 const claudeConfig = homeLocked.providers.applyLimits({
294 ...DEFAULT_SERVER_SETTINGS,
295 providerInstances: {
296 [claudeId]: { driver: claude, config: { homePath: "/home/me/.other-claude" } },
297 },
298 }).providerInstances[claudeId]?.config;
299 assert.deepEqual(claudeConfig, {});
300 assert.include(
301 homeLocked.summary?.limits?.providers?.lockedInstanceFields?.[claude] ?? [],
302 "config.homePath",
303 );
304 // Codex has a second home setting, which a locked CODEX_HOME owns too.
305 const codexHome = yield* ManagedPolicy.fromDocument("/test/policy.json", {
306 schemaVersion: 1,
307 organization: "Example Corp",
308 limits: {
309 providers: {
310 instances: {
311 [codex]: {
312 locked: true,
313 environment: [{ name: "CODEX_HOME", value: "/opt/codex-home" }],
314 },
315 },
316 },
317 },
318 });
319 assert.includeMembers(
320 [...(codexHome.summary?.limits?.providers?.lockedInstanceFields?.[codex] ?? [])],
321 ["config.homePath", "config.shadowHomePath"],
322 );
323 // A server URL makes OpenCode skip the local launch a pin sets, so the pin owns it too.
324 const opencode = ProviderDriverKind.make("opencode");
325 const opencodePinned = yield* ManagedPolicy.fromDocument("/test/policy.json", {
326 schemaVersion: 1,
327 organization: "Example Corp",
328 limits: {
329 providers: { instances: { [opencode]: { locked: true, binaryPath: "/opt/opencode" } } },
330 },
331 });
332 assert.include(
333 opencodePinned.summary?.limits?.providers?.lockedInstanceFields?.[opencode] ?? [],
334 "config.serverUrl",
335 );
336 // The same override from the environment that starts the server is ignored too.
337 const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "--yolo" };
338 assert.deepEqual(providerHostEnvironment((yield* policyOn("linux")).summary, host), {
339 PATH: "/usr/bin",
340 });
341 }),
342 );
343
344 it.effect("refuses a default runtime mode above its own ceiling", () =>
345 Effect.gen(function* () {
346 const reasons = yield* Effect.forEach([false, true], (locked) =>
347 loadFrom(
348 JSON.stringify({
349 schemaVersion: 1,
350 organization: "Example Corp",
351 settings: { defaultRuntimeMode: { value: "auto", locked } },
352 limits: { maxRuntimeMode: "auto-accept-edits" },
353 }),
354 ).pipe(
355 Effect.flip,
356 Effect.map((error) => error.reason),
357 ),
358 );
359 assert.deepEqual(reasons, [
360 '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
361 '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
362 ]);
363 }),
364 );
365
366 it.effect("tells clients which drivers run and which instance fields are locked", () =>
367 Effect.gen(function* () {
368 // A provider the policy cannot name would also escape its launch-setting rules.
369 const everyDriver = BUILT_IN_DRIVERS.map((driver) => driver.driverKind);
370 const allowingAll = yield* loadFrom(
371 JSON.stringify({
372 schemaVersion: 1,
373 organization: "Example Corp",
374 limits: { providers: { allowedDrivers: everyDriver } },
375 }),
376 );
377 assert.deepEqual<unknown>(
378 allowingAll.summary?.limits?.providers?.allowedDrivers,
379 everyDriver,
380 );
381
382 const policy = yield* loadFrom(
383 JSON.stringify({
384 schemaVersion: 1,
385 organization: "Example Corp",
386 limits: {
387 providers: {
388 allowedDrivers: ["claudeAgent", "codex"],
389 instances: {
390 claudeAgent: {
391 locked: true,
392 environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
393 binaryPath: "/opt/claude/bin/claude",
394 },
395 codex: { locked: false, launchArgs: "-c model_provider=gateway" },
396 },
397 },
398 },
399 }),
400 );
401 assert.deepEqual<unknown>(policy.summary?.limits, {
402 providers: {
403 allowedDrivers: ["claudeAgent", "codex"],
404 lockedInstanceFields: {
405 claudeAgent: ["config.binaryPath", "environment.CLAUDE_CODE_USE_BEDROCK"],
406 },
407 },
408 });
409 assert.equal(
410 disallowedDriverReason(policy.summary, ProviderDriverKind.make("cursor")),
411 "Example Corp's policy does not allow the Cursor provider.",
412 );
413 assert.isUndefined(disallowedDriverReason(policy.summary, ProviderDriverKind.make("codex")));
414 }),
415 );
416
417 it.effect("refuses provider limits it cannot enforce", () =>
418 Effect.gen(function* () {
419 const withProviders = (providers: unknown) =>
420 JSON.stringify({
421 schemaVersion: 1,
422 organization: "Example Corp",
423 limits: { providers },
424 });
425 const reasons = yield* Effect.forEach(
426 [
427 withProviders({ allowedDrivers: ["claudeAgent", "notAProvider"] }),
428 withProviders({ instances: { notAProvider: { locked: true, binaryPath: "/x" } } }),
429 // Cursor has no launch arguments setting to pin.
430 withProviders({ instances: { cursor: { locked: true, launchArgs: "--x" } } }),
431 withProviders({ instances: { codex: { locked: true, homePath: "/x" } } }),
432 withProviders({
433 instances: { codex: { locked: true, environment: [{ name: "1BAD", value: "" }] } },
434 }),
435 // No provider could run at all.
436 withProviders({ allowedDrivers: [] }),
437 ],
438 (contents) =>
439 loadFrom(contents).pipe(
440 Effect.flip,
441 Effect.map((error) => error.reason),
442 ),
443 );
444 assert.lengthOf(reasons, 6);
445 assert.include(reasons[0], "notAProvider");
446 assert.include(reasons[1], "notAProvider");
447 assert.include(reasons[2], "launchArgs");
448 }),
449 );
450
451 it.effect(
452 "tells clients how updates are managed and refuses an update feed it cannot trust",
453 () =>
454 Effect.gen(function* () {
455 const base = { schemaVersion: 1, organization: "Example Corp" };
456 const updates = {
457 mode: "auto" as const,
458 feedUrl: "https://updates.example/t3",
459 allowNightly: false,
460 };
461 const policy = yield* loadFrom(JSON.stringify({ ...base, limits: { updates } }));
462 const { feedUrl: _feedUrl, ...clientUpdates } = updates;
463 assert.deepEqual(policy.summary?.limits, { updates: clientUpdates });
464 for (const invalid of [
465 { mode: "auto", feedUrl: "http://updates.example/t3" },
466 { mode: "manual" },
467 { mode: "sometimes" },
468 { mode: "auto", pinVersion: "1.2.3" },
469 ]) {
470 yield* loadFrom(JSON.stringify({ ...base, limits: { updates: invalid } })).pipe(
471 Effect.flip,
472 );
473 }
474 }),
475 );
476 });