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

managedPolicyFile.ts

600 lines24.0 KB

1import {
2 ManagedPolicyClient,
3 ManagedPolicyDocument,
4 SERVER_EXIT_CODE_MANAGED_POLICY,
5} from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import * as Context from "effect/Context";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Runtime from "effect/Runtime";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import { ChildProcess, ChildProcessSpawner } from "effect/process";
17​
18import * as HostProcess from "./HostProcess.ts";
19​
20export class ManagedPolicyFileError extends Schema.TaggedError<ManagedPolicyFileError>()(
21 "ManagedPolicyFileError",
22 {
23 path: Schema.String,
24 reason: Schema.String,
25 cause: Schema.optional(Schema.Defect()),
26 },
27) {
28 override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_MANAGED_POLICY;
29​
30 override get message(): string {
31 return `T3 Code cannot use the managed policy at ${this.path}: ${this.reason}. It will not start until an administrator fixes this.`;
32 }
34​
35/** The system path an administrator deploys the policy to on `platform`. */
36export function managedPolicyPath(platform: NodeJS.Platform): string {
37 switch (platform) {
38 case "darwin":
39 return "/Library/Application Support/T3Code/policy.json";
40 case "win32":
41 // Not ProgramData, where a user can create the folder first and own it; and not
42 // %ProgramFiles%, which a user can point somewhere they write.
43 return "C:\\Program Files\\T3Code\\policy.json";
44 default:
45 return "/etc/t3code/policy.json";
46 }
48​
49// Unknown keys may be restrictions from a newer release; refusing them keeps a file this
50// build cannot fully enforce from looking enforced.
51const decodeDocumentJsonExit = Schema.decodeUnknownExit(
52 Schema.fromJsonString(ManagedPolicyDocument),
53 { onExcessProperty: "error" },
54);
55const decodeDocumentExit = Schema.decodeUnknownExit(ManagedPolicyDocument, {
56 onExcessProperty: "error",
57});
58​
59/** Decode a policy from JSON text, or from a value a profile already parsed. */
60const decodeDocument = (path: string, raw: unknown) => {
61 const decoded = typeof raw === "string" ? decodeDocumentJsonExit(raw) : decodeDocumentExit(raw);
62 if (Exit.isSuccess(decoded)) return Effect.succeed(decoded.value);
63 const error = Cause.squash(decoded.cause);
64 // The schema message names the offending key, e.g. `Expected no excess property at ["limits"]`.
65 const detail = Schema.isSchemaError(error) ? ` (${error.message.replace(/\s*\n\s*/g, " ")})` : "";
66 return Effect.fail(
67 new ManagedPolicyFileError({
68 path,
69 reason: `it is not valid JSON or does not match the policy schema${detail}`,
70 cause: decoded.cause,
71 }),
72 );
73};
74​
75/** Read the policy document at `path`; a missing file means no policy. */
76export const readManagedPolicyFile = Effect.fn("readManagedPolicyFile")(function* (path: string) {
77 const fs = yield* FileSystem.FileSystem;
78 const exists = yield* fs
79 .exists(path)
80 .pipe(
81 Effect.mapError(
82 (cause) =>
83 new ManagedPolicyFileError({ path, reason: "the file cannot be checked", cause }),
84 ),
85 );
86 if (!exists) return undefined;
87 const raw = yield* fs
88 .readFileString(path)
89 .pipe(
90 Effect.mapError(
91 (cause) => new ManagedPolicyFileError({ path, reason: "the file cannot be read", cause }),
92 ),
93 );
94 return yield* decodeDocument(path, raw);
95});
96​
97/** Where a configuration profile's managed preferences land on macOS. */
98export const MACOS_MANAGED_PREFERENCES_PATH =
99 "/Library/Managed Preferences/com.t3tools.t3code.plist";
100const WINDOWS_POLICY_SUBKEY = "SOFTWARE\\Policies\\T3Tools\\T3Code";
101/**
102 * The registry key Group Policy and Intune write to on Windows. It holds either the Group Policy
103 * template's values, one per control, or a `Policy` string with the whole policy as JSON.
104 */
105export const WINDOWS_POLICY_KEY = `HKLM\\${WINDOWS_POLICY_SUBKEY}`;
106​
107/** Each value a Group Policy control writes, and where it lands in the document. */
108export const WINDOWS_POLICY_VALUES = {
109 Organization: { type: "string", path: ["organization"] },
110 SupportUrl: { type: "string", path: ["supportUrl"] },
111 Settings: { type: "json", path: ["settings"] },
112 MaxRuntimeMode: { type: "string", path: ["limits", "maxRuntimeMode"] },
113 Connect: { type: "boolean", path: ["limits", "connect"] },
114 WebhookTasks: { type: "boolean", path: ["limits", "webhookTasks"] },
115 Telemetry: { type: "boolean", path: ["limits", "telemetry"] },
116 BrowserCookieImport: { type: "boolean", path: ["limits", "browserCookieImport"] },
117 ProviderInstances: { type: "json", path: ["limits", "providers", "instances"] },
118 UpdatesMode: { type: "string", path: ["limits", "updates", "mode"] },
119 UpdatesFeedUrl: { type: "string", path: ["limits", "updates", "feedUrl"] },
120 AllowNightly: { type: "boolean", path: ["limits", "updates", "allowNightly"] },
121} as const satisfies Record<
122 string,
123 { readonly type: "string" | "json" | "boolean"; readonly path: ReadonlyArray<string> }
124>;
125​
126/** Subkeys of checkboxes: every value set to 1 is one entry of the list at `path`. */
127export const WINDOWS_POLICY_LISTS = {
128 Clients: ["limits", "clients"],
129 AllowedDrivers: ["limits", "providers", "allowedDrivers"],
130} as const satisfies Record<string, ReadonlyArray<string>>;
131// A disabled policy still writes its checkboxes' falseValue; its own DWORD disambiguates it.
132export const WINDOWS_POLICY_GROUPS = {
133 ...WINDOWS_POLICY_LISTS,
134 Updates: ["limits", "updates"],
135} as const satisfies Record<string, ReadonlyArray<string>>;
136// An absolute path: an earlier PATH entry could otherwise answer that there is no policy.
137const PLUTIL = "/usr/bin/plutil";
138​
139export class WindowsRegistryError extends Schema.TaggedError<WindowsRegistryError>()(
140 "WindowsRegistryError",
141 {
142 /** The Win32 error, such as 5 for access denied; absent when the registry API cannot load. */
143 code: Schema.optional(Schema.Number),
144 cause: Schema.optional(Schema.Defect()),
145 },
146) {
147 override get message(): string {
148 return this.code === undefined ? "the registry API cannot load" : `Windows error ${this.code}`;
149 }
151​
152/** A registry value; REG_EXPAND_SZ and every other type read as `other`. */
153export type RegistryValue =
154 | { readonly name: string; readonly type: "REG_SZ"; readonly data: string }
155 | { readonly name: string; readonly type: "REG_DWORD"; readonly data: number }
156 | { readonly name: string; readonly type: "other" };
157​
158export interface RegistryKey {
159 readonly values: ReadonlyArray<RegistryValue>;
160 readonly subkeys: ReadonlyArray<string>;
162​
163/**
164 * Reads the registry through the Win32 API in this process. A missing key and a failed read come
165 * back apart, and blocked registry tools such as reg.exe do not matter.
166 */
167export class WindowsRegistry extends Context.Service<
168 WindowsRegistry,
169 {
170 /** The values and subkey names of HKLM\\`subkey` in the 64-bit view; undefined when absent. */
171 readonly readMachineKey: (
172 subkey: string,
173 ) => Effect.Effect<RegistryKey | undefined, WindowsRegistryError>;
174 }
175>()("@t3tools/shared/managedPolicyFile/WindowsRegistry") {}
176​
177// (HKEY)(LONG)0x80000002, sign-extended to 64 bits.
178const HKEY_LOCAL_MACHINE = -0x7ffffffen;
179const KEY_READ = 0x20019;
180const KEY_WOW64_64KEY = 0x100;
181const REG_SZ = 1;
182const REG_DWORD = 4;
183const ERROR_FILE_NOT_FOUND = 2;
184const ERROR_MORE_DATA = 234;
185const ERROR_NO_MORE_ITEMS = 259;
186// Value and key names are at most 16,383 characters.
187const MAX_NAME_CHARS = 16_384;
188​
189class Win32Failure extends Error {
190 readonly code: number;
191 constructor(code: number) {
192 super(`Windows error ${code}`);
193 this.code = code;
194 }
196​
197/**
198 * Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only
199 * through `require`, and the desktop's CommonJS bundle loads them with `import()`.
200 */
201export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rs")>) =>
202 Layer.effect(
203 WindowsRegistry,
204 Effect.gen(function* () {
205 const architecture = yield* HostProcess.Architecture;
206 const loadApi = yield* Effect.cached(
207 Effect.tryPromise({
208 try: async () => {
209 // HKEY_LOCAL_MACHINE, key handles, and the null pointers below are 64-bit.
210 if (architecture !== "x64" && architecture !== "arm64") {
211 throw new Error(`no registry access on ${architecture}`);
212 }
213 const { DataType, load, open } = await loadFfi();
214 open({ library: "t3-advapi32", path: "advapi32.dll" });
215 const call = (
216 funcName: string,
217 paramsType: Array<(typeof DataType)[keyof typeof DataType]>,
218 paramsValue: Array<unknown>,
219 ): number =>
220 load({
221 library: "t3-advapi32",
222 funcName,
223 retType: DataType.I32,
224 paramsType,
225 paramsValue,
226 } as Parameters<typeof load>[0]) as number;
227 const { BigInt: Handle, U32, U8Array: Out, WString } = DataType;
228 return {
229 open: (subkey: string, handle: Buffer) =>
230 call(
231 "RegOpenKeyExW",
232 [Handle, WString, U32, U32, Out],
233 [HKEY_LOCAL_MACHINE, subkey, 0, KEY_READ | KEY_WOW64_64KEY, handle],
234 ),
235 enumValue: (
236 key: bigint,
237 index: number,
238 name: Buffer,
239 nameChars: Buffer,
240 type: Buffer,
241 data: Buffer,
242 dataBytes: Buffer,
243 ) =>
244 call(
245 "RegEnumValueW",
246 [Handle, U32, Out, Out, Handle, Out, Out, Out],
247 [key, index, name, nameChars, 0n, type, data, dataBytes],
248 ),
249 enumKey: (key: bigint, index: number, name: Buffer, nameChars: Buffer) =>
250 call(
251 "RegEnumKeyExW",
252 [Handle, U32, Out, Out, Handle, Handle, Handle, Handle],
253 [key, index, name, nameChars, 0n, 0n, 0n, 0n],
254 ),
255 close: (key: bigint) => call("RegCloseKey", [Handle], [key]),
256 };
257 },
258 catch: (cause) => new WindowsRegistryError({ cause }),
259 }),
260 );
261​
262 const readKey = (api: Effect.Success<typeof loadApi>, subkey: string) => {
263 const handle = Buffer.alloc(8);
264 const opened = api.open(subkey, handle);
265 if (opened === ERROR_FILE_NOT_FOUND) return undefined;
266 if (opened !== 0) throw new Win32Failure(opened);
267 const key = handle.readBigInt64LE();
268 try {
269 const name = Buffer.alloc(MAX_NAME_CHARS * 2);
270 const chars = Buffer.alloc(4);
271 const values: Array<RegistryValue> = [];
272 for (let index = 0; ; index++) {
273 let data = Buffer.alloc(64 * 1024);
274 const type = Buffer.alloc(4);
275 const bytes = Buffer.alloc(4);
276 const attempt = () => {
277 chars.writeUInt32LE(MAX_NAME_CHARS);
278 bytes.writeUInt32LE(data.length);
279 return api.enumValue(key, index, name, chars, type, data, bytes);
280 };
281 let code = attempt();
282 // The value is larger than the buffer; the API reported the size it needs.
283 if (code === ERROR_MORE_DATA) {
284 data = Buffer.alloc(bytes.readUInt32LE());
285 code = attempt();
286 }
287 if (code === ERROR_NO_MORE_ITEMS) break;
288 if (code !== 0) throw new Win32Failure(code);
289 const valueName = name.subarray(0, chars.readUInt32LE() * 2).toString("utf16le");
290 const stored = data.subarray(0, bytes.readUInt32LE());
291 const valueType = type.readUInt32LE();
292 values.push(
293 valueType === REG_SZ
294 ? {
295 name: valueName,
296 type: "REG_SZ",
297 data: stored.toString("utf16le").replace(/\0+$/, ""),
298 }
299 : valueType === REG_DWORD && stored.length === 4
300 ? { name: valueName, type: "REG_DWORD", data: stored.readUInt32LE() }
301 : { name: valueName, type: "other" },
302 );
303 }
304 const subkeys: Array<string> = [];
305 for (let index = 0; ; index++) {
306 chars.writeUInt32LE(MAX_NAME_CHARS);
307 const code = api.enumKey(key, index, name, chars);
308 if (code === ERROR_NO_MORE_ITEMS) break;
309 if (code !== 0) throw new Win32Failure(code);
310 subkeys.push(name.subarray(0, chars.readUInt32LE() * 2).toString("utf16le"));
311 }
312 return { values, subkeys };
313 } finally {
314 api.close(key);
315 }
316 };
317​
318 return WindowsRegistry.of({
319 readMachineKey: Effect.fn("WindowsRegistry.readMachineKey")(function* (subkey) {
320 const api = yield* loadApi;
321 return yield* Effect.try({
322 try: () => readKey(api, subkey),
323 catch: (cause) =>
324 new WindowsRegistryError(
325 cause instanceof Win32Failure ? { code: cause.code, cause } : { cause },
326 ),
327 });
328 }),
329 });
330 }),
331 );
332​
333// A hung query must not hang startup; a timeout reads as a failed query.
334const run = Effect.fnUntraced(
335 function* (command: string, args: ReadonlyArray<string>) {
336 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
337 const handle = yield* spawner.spawn(
338 ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }),
339 );
340 const [stdout, exitCode] = yield* Effect.all(
341 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
342 { concurrency: 2 },
343 );
344 return { stdout, exitCode: Number(exitCode) };
345 },
346 Effect.scoped,
347 Effect.timeout(Duration.seconds(10)),
348);
349​
350const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
351type PolicyRegistryValue = RegistryValue & {
352 /** The list subkey the value sits in, or "" for the policy key itself. */
353 readonly key: string;
354};
355​
356const setPath = (target: Record<string, unknown>, path: ReadonlyArray<string>, value: unknown) => {
357 let node = target;
358 for (const segment of path.slice(0, -1)) {
359 node = (node[segment] ??= {}) as Record<string, unknown>;
360 }
361 node[path.at(-1)!] = value;
362};
363​
364const dwordBoolean = (value: RegistryValue) =>
365 value.type !== "REG_DWORD"
366 ? undefined
367 : value.data === 0
368 ? false
369 : value.data === 1
370 ? true
371 : undefined;
372​
373/**
374 * The document the Group Policy template's values describe, undefined when they describe none, or
375 * why they do not describe one.
376 */
377function windowsPolicyDocument(
378 values: ReadonlyArray<PolicyRegistryValue>,
379 knownDrivers: ReadonlyArray<string>,
380): { readonly document: unknown } | { readonly error: string } {
381 // Registry names ignore case; a hand-written `organization` is still Organization.
382 const canonical = new Map(
383 [...Object.keys(WINDOWS_POLICY_VALUES), ...Object.keys(WINDOWS_POLICY_GROUPS)].map((name) => [
384 name.toLowerCase(),
385 name,
386 ]),
387 );
388 values = values.map((value) =>
389 value.key === ""
390 ? { ...value, name: canonical.get(value.name.toLowerCase()) ?? value.name }
391 : value,
392 );
393 const document: Record<string, unknown> = { schemaVersion: 1 };
394 const lists = new Map<string, Array<string>>();
395 const disabled: Array<ReadonlyArray<string>> = [];
396 for (const value of values) {
397 if (value.key !== "" || !Object.hasOwn(WINDOWS_POLICY_GROUPS, value.name)) continue;
398 const enabled = dwordBoolean(value);
399 if (enabled === undefined) return { error: `${value.name} must be a DWORD of 0 or 1` };
400 if (!enabled) {
401 disabled.push(WINDOWS_POLICY_GROUPS[value.name as keyof typeof WINDOWS_POLICY_GROUPS]);
402 } else if (Object.hasOwn(WINDOWS_POLICY_LISTS, value.name)) {
403 lists.set(value.name, []);
404 }
405 }
406 const put = (path: ReadonlyArray<string>, value: unknown) => {
407 if (!disabled.some((prefix) => prefix.every((segment, index) => path[index] === segment))) {
408 setPath(document, path, value);
409 }
410 };
411 for (const value of values) {
412 const where = value.key === "" ? value.name : `${value.key}\\${value.name}`;
413 if (value.key !== "") {
414 const checked = dwordBoolean(value);
415 if (checked === undefined) return { error: `${where} must be a DWORD of 0 or 1` };
416 const list = lists.get(value.key) ?? [];
417 lists.set(value.key, list);
418 if (checked) {
419 const names = value.key === "Clients" ? ManagedPolicyClient.literals : knownDrivers;
420 list.push(
421 names.find((name) => name.toLowerCase() === value.name.toLowerCase()) ?? value.name,
422 );
423 }
424 continue;
425 }
426 if (Object.hasOwn(WINDOWS_POLICY_GROUPS, value.name)) continue;
427 if (!Object.hasOwn(WINDOWS_POLICY_VALUES, value.name)) {
428 return { error: `${value.name} is not a T3 Code policy value` };
429 }
430 const field = WINDOWS_POLICY_VALUES[value.name as keyof typeof WINDOWS_POLICY_VALUES];
431 if (field.type === "boolean") {
432 const flag = dwordBoolean(value);
433 if (flag === undefined) return { error: `${where} must be a DWORD of 0 or 1` };
434 put(field.path, flag);
435 continue;
436 }
437 if (value.type !== "REG_SZ") return { error: `${where} must be a string (REG_SZ)` };
438 // Group Policy writes an empty string for a box left blank.
439 if (value.data === "") continue;
440 if (field.type === "string") {
441 put(field.path, value.data);
442 continue;
443 }
444 const parsed = decodeJsonExit(value.data);
445 if (Exit.isFailure(parsed)) return { error: `${where} is not valid JSON` };
446 put(field.path, parsed.value);
447 }
448 for (const [key, list] of lists) {
449 put(WINDOWS_POLICY_LISTS[key as keyof typeof WINDOWS_POLICY_LISTS], list);
450 }
451 // Policies set to Disabled leave values behind that restrict nothing.
452 if (Object.keys(document).length === 1) return { document: undefined };
453 // The schema would name `["organization"]`, which an admin cannot map to a Group Policy setting.
454 if (document.organization === undefined) {
455 return { error: "set the Organization policy whenever another T3 Code policy is set" };
456 }
457 return { document };
459​
460// Strict: keys beside the wrapper, or more than one entry, decode as a plain document and fail.
461const decodeForcedExit = Schema.decodeUnknownExit(
462 Schema.Struct({
463 Forced: Schema.Tuple([Schema.Struct({ mcx_preference_settings: Schema.Unknown })]),
464 }),
465 { onExcessProperty: "error" },
466);
467​
468// macOS writes `PayloadUUID` and `_manualProfile` beside the profile's own keys; no policy key
469// starts with `Payload` or `_`, so dropping them cannot hide a restriction.
470const withoutProfileKeys = (value: unknown) =>
471 value === null || typeof value !== "object" || Array.isArray(value)
472 ? value
473 : Object.fromEntries(
474 Object.entries(value).filter(([key]) => !key.startsWith("Payload") && !key.startsWith("_")),
475 );
476​
477/**
478 * Installed managed preferences hold the profile's keys directly, but MCX-style profiles keep
479 * them under `Forced[0].mcx_preference_settings`; read either rather than refuse a valid profile.
480 */
481function unwrapForced(json: string): unknown {
482 const parsed = decodeJsonExit(json);
483 if (Exit.isFailure(parsed)) return json;
484 const preferences = withoutProfileKeys(parsed.value);
485 const forced = decodeForcedExit(preferences);
486 return Exit.isSuccess(forced)
487 ? withoutProfileKeys(forced.value.Forced[0].mcx_preference_settings)
488 : preferences;
490​
491/** Read the policy a configuration profile or Group Policy set; absent means no such policy. */
492const readPlatformPolicy = Effect.fnUntraced(function* (
493 platform: NodeJS.Platform,
494 knownDrivers: ReadonlyArray<string>,
495) {
496 if (platform === "darwin") {
497 const path = MACOS_MANAGED_PREFERENCES_PATH;
498 const exists = yield* (yield* FileSystem.FileSystem)
499 .exists(path)
500 .pipe(
501 Effect.mapError(
502 (cause) =>
503 new ManagedPolicyFileError({ path, reason: "the profile cannot be checked", cause }),
504 ),
505 );
506 if (!exists) return undefined;
507 const converted = yield* run(PLUTIL, ["-convert", "json", "-o", "-", path]).pipe(
508 Effect.mapError(
509 (cause) =>
510 new ManagedPolicyFileError({ path, reason: "the profile cannot be read", cause }),
511 ),
512 );
513 if (converted.exitCode !== 0) {
514 return yield* new ManagedPolicyFileError({ path, reason: "the profile cannot be read" });
515 }
516 return { source: path, document: yield* decodeDocument(path, unwrapForced(converted.stdout)) };
517 }
518 if (platform === "win32") {
519 const path = WINDOWS_POLICY_KEY;
520 const registry = yield* WindowsRegistry;
521 const readKey = (subkey: string) =>
522 registry.readMachineKey(subkey).pipe(
523 Effect.mapError(
524 (cause) =>
525 new ManagedPolicyFileError({
526 path,
527 reason:
528 cause.code === undefined
529 ? "this T3 Code install cannot load its registry reader; reinstall T3 Code"
530 : `the registry cannot be read (${cause.message})`,
531 cause,
532 }),
533 ),
534 );
535 const refuse = (reason: string) => new ManagedPolicyFileError({ path, reason });
536 const root = yield* readKey(WINDOWS_POLICY_SUBKEY);
537 if (root === undefined) return undefined;
538 const json = root.values.find((value) => value.name.toLowerCase() === "policy");
539 if (json !== undefined) {
540 // Not Configured clears a list policy's values but can leave its empty subkey behind.
541 let templateSettings = root.values.length > 1;
542 for (const subkey of root.subkeys) {
543 if (templateSettings) break;
544 const child = yield* readKey(`${WINDOWS_POLICY_SUBKEY}\\${subkey}`);
545 templateSettings =
546 child !== undefined && (child.values.length > 0 || child.subkeys.length > 0);
547 }
548 if (templateSettings) {
549 return yield* refuse(
550 "it holds both a Policy value and Group Policy settings; deploy the policy one way",
551 );
552 }
553 if (json.type !== "REG_SZ") return yield* refuse("its Policy value is not a string (REG_SZ)");
554 return { source: path, document: yield* decodeDocument(path, json.data) };
555 }
556 const values: Array<PolicyRegistryValue> = root.values.map((value) => ({ ...value, key: "" }));
557 for (const subkey of root.subkeys) {
558 // Registry names ignore case.
559 const list = Object.keys(WINDOWS_POLICY_LISTS).find(
560 (name) => name.toLowerCase() === subkey.toLowerCase(),
561 );
562 if (list === undefined) return yield* refuse(`${subkey} is not a T3 Code policy key`);
563 const checkboxes = yield* readKey(`${WINDOWS_POLICY_SUBKEY}\\${subkey}`);
564 if (checkboxes === undefined) continue;
565 if (checkboxes.subkeys.length > 0) {
566 return yield* refuse(`${subkey}\\${checkboxes.subkeys[0]} is not a T3 Code policy key`);
567 }
568 values.push(...checkboxes.values.map((value) => ({ ...value, key: list })));
569 }
570 const built = windowsPolicyDocument(values, knownDrivers);
571 if ("error" in built) return yield* refuse(built.error);
572 // An empty key, or one holding only policies set to Disabled, sets nothing.
573 if (built.document === undefined) return undefined;
574 return { source: path, document: yield* decodeDocument(path, built.document) };
575 }
576 return undefined;
577});
578​
579/**
580 * Read the machine's policy from wherever an administrator put it: a configuration profile on
581 * macOS, the Policies registry key on Windows, or the policy file. Two sources are refused rather
582 * than merged, so what applies is never a mix nobody wrote.
583 */
584export const readManagedPolicy = Effect.fn("readManagedPolicy")(function* (
585 platform: NodeJS.Platform,
586 knownDrivers: ReadonlyArray<string> = [],
587) {
588 const filePath = managedPolicyPath(platform);
589 const [platformPolicy, file] = yield* Effect.all([
590 readPlatformPolicy(platform, knownDrivers),
591 readManagedPolicyFile(filePath),
592 ]);
593 if (platformPolicy !== undefined && file !== undefined) {
594 return yield* new ManagedPolicyFileError({
595 path: platformPolicy.source,
596 reason: `a policy file at ${filePath} also exists; deploy the policy one way`,
597 });
598 }
599 return platformPolicy ?? (file === undefined ? undefined : { source: filePath, document: file });
600});