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