Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

policy.ts

182 lines7.5 KB

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