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