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

managedPolicyFile.ts

330 lines12.9 KB

1import { ManagedPolicyDocument } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/process";
12​
13import * as HostProcess from "./HostProcess.ts";
14​
15export class ManagedPolicyFileError extends Schema.TaggedError<ManagedPolicyFileError>()(
16 "ManagedPolicyFileError",
17 {
18 path: Schema.String,
19 reason: Schema.String,
20 cause: Schema.optional(Schema.Defect()),
21 },
22) {
23 override get message(): string {
24 return `T3 Code cannot use the managed policy at ${this.path}: ${this.reason}. It will not start until an administrator fixes this.`;
25 }
27​
28/** The system path an administrator deploys the policy to on `platform`. */
29export function managedPolicyPath(platform: NodeJS.Platform): string {
30 switch (platform) {
31 case "darwin":
32 return "/Library/Application Support/T3Code/policy.json";
33 case "win32":
34 // Not ProgramData, where a user can create the folder first and own it; and not
35 // %ProgramFiles%, which a user can point somewhere they write.
36 return "C:\\Program Files\\T3Code\\policy.json";
37 default:
38 return "/etc/t3code/policy.json";
39 }
41​
42// Unknown keys may be restrictions from a newer release; refusing them keeps a file this
43// build cannot fully enforce from looking enforced.
44const decodeDocumentJsonExit = Schema.decodeUnknownExit(
45 Schema.fromJsonString(ManagedPolicyDocument),
46 { onExcessProperty: "error" },
47);
48const decodeDocumentExit = Schema.decodeUnknownExit(ManagedPolicyDocument, {
49 onExcessProperty: "error",
50});
51​
52/** Decode a policy from JSON text, or from a value a profile already parsed. */
53const decodeDocument = (path: string, raw: unknown) => {
54 const decoded = typeof raw === "string" ? decodeDocumentJsonExit(raw) : decodeDocumentExit(raw);
55 if (Exit.isSuccess(decoded)) return Effect.succeed(decoded.value);
56 const error = Cause.squash(decoded.cause);
57 // The schema message names the offending key, e.g. `Expected no excess property at ["limits"]`.
58 const detail = Schema.isSchemaError(error) ? ` (${error.message.replace(/\s*\n\s*/g, " ")})` : "";
59 return Effect.fail(
60 new ManagedPolicyFileError({
61 path,
62 reason: `it is not valid JSON or does not match the policy schema${detail}`,
63 cause: decoded.cause,
64 }),
65 );
66};
67​
68/** Read the policy document at `path`; a missing file means no policy. */
69export const readManagedPolicyFile = Effect.fn("readManagedPolicyFile")(function* (path: string) {
70 const fs = yield* FileSystem.FileSystem;
71 const exists = yield* fs
72 .exists(path)
73 .pipe(
74 Effect.mapError(
75 (cause) =>
76 new ManagedPolicyFileError({ path, reason: "the file cannot be checked", cause }),
77 ),
78 );
79 if (!exists) return undefined;
80 const raw = yield* fs
81 .readFileString(path)
82 .pipe(
83 Effect.mapError(
84 (cause) => new ManagedPolicyFileError({ path, reason: "the file cannot be read", cause }),
85 ),
86 );
87 return yield* decodeDocument(path, raw);
88});
89​
90/** Where a configuration profile's managed preferences land on macOS. */
91export const MACOS_MANAGED_PREFERENCES_PATH =
92 "/Library/Managed Preferences/com.t3tools.t3code.plist";
93const WINDOWS_POLICY_SUBKEY = "SOFTWARE\\Policies\\T3Tools\\T3Code";
94/** The registry key Group Policy and Intune write to on Windows; `Policy` holds the JSON. */
95export const WINDOWS_POLICY_KEY = `HKLM\\${WINDOWS_POLICY_SUBKEY}`;
96// An absolute path: an earlier PATH entry could otherwise answer that there is no policy.
97const PLUTIL = "/usr/bin/plutil";
98​
99export class WindowsRegistryError extends Schema.TaggedError<WindowsRegistryError>()(
100 "WindowsRegistryError",
101 {
102 /** The Win32 error, such as 5 for access denied; absent when the registry API cannot load. */
103 code: Schema.optional(Schema.Number),
104 cause: Schema.optional(Schema.Defect()),
105 },
106) {
107 override get message(): string {
108 return this.code === undefined ? "the registry API cannot load" : `Windows error ${this.code}`;
109 }
111​
112/**
113 * Reads the registry through the Win32 API in this process. A missing value and a failed read
114 * come back apart, and blocked registry tools such as reg.exe do not matter.
115 */
116export class WindowsRegistry extends Context.Service<
117 WindowsRegistry,
118 {
119 /** The REG_SZ `value` of HKLM\\`subkey` in the 64-bit view; undefined when either is absent. */
120 readonly readMachineString: (
121 subkey: string,
122 value: string,
123 ) => Effect.Effect<string | undefined, WindowsRegistryError>;
124 }
125>()("@t3tools/shared/managedPolicyFile/WindowsRegistry") {}
126​
127// (HKEY)(LONG)0x80000002, sign-extended to 64 bits.
128const HKEY_LOCAL_MACHINE = -0x7ffffffen;
129const RRF_RT_REG_SZ = 0x2;
130const RRF_SUBKEY_WOW6464KEY = 0x10000;
131// Without it a REG_EXPAND_SZ value passes as REG_SZ, with the user's variables filled in.
132const RRF_NOEXPAND = 0x10000000;
133const ERROR_FILE_NOT_FOUND = 2;
134const ERROR_MORE_DATA = 234;
135const ERROR_UNSUPPORTED_TYPE = 1630;
136​
137/**
138 * Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only
139 * through `require`, and the desktop's CommonJS bundle loads them with `import()`.
140 */
141export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rs")>) =>
142 Layer.effect(
143 WindowsRegistry,
144 Effect.gen(function* () {
145 const architecture = yield* HostProcess.Architecture;
146 const loadGetValue = yield* Effect.cached(
147 Effect.tryPromise({
148 try: async () => {
149 // HKEY_LOCAL_MACHINE and the pointer arguments below are 64-bit.
150 if (architecture !== "x64" && architecture !== "arm64") {
151 throw new Error(`no registry access on ${architecture}`);
152 }
153 const { DataType, load, open } = await loadFfi();
154 open({ library: "t3-advapi32", path: "advapi32.dll" });
155 return (subkey: string, value: string, data: Buffer, size: Buffer): number =>
156 load({
157 library: "t3-advapi32",
158 funcName: "RegGetValueW",
159 retType: DataType.I32,
160 paramsType: [
161 DataType.BigInt,
162 DataType.WString,
163 DataType.WString,
164 DataType.U32,
165 DataType.BigInt,
166 DataType.U8Array,
167 DataType.U8Array,
168 ],
169 paramsValue: [
170 HKEY_LOCAL_MACHINE,
171 subkey,
172 value,
173 RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY | RRF_NOEXPAND,
174 0n,
175 data,
176 size,
177 ],
178 });
179 },
180 catch: (cause) => new WindowsRegistryError({ cause }),
181 }),
182 );
183 return WindowsRegistry.of({
184 readMachineString: Effect.fn("WindowsRegistry.readMachineString")(
185 function* (subkey, value) {
186 const getValue = yield* loadGetValue;
187 const attempt = (bytes: number) =>
188 Effect.try({
189 try: () => {
190 const data = Buffer.alloc(bytes);
191 const size = Buffer.alloc(4);
192 size.writeUInt32LE(bytes);
193 const code = getValue(subkey, value, data, size);
194 return { code, data, bytes: size.readUInt32LE() };
195 },
196 catch: (cause) => new WindowsRegistryError({ cause }),
197 });
198 let result = yield* attempt(64 * 1024);
199 // The value grew past the buffer; the API reported the size it needs.
200 if (result.code === ERROR_MORE_DATA) result = yield* attempt(result.bytes);
201 if (result.code === ERROR_FILE_NOT_FOUND) return undefined;
202 if (result.code !== 0) return yield* new WindowsRegistryError({ code: result.code });
203 // The size counts the terminating null RegGetValueW adds.
204 return result.data.subarray(0, result.bytes).toString("utf16le").replace(/\0+$/, "");
205 },
206 ),
207 });
208 }),
209 );
210​
211// A hung query must not hang startup; a timeout reads as a failed query.
212const run = Effect.fnUntraced(
213 function* (command: string, args: ReadonlyArray<string>) {
214 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
215 const handle = yield* spawner.spawn(
216 ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }),
217 );
218 const [stdout, exitCode] = yield* Effect.all(
219 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
220 { concurrency: 2 },
221 );
222 return { stdout, exitCode: Number(exitCode) };
223 },
224 Effect.scoped,
225 Effect.timeout(Duration.seconds(10)),
226);
227​
228const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
229// Strict: keys beside the wrapper, or more than one entry, decode as a plain document and fail.
230const decodeForcedExit = Schema.decodeUnknownExit(
231 Schema.Struct({
232 Forced: Schema.Tuple([Schema.Struct({ mcx_preference_settings: Schema.Unknown })]),
233 }),
234 { onExcessProperty: "error" },
235);
236​
237// macOS writes `PayloadUUID` and `_manualProfile` beside the profile's own keys; no policy key
238// starts with `Payload` or `_`, so dropping them cannot hide a restriction.
239const withoutProfileKeys = (value: unknown) =>
240 value === null || typeof value !== "object" || Array.isArray(value)
241 ? value
242 : Object.fromEntries(
243 Object.entries(value).filter(([key]) => !key.startsWith("Payload") && !key.startsWith("_")),
244 );
245​
246/**
247 * Installed managed preferences hold the profile's keys directly, but MCX-style profiles keep
248 * them under `Forced[0].mcx_preference_settings`; read either rather than refuse a valid profile.
249 */
250function unwrapForced(json: string): unknown {
251 const parsed = decodeJsonExit(json);
252 if (Exit.isFailure(parsed)) return json;
253 const preferences = withoutProfileKeys(parsed.value);
254 const forced = decodeForcedExit(preferences);
255 return Exit.isSuccess(forced)
256 ? withoutProfileKeys(forced.value.Forced[0].mcx_preference_settings)
257 : preferences;
259​
260/** Read the policy a configuration profile or Group Policy set; absent means no such policy. */
261const readPlatformPolicy = Effect.fnUntraced(function* (platform: NodeJS.Platform) {
262 if (platform === "darwin") {
263 const path = MACOS_MANAGED_PREFERENCES_PATH;
264 const exists = yield* (yield* FileSystem.FileSystem)
265 .exists(path)
266 .pipe(
267 Effect.mapError(
268 (cause) =>
269 new ManagedPolicyFileError({ path, reason: "the profile cannot be checked", cause }),
270 ),
271 );
272 if (!exists) return undefined;
273 const converted = yield* run(PLUTIL, ["-convert", "json", "-o", "-", path]).pipe(
274 Effect.mapError(
275 (cause) =>
276 new ManagedPolicyFileError({ path, reason: "the profile cannot be read", cause }),
277 ),
278 );
279 if (converted.exitCode !== 0) {
280 return yield* new ManagedPolicyFileError({ path, reason: "the profile cannot be read" });
281 }
282 return { source: path, document: yield* decodeDocument(path, unwrapForced(converted.stdout)) };
283 }
284 if (platform === "win32") {
285 const path = WINDOWS_POLICY_KEY;
286 const raw = yield* (yield* WindowsRegistry)
287 .readMachineString(WINDOWS_POLICY_SUBKEY, "Policy")
288 .pipe(
289 Effect.mapError(
290 (cause) =>
291 new ManagedPolicyFileError({
292 path,
293 reason:
294 cause.code === ERROR_UNSUPPORTED_TYPE
295 ? "its Policy value is not a string (REG_SZ)"
296 : cause.code === undefined
297 ? "this T3 Code install cannot load its registry reader; reinstall T3 Code"
298 : `the registry cannot be read (${cause.message})`,
299 cause,
300 }),
301 ),
302 );
303 return raw === undefined
304 ? undefined
305 : { source: path, document: yield* decodeDocument(path, raw) };
306 }
307 return undefined;
308});
309​
310/**
311 * Read the machine's policy from wherever an administrator put it: a configuration profile on
312 * macOS, the Policies registry key on Windows, or the policy file. Two sources are refused rather
313 * than merged, so what applies is never a mix nobody wrote.
314 */
315export const readManagedPolicy = Effect.fn("readManagedPolicy")(function* (
316 platform: NodeJS.Platform,
317) {
318 const filePath = managedPolicyPath(platform);
319 const [platformPolicy, file] = yield* Effect.all([
320 readPlatformPolicy(platform),
321 readManagedPolicyFile(filePath),
322 ]);
323 if (platformPolicy !== undefined && file !== undefined) {
324 return yield* new ManagedPolicyFileError({
325 path: platformPolicy.source,
326 reason: `a policy file at ${filePath} also exists; deploy the policy one way`,
327 });
328 }
329 return platformPolicy ?? (file === undefined ? undefined : { source: filePath, document: file });
330});