Open History to see the last commit
1import * as Console from "effect/Console";
2import type { ManagedPolicyDocument } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as References from "effect/References";
9import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
10import * as CliError from "effect/cli/CliError";
11import * as SecureRandom from "effect/crypto/SecureRandom";
12
13import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
14import { listManageableSettings } from "../policy/managedSettings.ts";
15import { macosProfile, windowsAdml, windowsAdmx } from "../policy/policyTemplates.ts";
16import { expandHomePath } from "../os-jank.ts";
17import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
18import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
19
20const describePolicy = (
21 policy: ManagedPolicy.ManagedPolicy["Service"],
22 loaded: Effect.Success<ReturnType<typeof ManagedPolicy.loadedPolicy>>,
23) => {
24 const { document } = policy;
25 if (document === undefined || loaded === null) {
26 return "No managed policy on this machine. Every setting belongs to the user.\n";
27 }
28 const settings = Object.entries(document.settings ?? {});
29 const lines = [
30 `Managed by ${document.organization} (${policy.path}, fingerprint ${loaded.fingerprint}).`,
31 ...(document.supportUrl === undefined ? [] : [`Support: ${document.supportUrl}`]),
32 "",
33 settings.length === 0 ? "No managed settings." : "Settings:",
34 ...settings.map(
35 ([path, setting]) =>
36 ` ${path} = ${JSON.stringify(setting.value)} (${setting.locked ? "locked" : "default"})`,
37 ),
38 ];
39 if (document.limits !== undefined) {
40 lines.push("", "Limits:", JSON.stringify(document.limits, null, 2));
41 }
42 return `${lines.join("\n")}\n`;
43};
44
45/** Whether the server running from this T3 home loaded the installed policy, which waits for a restart. */
46export const describeRunningServer = Effect.fn("cli.policy.describeRunningServer")(function* (
47 statePath: string,
48 installed: Effect.Success<ReturnType<typeof ManagedPolicy.loadedPolicy>>,
49) {
50 const state = yield* readPersistedServerRuntimeState(statePath);
51 if (Option.isNone(state) || !isProcessAlive(state.value.pid)) {
52 return "No T3 Code server is running from this T3 home. The installed policy applies when one starts.";
53 }
54 const { pid, startedAt, managedPolicy: loaded } = state.value;
55 const server = `The running server (pid ${pid}, started ${startedAt})`;
56 if (loaded === undefined) {
57 return `${server} does not report which policy it loaded. Restart it to apply the installed policy.`;
58 }
59 if ((loaded?.fingerprint ?? null) === (installed?.fingerprint ?? null)) {
60 return loaded === null
61 ? `${server} runs without a policy, as installed.`
62 : `${server} loaded this policy.`;
63 }
64 const what =
65 loaded === null
66 ? "no policy"
67 : `${loaded.organization}'s policy from ${loaded.source} (fingerprint ${loaded.fingerprint})`;
68 return `${server} loaded ${what}. Restart T3 Code to apply the installed policy.`;
69});
70
71const showCommand = Command.make("show", projectLocationFlags).pipe(
72 Command.withDescription(
73 "Show the policy installed on this machine, and whether the running server loaded it.",
74 ),
75 Command.withHandler(
76 Effect.fn("cli.policy.show")(function* (flags) {
77 // The command prints the policy itself; the server's startup log line would repeat it.
78 const policy = yield* ManagedPolicy.ManagedPolicy.pipe(
79 Effect.provide(
80 ManagedPolicy.layer.pipe(
81 Layer.provide(Layer.succeed(References.MinimumLogLevel, "Warn")),
82 ),
83 ),
84 );
85 const installed = yield* ManagedPolicy.loadedPolicy(policy);
86 yield* Console.log(describePolicy(policy, installed));
87 const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel);
88 yield* Console.log(yield* describeRunningServer(config.serverRuntimeStatePath, installed));
89 }),
90 ),
91);
92
93const checkCommand = Command.make("check", {
94 file: Argument.String("file").pipe(Argument.withDescription("Policy file to validate.")),
95}).pipe(
96 Command.withDescription("Validate a policy file before deploying it."),
97 Command.withHandler(
98 Effect.fn("cli.policy.check")(function* ({ file }) {
99 const policyFile = yield* expandHomePath(file);
100 // Startup treats a missing file as no policy; a draft that is not there checks nothing.
101 if (!(yield* (yield* FileSystem.FileSystem).exists(policyFile))) {
102 return yield* new CliError.UserError({
103 cause: file,
104 userMessage: `No policy file at ${file}.`,
105 });
106 }
107 const policy = yield* ManagedPolicy.load(policyFile);
108 yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy)));
109 }),
110 ),
111);
112
113const SAMPLE_POLICY: ManagedPolicyDocument = {
114 schemaVersion: 1,
115 organization: "Example Corp",
116 limits: { maxRuntimeMode: "auto-accept-edits", clients: ["desktop"], telemetry: false },
117};
118
119const templatesCommand = Command.make("templates", {
120 directory: Argument.String("directory").pipe(
121 Argument.withDescription("Directory to write the templates to."),
122 ),
123 policy: Flag.String("policy").pipe(
124 Flag.withDescription("Policy file to put in the macOS profile. Default: a small sample."),
125 Flag.optional,
126 ),
127}).pipe(
128 Command.withDescription(
129 "Write the Windows Group Policy template and a macOS configuration profile.",
130 ),
131 Command.withHandler(
132 Effect.fn("cli.policy.templates")(function* ({ directory, policy }) {
133 const fs = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 let document = SAMPLE_POLICY;
136 if (Option.isSome(policy)) {
137 const file = yield* expandHomePath(policy.value);
138 if (!(yield* fs.exists(file))) {
139 return yield* new CliError.UserError({
140 cause: policy.value,
141 userMessage: `No policy file at ${policy.value}.`,
142 });
143 }
144 const loaded = (yield* ManagedPolicy.load(file)).document;
145 if (loaded !== undefined) document = loaded;
146 }
147 const random = yield* SecureRandom.SecureRandom;
148 const profile = macosProfile(document, {
149 profile: yield* random.uuidV4().pipe(Effect.orDie),
150 payload: yield* random.uuidV4().pipe(Effect.orDie),
151 });
152 if (profile._tag === "Invalid") {
153 return yield* new CliError.UserError({ cause: document, userMessage: profile.reason });
154 }
155 const outputDir = yield* expandHomePath(directory);
156 const files = [
157 [path.join(outputDir, "windows", "t3code.admx"), windowsAdmx()],
158 [path.join(outputDir, "windows", "en-US", "t3code.adml"), windowsAdml()],
159 [path.join(outputDir, "macos", "t3code.mobileconfig"), profile.profile],
160 ] as const;
161 for (const [file, contents] of files) {
162 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
163 yield* fs.writeFileString(file, contents);
164 yield* Console.log(file);
165 }
166 }),
167 ),
168);
169
170const describeManageableSettings = () =>
171 listManageableSettings()
172 .map(
173 ([path, value]) =>
174 `${path} = ${value === undefined ? "(no default)" : JSON.stringify(value)}`,
175 )
176 .join("\n");
177
178const settingsCommand = Command.make("settings").pipe(
179 Command.withDescription("List the settings a policy can manage, with their defaults."),
180 Command.withHandler(() => Console.log(describeManageableSettings())),
181);
182
183export const policyCommand = Command.make("policy").pipe(
184 Command.withDescription("Inspect the administrator's managed policy."),
185 Command.withSubcommands([showCommand, checkCommand, settingsCommand, templatesCommand]),
186);