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 22, 05:45 UTC
feat(policy): admins set managed policy from a Group Policy template (#29862)
Co-authored-by: Matthew Feroz <136640686+MatthewFeroz@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 3, 2026 at 12:41 UTC
bd48d8c8f622dfb4ac3a092061f205b85045d244
8 files changed
+1053
-116
apps/server/src/cli/policy.ts
+61
-2
@@ -1,13 +1,17 @@
1
import * as Console from "effect/Console";
2
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
3
import * as Effect from "effect/Effect";
4
import * as FileSystem from "effect/FileSystem";
5
import * as Layer from "effect/Layer";
6
import * as Option from "effect/Option";
7
+import * as Path from "effect/Path";
8
import * as References from "effect/References";
7
-import { Argument, Command, GlobalFlag } from "effect/cli";
9
+import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
10
import * as CliError from "effect/cli/CliError";
11
+import * as SecureRandom from "effect/crypto/SecureRandom";
12
13
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
14
+import { macosProfile, windowsAdml, windowsAdmx } from "../policy/policyTemplates.ts";
15
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
16
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
17
@@ -103,7 +107,62 @@ const checkCommand = Command.make("check", {
107
),
108
);
109
110
+const SAMPLE_POLICY: ManagedPolicyDocument = {
111
+ schemaVersion: 1,
112
+ organization: "Example Corp",
113
+ limits: { maxRuntimeMode: "auto-accept-edits", clients: ["desktop"], telemetry: false },
114
+};
115
+
116
+const templatesCommand = Command.make("templates", {
117
+ directory: Argument.String("directory").pipe(
118
+ Argument.withDescription("Directory to write the templates to."),
119
+ ),
120
+ policy: Flag.String("policy").pipe(
121
+ Flag.withDescription("Policy file to put in the macOS profile. Default: a small sample."),
122
+ Flag.optional,
123
+ ),
124
+}).pipe(
125
+ Command.withDescription(
126
+ "Write the Windows Group Policy template and a macOS configuration profile.",
127
+ ),
128
+ Command.withHandler(
129
+ Effect.fn("cli.policy.templates")(function* ({ directory, policy }) {
130
+ const fs = yield* FileSystem.FileSystem;
131
+ const path = yield* Path.Path;
132
+ let document = SAMPLE_POLICY;
133
+ if (Option.isSome(policy)) {
134
+ if (!(yield* fs.exists(policy.value))) {
135
+ return yield* new CliError.UserError({
136
+ cause: policy.value,
137
+ userMessage: `No policy file at ${policy.value}.`,
138
+ });
139
+ }
140
+ const loaded = (yield* ManagedPolicy.load(policy.value)).document;
141
+ if (loaded !== undefined) document = loaded;
142
+ }
143
+ const random = yield* SecureRandom.SecureRandom;
144
+ const profile = macosProfile(document, {
145
+ profile: yield* random.uuidV4().pipe(Effect.orDie),
146
+ payload: yield* random.uuidV4().pipe(Effect.orDie),
147
+ });
148
+ if (profile._tag === "Invalid") {
149
+ return yield* new CliError.UserError({ cause: document, userMessage: profile.reason });
150
+ }
151
+ const files = [
152
+ [path.join(directory, "windows", "t3code.admx"), windowsAdmx()],
153
+ [path.join(directory, "windows", "en-US", "t3code.adml"), windowsAdml()],
154
+ [path.join(directory, "macos", "t3code.mobileconfig"), profile.profile],
155
+ ] as const;
156
+ for (const [file, contents] of files) {
157
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
158
+ yield* fs.writeFileString(file, contents);
159
+ yield* Console.log(file);
160
+ }
161
+ }),
162
+ ),
163
+);
164
+
165
export const policyCommand = Command.make("policy").pipe(
166
Command.withDescription("Inspect the administrator's managed policy."),
108
- Command.withSubcommands([showCommand, checkCommand]),
167
+ Command.withSubcommands([showCommand, checkCommand, templatesCommand]),
168
);
apps/server/src/policy/ManagedPolicy.ts
+4
-1
@@ -185,7 +185,10 @@ const make = Effect.gen(function* () {
185
const policy = yield* Option.match(devPath, {
186
onSome: load,
187
onNone: () =>
188
- readManagedPolicy(platform).pipe(
188
+ readManagedPolicy(
189
+ platform,
190
+ ManagedProviders.knownDriverLabels().map(({ driver }) => driver),
191
+ ).pipe(
192
Effect.flatMap((found) =>
193
fromDocument(found?.source ?? managedPolicyPath(platform), found?.document),
194
),
apps/server/src/policy/managedProviders.ts
+4
@@ -77,6 +77,10 @@ const KNOWN_DRIVERS: ReadonlyMap<ProviderDriverKind, KnownDriver> = new Map([
77
),
78
]);
79
80
+/** Each driver a policy may name, with the label users see. */
81
+export const knownDriverLabels = () =>
82
+ Array.from(KNOWN_DRIVERS, ([driver, { label }]) => ({ driver, label }));
83
+
84
const PINNED_CONFIG_FIELDS = ["binaryPath", "launchArgs"] as const;
85
type PinnedConfigField = (typeof PINNED_CONFIG_FIELDS)[number];
86
apps/server/src/policy/policyTemplates.test.ts
new
+37
@@ -0,0 +1,37 @@
1
+import { assert, it } from "@effect/vitest";
2
+import {
3
+ WINDOWS_POLICY_GROUPS,
4
+ WINDOWS_POLICY_LISTS,
5
+ WINDOWS_POLICY_VALUES,
6
+} from "@t3tools/shared/managedPolicyFile";
7
+
8
+import { macosProfile, windowsAdmx } from "./policyTemplates.ts";
9
+
10
+it("gives every registry value the Windows reader accepts a Group Policy control", () => {
11
+ const admx = windowsAdmx();
12
+ for (const name of Object.keys(WINDOWS_POLICY_VALUES)) {
13
+ assert.include(admx, `valueName="${name}"`);
14
+ }
15
+ for (const key of Object.keys(WINDOWS_POLICY_LISTS)) {
16
+ assert.include(admx, `key="SOFTWARE\\Policies\\T3Tools\\T3Code\\${key}"`);
17
+ }
18
+ for (const name of Object.keys(WINDOWS_POLICY_GROUPS)) {
19
+ assert.include(admx, `valueName="${name}"`);
20
+ }
21
+});
22
+
23
+it("refuses a profile for a policy with a null value, which a plist cannot hold", () => {
24
+ const profile = macosProfile(
25
+ {
26
+ schemaVersion: 1,
27
+ organization: "Example Corp",
28
+ settings: { defaultModelSelection: { value: null, locked: true } },
29
+ },
30
+ { profile: "profile-uuid", payload: "payload-uuid" },
31
+ );
32
+ assert.deepStrictEqual(profile, {
33
+ _tag: "Invalid",
34
+ reason:
35
+ "settings.defaultModelSelection is null, which a configuration profile cannot hold; deploy this policy as a file.",
36
+ });
37
+});
apps/server/src/policy/policyTemplates.ts
new
+386
@@ -0,0 +1,386 @@
1
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
2
+import {
3
+ WINDOWS_POLICY_KEY,
4
+ WINDOWS_POLICY_GROUPS,
5
+ WINDOWS_POLICY_LISTS,
6
+ WINDOWS_POLICY_VALUES,
7
+} from "@t3tools/shared/managedPolicyFile";
8
+
9
+import { knownDriverLabels } from "./managedProviders.ts";
10
+
11
+type ValueName = keyof typeof WINDOWS_POLICY_VALUES;
12
+type ListKey = keyof typeof WINDOWS_POLICY_LISTS;
13
+
14
+type Element =
15
+ | {
16
+ readonly kind: "text";
17
+ readonly name: ValueName;
18
+ readonly label: string;
19
+ readonly json?: true;
20
+ }
21
+ | {
22
+ readonly kind: "enum";
23
+ readonly name: ValueName;
24
+ readonly label: string;
25
+ readonly items: ReadonlyArray<{ readonly value: string; readonly label: string }>;
26
+ readonly defaultItem: number;
27
+ }
28
+ | {
29
+ readonly kind: "checkbox";
30
+ readonly list?: ListKey;
31
+ readonly name: string;
32
+ readonly label: string;
33
+ readonly defaultChecked: boolean;
34
+ };
35
+
36
+interface Policy {
37
+ readonly id: string;
38
+ readonly title: string;
39
+ readonly help: string;
40
+ /** A policy whose Enabled and Disabled states are themselves the value. */
41
+ readonly toggle?: ValueName;
42
+ readonly elements?: ReadonlyArray<Element>;
43
+}
44
+
45
+const RUNTIME_MODES = [
46
+ { value: "approval-required", label: "Supervised" },
47
+ { value: "auto-accept-edits", label: "Auto-accept edits" },
48
+ { value: "auto", label: "Auto" },
49
+ { value: "full-access", label: "Full access" },
50
+];
51
+
52
+const policies = (): ReadonlyArray<Policy> => [
53
+ {
54
+ id: "Organization",
55
+ title: "Organization",
56
+ help: 'Required whenever any other T3 Code policy is set: T3 Code will not start with policies that do not name an organization.\n\nUsers see the name as "Managed by <organization>" beside every control the policy locks. The support URL is optional.',
57
+ elements: [
58
+ { kind: "text", name: "Organization", label: "Organization name" },
59
+ { kind: "text", name: "SupportUrl", label: "Support URL (optional)" },
60
+ ],
61
+ },
62
+ {
63
+ id: "MaxRuntimeMode",
64
+ title: "Broadest permission mode",
65
+ help: "The broadest permission mode any thread may use, including threads agents and scheduled tasks start.\n\nA thread already above it cannot run another turn until someone lowers its mode. Under this limit, each provider's launch settings (binary path, launch arguments, environment variables) come only from the policy.\n\nDisabled or Not Configured: no restriction.",
66
+ elements: [
67
+ {
68
+ kind: "enum",
69
+ name: "MaxRuntimeMode",
70
+ label: "Broadest permission mode",
71
+ items: RUNTIME_MODES,
72
+ defaultItem: 1,
73
+ },
74
+ ],
75
+ },
76
+ {
77
+ id: "Clients",
78
+ title: "Allowed clients",
79
+ help: "What may connect to T3 Code on this machine.\n\nWithout Remote, T3 Code only listens on this machine, does not create pairing links, signs out devices that paired earlier, and turns T3 Connect off. Check at least one client.\n\nDisabled or Not Configured: no restriction.",
80
+ elements: [
81
+ {
82
+ kind: "checkbox",
83
+ list: "Clients",
84
+ name: "desktop",
85
+ label: "Desktop app on this machine",
86
+ defaultChecked: true,
87
+ },
88
+ {
89
+ kind: "checkbox",
90
+ list: "Clients",
91
+ name: "local-browser",
92
+ label: "A browser on this machine",
93
+ defaultChecked: true,
94
+ },
95
+ {
96
+ kind: "checkbox",
97
+ list: "Clients",
98
+ name: "remote",
99
+ label: "Remote: phones, other computers, app.t3.codes",
100
+ defaultChecked: false,
101
+ },
102
+ ],
103
+ },
104
+ {
105
+ id: "Connect",
106
+ title: "Allow T3 Connect",
107
+ help: "Disabled turns T3 Connect off and unlinks this machine. Other remote access still follows Allowed clients.\n\nEnabled or Not Configured leaves T3 Connect available.",
108
+ toggle: "Connect",
109
+ },
110
+ {
111
+ id: "WebhookTasks",
112
+ title: "Allow webhook tasks",
113
+ help: "Disabled stops scheduled tasks from using webhook triggers. Existing webhook tasks are kept but do not run.",
114
+ toggle: "WebhookTasks",
115
+ },
116
+ {
117
+ id: "BrowserCookieImport",
118
+ title: "Allow importing browser cookies",
119
+ help: "Disabled stops users from importing cookies from another browser into T3 Code's browser.",
120
+ toggle: "BrowserCookieImport",
121
+ },
122
+ {
123
+ id: "Telemetry",
124
+ title: "Allow usage data",
125
+ help: "Disabled stops T3 Code from sending product usage data and relay connection traces. Enabled cannot turn them on for a user who turned them off.",
126
+ toggle: "Telemetry",
127
+ },
128
+ {
129
+ id: "AllowedDrivers",
130
+ title: "Allowed providers",
131
+ help: "Only the checked providers may run. Threads on other providers stay, marked unavailable.\n\nDisabled or Not Configured: no restriction.",
132
+ elements: knownDriverLabels().map(({ driver, label }) => ({
133
+ kind: "checkbox" as const,
134
+ list: "AllowedDrivers" as const,
135
+ name: driver,
136
+ label,
137
+ defaultChecked: driver === "codex" || driver === "claudeAgent",
138
+ })),
139
+ },
140
+ {
141
+ id: "Updates",
142
+ title: "Updates",
143
+ help: "Off stops T3 Code from checking for updates, for machines that receive T3 Code through device management.\n\nA feed URL makes the desktop app update from your own mirror of the release feed instead of GitHub; it must be https. Unchecking nightly makes the nightly channel unavailable.\n\nDisabled or Not Configured: no restriction.",
144
+ elements: [
145
+ {
146
+ kind: "enum",
147
+ name: "UpdatesMode",
148
+ label: "Updates",
149
+ items: [
150
+ { value: "auto", label: "Automatic" },
151
+ { value: "off", label: "Off" },
152
+ ],
153
+ defaultItem: 0,
154
+ },
155
+ { kind: "text", name: "UpdatesFeedUrl", label: "Feed URL (optional)" },
156
+ {
157
+ kind: "checkbox",
158
+ name: "AllowNightly",
159
+ label: "Allow the nightly channel",
160
+ defaultChecked: true,
161
+ },
162
+ ],
163
+ },
164
+ {
165
+ id: "Settings",
166
+ title: "Managed settings (JSON)",
167
+ help: 'Defaults and locks for server settings, as the "settings" object of a T3 Code policy. Each key is a setting path; each value is {"value": ..., "locked": true|false}.\n\nExample: {"enableAgentBrowserAccess": {"value": false, "locked": true}}\n\nRun "t3 policy check" on a policy file with the same object to validate it first.',
168
+ elements: [{ kind: "text", name: "Settings", label: "Settings JSON", json: true }],
169
+ },
170
+ {
171
+ id: "ProviderInstances",
172
+ title: "Provider settings (JSON)",
173
+ help: 'Fields set on every instance of a provider, as the "limits.providers.instances" object of a T3 Code policy: environment variables, binaryPath, launchArgs.\n\nExample: {"claudeAgent": {"locked": true, "environment": [{"name": "CLAUDE_CODE_USE_BEDROCK", "value": "1"}]}}\n\nEvery user on the machine can read this value, so do not put credentials in it.',
174
+ elements: [
175
+ { kind: "text", name: "ProviderInstances", label: "Provider settings JSON", json: true },
176
+ ],
177
+ },
178
+];
179
+
180
+const escapeXml = (text: string) =>
181
+ text
182
+ .replaceAll("&", "&")
183
+ .replaceAll("<", "<")
184
+ .replaceAll(">", ">")
185
+ .replaceAll('"', """);
186
+
187
+// ADMX keys are relative to the hive the policy class picks.
188
+const ADMX_KEY = WINDOWS_POLICY_KEY.replace(/^HKLM\\/, "");
189
+const elementId = (element: Element) =>
190
+ element.kind === "checkbox" && element.list !== undefined
191
+ ? `${element.list}_${element.name}`
192
+ : element.name;
193
+
194
+const admxElement = (element: Element) => {
195
+ const id = elementId(element);
196
+ switch (element.kind) {
197
+ case "text":
198
+ return `<text id="${id}" valueName="${element.name}"${
199
+ element.name === "Organization" ? ' required="true"' : ""
200
+ }${element.json ? ' maxLength="32767"' : ""} />`;
201
+ case "enum":
202
+ return [
203
+ `<enum id="${id}" valueName="${element.name}" required="true">`,
204
+ ...element.items.map(
205
+ (item) =>
206
+ ` <item displayName="$(string.${id}_${item.value})"><value><string>${item.value}</string></value></item>`,
207
+ ),
208
+ "</enum>",
209
+ ].join("\n ");
210
+ case "checkbox":
211
+ return `<boolean id="${id}"${
212
+ element.list === undefined ? "" : ` key="${ADMX_KEY}\\${element.list}"`
213
+ } valueName="${escapeXml(element.name)}"><trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue></boolean>`;
214
+ }
215
+};
216
+
217
+/** The language-neutral Group Policy template. */
218
+export function windowsAdmx(): string {
219
+ const body = policies().map((policy) => {
220
+ const head = `<policy name="${policy.id}" class="Machine" displayName="$(string.${policy.id})" explainText="$(string.${policy.id}_Help)" key="${ADMX_KEY}"`;
221
+ const common = `<parentCategory ref="T3Code" />\n <supportedOn ref="SUPPORTED_T3Code" />`;
222
+ if (policy.toggle !== undefined) {
223
+ return ` ${head} valueName="${policy.toggle}">
224
+ ${common}
225
+ <enabledValue><decimal value="1" /></enabledValue>
226
+ <disabledValue><decimal value="0" /></disabledValue>
227
+ </policy>`;
228
+ }
229
+ const grouped = Object.hasOwn(WINDOWS_POLICY_GROUPS, policy.id);
230
+ return ` ${head}${grouped ? ` valueName="${policy.id}"` : ""} presentation="$(presentation.${policy.id})">
231
+ ${common}${grouped ? '\n <enabledValue><decimal value="1" /></enabledValue>\n <disabledValue><decimal value="0" /></disabledValue>' : ""}
232
+ <elements>
233
+ ${(policy.elements ?? []).map(admxElement).join("\n ")}
234
+ </elements>
235
+ </policy>`;
236
+ });
237
+ return `<?xml version="1.0" encoding="utf-8"?>
238
+<policyDefinitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.0" schemaVersion="1.0" xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions">
239
+ <policyNamespaces>
240
+ <target prefix="t3code" namespace="T3Tools.Policies.T3Code" />
241
+ </policyNamespaces>
242
+ <resources minRequiredRevision="1.0" />
243
+ <supportedOn>
244
+ <definitions>
245
+ <definition name="SUPPORTED_T3Code" displayName="$(string.SUPPORTED_T3Code)" />
246
+ </definitions>
247
+ </supportedOn>
248
+ <categories>
249
+ <category name="T3Code" displayName="$(string.T3Code)" />
250
+ </categories>
251
+ <policies>
252
+${body.join("\n")}
253
+ </policies>
254
+</policyDefinitions>
255
+`;
256
+}
257
+
258
+const presentationElement = (element: Element) => {
259
+ const id = elementId(element);
260
+ switch (element.kind) {
261
+ case "text":
262
+ return `<textBox refId="${id}"><label>${escapeXml(element.label)}</label></textBox>`;
263
+ case "enum":
264
+ return `<dropdownList refId="${id}" noSort="true" defaultItem="${element.defaultItem}">${escapeXml(element.label)}</dropdownList>`;
265
+ case "checkbox":
266
+ return `<checkBox refId="${id}" defaultChecked="${element.defaultChecked}">${escapeXml(element.label)}</checkBox>`;
267
+ }
268
+};
269
+
270
+/** The en-US strings and dialog layouts for `windowsAdmx`. */
271
+export function windowsAdml(): string {
272
+ const strings: Array<readonly [string, string]> = [
273
+ ["T3Code", "T3 Code"],
274
+ ["SUPPORTED_T3Code", "T3 Code with managed policy support"],
275
+ ];
276
+ const presentations: Array<string> = [];
277
+ for (const policy of policies()) {
278
+ strings.push([policy.id, policy.title], [`${policy.id}_Help`, policy.help]);
279
+ for (const element of policy.elements ?? []) {
280
+ if (element.kind === "enum") {
281
+ for (const item of element.items) {
282
+ strings.push([`${elementId(element)}_${item.value}`, item.label]);
283
+ }
284
+ }
285
+ }
286
+ if (policy.elements !== undefined) {
287
+ presentations.push(
288
+ ` <presentation id="${policy.id}">\n ${policy.elements.map(presentationElement).join("\n ")}\n </presentation>`,
289
+ );
290
+ }
291
+ }
292
+ return `<?xml version="1.0" encoding="utf-8"?>
293
+<policyDefinitionResources xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.0" schemaVersion="1.0" xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions">
294
+ <displayName>T3 Code</displayName>
295
+ <description>Policies for T3 Code</description>
296
+ <resources>
297
+ <stringTable>
298
+${strings.map(([id, text]) => ` <string id="${id}">${escapeXml(text)}</string>`).join("\n")}
299
+ </stringTable>
300
+ <presentationTable>
301
+${presentations.join("\n")}
302
+ </presentationTable>
303
+ </resources>
304
+</policyDefinitionResources>
305
+`;
306
+}
307
+
308
+const plistValue = (value: unknown, indent: string): string => {
309
+ const inner = `${indent} `;
310
+ if (typeof value === "string") return `${indent}<string>${escapeXml(value)}</string>`;
311
+ if (typeof value === "boolean") return `${indent}<${value} />`;
312
+ if (typeof value === "number") {
313
+ return Number.isInteger(value)
314
+ ? `${indent}<integer>${value}</integer>`
315
+ : `${indent}<real>${value}</real>`;
316
+ }
317
+ if (Array.isArray(value)) {
318
+ return `${indent}<array>\n${value.map((item) => plistValue(item, inner)).join("\n")}\n${indent}</array>`;
319
+ }
320
+ const entries = Object.entries(value as Record<string, unknown>);
321
+ return `${indent}<dict>\n${entries
322
+ .map(([key, item]) => `${inner}<key>${escapeXml(key)}</key>\n${plistValue(item, inner)}`)
323
+ .join("\n")}\n${indent}</dict>`;
324
+};
325
+
326
+/** Where `value` holds a `null`, as path segments, or undefined when it holds none. */
327
+const nullPath = (
328
+ value: unknown,
329
+ path: ReadonlyArray<string>,
330
+): ReadonlyArray<string> | undefined => {
331
+ if (value === null) return path;
332
+ if (typeof value !== "object") return undefined;
333
+ for (const [key, item] of Object.entries(value)) {
334
+ const found = nullPath(item, [...path, key]);
335
+ if (found !== undefined) return found;
336
+ }
337
+ return undefined;
338
+};
339
+
340
+/** A device configuration profile that installs `document` for `com.t3tools.t3code`. */
341
+export function macosProfile(
342
+ document: ManagedPolicyDocument,
343
+ uuids: { readonly profile: string; readonly payload: string },
344
+):
345
+ | { readonly _tag: "Valid"; readonly profile: string }
346
+ | { readonly _tag: "Invalid"; readonly reason: string } {
347
+ // A plist has no null, and a setting may be locked empty.
348
+ const empty = nullPath(document, []);
349
+ if (empty !== undefined) {
350
+ const setting =
351
+ empty[0] === "settings" && empty.at(-1) === "value" ? empty.slice(0, -1) : empty;
352
+ return {
353
+ _tag: "Invalid",
354
+ reason: `${setting.join(".")} is null, which a configuration profile cannot hold; deploy this policy as a file.`,
355
+ };
356
+ }
357
+ const profile = {
358
+ PayloadContent: [
359
+ {
360
+ PayloadDisplayName: "T3 Code policy",
361
+ PayloadIdentifier: `com.t3tools.t3code.policy.${uuids.payload}`,
362
+ PayloadType: "com.t3tools.t3code",
363
+ PayloadUUID: uuids.payload,
364
+ PayloadVersion: 1,
365
+ ...document,
366
+ },
367
+ ],
368
+ PayloadDescription: "Configures T3 Code for every user on this Mac.",
369
+ PayloadDisplayName: `T3 Code policy for ${document.organization}`,
370
+ PayloadIdentifier: `com.t3tools.t3code.policy`,
371
+ PayloadOrganization: document.organization,
372
+ PayloadScope: "System",
373
+ PayloadType: "Configuration",
374
+ PayloadUUID: uuids.profile,
375
+ PayloadVersion: 1,
376
+ };
377
+ return {
378
+ _tag: "Valid",
379
+ profile: `<?xml version="1.0" encoding="UTF-8"?>
380
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
381
+<plist version="1.0">
382
+${plistValue(profile, "")}
383
+</plist>
384
+`,
385
+ };
386
+}
docs/user/managed-policy.md
+28
-11
@@ -46,11 +46,11 @@ Every user on the machine can read the policy, so do not put credentials in it.
46
47
Use one of these per machine:
48
49
-| OS | Native policy | Policy file |
50
-| ------- | ------------------------------------------------------------------- | ------------------------------------------------- |
51
-| macOS | Configuration profile for `com.t3tools.t3code` | `/Library/Application Support/T3Code/policy.json` |
52
-| Windows | `Policy` string value under `HKLM\SOFTWARE\Policies\T3Tools\T3Code` | `C:\Program Files\T3Code\policy.json` |
53
-| Linux | | `/etc/t3code/policy.json` |
49
+| OS | Native policy | Policy file |
50
+| ------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
51
+| macOS | Configuration profile for `com.t3tools.t3code` | `/Library/Application Support/T3Code/policy.json` |
52
+| Windows | Group Policy template, or a `Policy` JSON value (both under `HKLM\SOFTWARE\Policies\T3Tools\T3Code`) | `C:\Program Files\T3Code\policy.json` |
53
+| Linux | | `/etc/t3code/policy.json` |
54
55
T3 Code does not merge sources. If a machine has both a native policy and a policy file, T3 Code
56
refuses to start until you remove one.
@@ -62,14 +62,28 @@ administrators.
62
`com.t3tools.t3code`. The payload's keys are the policy's top-level keys (`schemaVersion`,
63
`organization`, `supportUrl`, `settings`, `limits`); JSON objects become dictionaries and lists
64
become arrays. To make the payload from a policy file you checked, run
65
-`plutil -convert xml1 -o com.t3tools.t3code.plist policy.json` and upload the result. Install it as
65
+`plutil -convert xml1 -o com.t3tools.t3code.plist policy.json` and upload the result, or run
66
+`t3 policy templates <directory> --policy policy.json` to write a complete
67
+`macos/t3code.mobileconfig`. Install it as
68
a device profile, since T3 Code ignores user profiles, and deploy only one profile for this domain.
69
A profile cannot hold `null`, so use a policy file if a setting's value must be `null`.
70
69
-**Windows registry.** Set the `Policy` value (`REG_SZ`) to the whole policy as one line of JSON,
71
+**Windows Group Policy.** Run `t3 policy templates <directory>` and copy
72
+`windows/t3code.admx` and `windows/en-US/t3code.adml` into your `PolicyDefinitions` folder or
73
+central store, or import them into Intune. The policies appear under Computer Configuration >
74
+Administrative Templates > T3 Code. Set **Organization** whenever you set any other T3 Code policy.
75
+Locks and provider fields go in the two JSON policies, as the same objects a policy file would hold.
76
+Machines pick up a change at the next Group Policy refresh; run `gpupdate /target:computer /force`
77
+to apply it now, then restart T3 Code.
78
+Setting **Allow T3 Connect**, **Allow webhook tasks**, **Allow importing browser cookies**, or
79
+**Allow usage data** to **Disabled** turns that feature off. Setting any other T3 Code policy to
80
+**Disabled** restricts nothing, the same as **Not Configured**.
81
+
82
+**Windows registry value.** Instead of the template, set the `Policy` value (`REG_SZ`) to the whole policy as one line of JSON,
83
from Group Policy Preferences or an Intune script. T3 Code reads it through the Windows registry
71
-API, so it works where registry tools such as `reg.exe` are blocked for users. In PowerShell, as an
72
-administrator:
84
+API, so it works where registry tools such as `reg.exe` are blocked for users. Use one or the other:
85
+T3 Code refuses to start when the key holds both a `Policy` value and the template's settings. In
86
+PowerShell, as an administrator:
87
88
```powershell
89
$json = (Get-Content -Raw -Encoding UTF8 policy.json) -replace '\r?\n\s*', ''
@@ -92,7 +106,8 @@ reopen the desktop app, or run `t3 service restart` for the
106
[background service](./background-service.md). Reconnecting a phone or browser does not reload the
107
policy.
108
95
-To remove a policy, delete the file, remove the profile, or delete the registry value, then restart
109
+To remove a policy, delete the file, remove the profile, set the Group Policy settings to
110
+**Not Configured**, or delete the registry value, then restart
111
the server. Users get back the settings they had chosen, since T3 Code never writes policy values
112
into them.
113
@@ -104,7 +119,9 @@ version does not support, or a machine with both a native policy and a file. The
119
the policy came from and what is wrong.
120
121
`t3 policy check` catches the same problems in a JSON file. For a profile or registry value, check
107
-the JSON before you convert it. A policy written for a newer version can use keys an older one
122
+the JSON before you convert it. For the Group Policy template, check a complete policy file that
123
+holds the same settings, then paste its `settings` and `limits.providers.instances` objects into the
124
+two JSON policies. A policy written for a newer version can use keys an older one
125
cannot enforce, so upgrade T3 Code before you deploy a policy that uses them.
126
127
## Settings
packages/shared/src/managedPolicyFile.test.ts
+194
-30
@@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
2
import * as Effect from "effect/Effect";
3
import * as FileSystem from "effect/FileSystem";
4
import * as Layer from "effect/Layer";
5
+import * as Schema from "effect/Schema";
6
import * as Sink from "effect/Sink";
7
import * as Stream from "effect/Stream";
8
import { ChildProcessSpawner } from "effect/process";
@@ -12,6 +13,7 @@ import {
13
MACOS_MANAGED_PREFERENCES_PATH,
14
managedPolicyPath,
15
readManagedPolicy,
16
+ type RegistryKey,
17
WINDOWS_POLICY_KEY,
18
layerWindowsRegistry,
19
WindowsRegistry,
@@ -23,8 +25,10 @@ const policy = JSON.stringify({ schemaVersion: 1, organization: "Example Corp" }
25
/** What a command prints and exits with. */
26
type Result = { readonly stdout: string; readonly exitCode: number };
27
26
-/** The registry's `Policy` value: its text, absent, or the Win32 error reading it fails with. */
27
-type RegistryAnswer = string | undefined | { readonly code?: number };
28
+/** Keys below the policy key ("" for the key itself), or the error every read fails with. */
29
+type RegistryAnswer = Readonly<Record<string, RegistryKey>> | WindowsRegistryError;
30
+const isRegistryError = Schema.is(WindowsRegistryError);
31
+const POLICY_SUBKEY = WINDOWS_POLICY_KEY.slice("HKLM\\".length);
32
33
/** Files that exist, what a command prints and exits with by command name, and the registry. */
34
const machine = (
@@ -36,10 +40,10 @@ const machine = (
40
Layer.succeed(
41
WindowsRegistry,
42
WindowsRegistry.of({
39
- readMachineString: () =>
40
- typeof registry === "object"
41
- ? Effect.fail(new WindowsRegistryError(registry))
42
- : Effect.succeed(registry),
43
+ readMachineKey: (subkey) =>
44
+ isRegistryError(registry)
45
+ ? Effect.fail(registry)
46
+ : Effect.succeed(registry[subkey.slice(POLICY_SUBKEY.length + 1)]),
47
}),
48
),
49
FileSystem.layerNoop({
@@ -70,11 +74,34 @@ const machine = (
74
),
75
);
76
77
+/** A policy key holding `values`, with checkbox subkeys of `name=0|1` entries. */
78
+const policyKey = (
79
+ values: RegistryKey["values"],
80
+ subkeys: Readonly<Record<string, Readonly<Record<string, number>>>> = {},
81
+): Readonly<Record<string, RegistryKey>> => ({
82
+ "": { values, subkeys: Object.keys(subkeys) },
83
+ ...Object.fromEntries(
84
+ Object.entries(subkeys).map(([name, boxes]) => [
85
+ name,
86
+ {
87
+ values: Object.entries(boxes).map(([box, data]) => ({
88
+ name: box,
89
+ type: "REG_DWORD" as const,
90
+ data,
91
+ })),
92
+ subkeys: [],
93
+ },
94
+ ]),
95
+ ),
96
+});
97
+const text = (name: string, data: string) => ({ name, type: "REG_SZ" as const, data });
98
+const dword = (name: string, data: number) => ({ name, type: "REG_DWORD" as const, data });
99
+
100
const read = (
101
platform: NodeJS.Platform,
102
files: Readonly<Record<string, string>>,
103
commands: Parameters<typeof machine>[1] = {},
77
- registry: RegistryAnswer = undefined,
104
+ registry: RegistryAnswer = {},
105
) =>
106
readManagedPolicy(platform).pipe(
107
Effect.map((found) => found?.source),
@@ -139,52 +166,189 @@ describe("readManagedPolicy", () => {
166
);
167
168
it.effect(
142
- "reads the Windows Policies registry value, and treats only an absent one as none",
169
+ "reads a Policy value of JSON from the registry, and treats only an absent key as none",
170
() =>
171
Effect.gen(function* () {
172
const file = { [managedPolicyPath("win32")]: policy };
173
const win32 = (files: Readonly<Record<string, string>>, registry: RegistryAnswer) =>
174
read("win32", files, {}, registry);
175
+ const json = policyKey([text("Policy", policy)]);
176
149
- assert.equal(yield* win32({}, policy), WINDOWS_POLICY_KEY);
150
- assert.isUndefined(yield* win32({}, undefined));
151
- assert.equal(yield* win32(file, undefined), managedPolicyPath("win32"));
152
- assert.include(yield* win32(file, policy), "deploy the policy one way");
177
+ assert.equal(yield* win32({}, json), WINDOWS_POLICY_KEY);
178
+ assert.isUndefined(yield* win32({}, {}));
179
+ assert.equal(yield* win32(file, {}), managedPolicyPath("win32"));
180
+ assert.include(yield* win32(file, json), "deploy the policy one way");
181
// A read that fails, here access denied, is not read as no policy, file or not.
182
for (const files of [{}, file]) {
183
assert.include(
156
- yield* win32(files, { code: 5 }),
184
+ yield* win32(files, new WindowsRegistryError({ code: 5 })),
185
"the registry cannot be read (Windows error 5)",
186
);
187
}
160
- assert.include(yield* win32({}, {}), "cannot load its registry reader; reinstall T3 Code");
188
assert.include(
162
- yield* win32({}, { code: 1630 }),
189
+ yield* win32({}, new WindowsRegistryError({})),
190
+ "cannot load its registry reader; reinstall T3 Code",
191
+ );
192
+ assert.include(
193
+ yield* win32({}, policyKey([{ name: "Policy", type: "other" }])),
194
"its Policy value is not a string (REG_SZ)",
195
);
165
- assert.include(yield* win32({}, "{ not json"), "does not match the policy schema");
196
+ assert.include(
197
+ yield* win32({}, policyKey([text("Policy", "{ not json")])),
198
+ "does not match the policy schema",
199
+ );
200
+ for (const both of [
201
+ policyKey([text("Policy", policy), text("Organization", "Example")]),
202
+ policyKey([text("Policy", policy)], { Clients: { desktop: 1 } }),
203
+ ]) {
204
+ assert.include(yield* win32({}, both), "both a Policy value and Group Policy settings");
205
+ }
206
+ // Not Configured clears a list policy's values but can leave its empty subkey behind.
207
+ assert.equal(
208
+ yield* win32({}, policyKey([text("Policy", policy)], { Clients: {} })),
209
+ WINDOWS_POLICY_KEY,
210
+ );
211
}),
212
);
213
214
+ it.effect("builds the policy from the values the Group Policy template writes", () =>
215
+ Effect.gen(function* () {
216
+ const organization = text("Organization", "Société 日本 ✓");
217
+ const document = (registry: RegistryAnswer) =>
218
+ readManagedPolicy("win32", ["codex", "claudeAgent"]).pipe(
219
+ Effect.map((found): unknown => found?.document),
220
+ Effect.catchTags({
221
+ ManagedPolicyFileError: (error) => Effect.succeed(`error: ${error.reason}`),
222
+ }),
223
+ Effect.provide(machine({}, {}, registry)),
224
+ );
225
+
226
+ assert.deepStrictEqual(
227
+ yield* document(
228
+ policyKey(
229
+ [
230
+ organization,
231
+ text("SupportUrl", ""),
232
+ // Registry names ignore case.
233
+ text("maxRuntimeMode", "auto-accept-edits"),
234
+ dword("Telemetry", 0),
235
+ text("Settings", '{"enableAgentBrowserAccess": {"value": false, "locked": true}}'),
236
+ text("UpdatesMode", "off"),
237
+ dword("AllowNightly", 1),
238
+ dword("Updates", 1),
239
+ dword("Clients", 1),
240
+ dword("AllowedDrivers", 1),
241
+ ],
242
+ // Registry names ignore case, so a subkey written in other case still counts.
243
+ {
244
+ clients: { Desktop: 1, "LOCAL-BROWSER": 1, REMOTE: 1 },
245
+ AllowedDrivers: { Codex: 1, CLAUDEAGENT: 1, UnknownDriver: 1 },
246
+ },
247
+ ),
248
+ ),
249
+ {
250
+ schemaVersion: 1,
251
+ organization: "Société 日本 ✓",
252
+ settings: { enableAgentBrowserAccess: { value: false, locked: true } },
253
+ limits: {
254
+ maxRuntimeMode: "auto-accept-edits",
255
+ telemetry: false,
256
+ updates: { mode: "off", allowNightly: true },
257
+ clients: ["desktop", "local-browser", "remote"],
258
+ providers: { allowedDrivers: ["codex", "claudeAgent", "UnknownDriver"] },
259
+ },
260
+ },
261
+ );
262
+
263
+ // Disabling a policy leaves each checkbox's falseValue behind; it restricts nothing.
264
+ const disabledGroups = {
265
+ Clients: { desktop: 0, "local-browser": 0, remote: 0 },
266
+ AllowedDrivers: { codex: 0, claudeAgent: 0 },
267
+ };
268
+ assert.deepStrictEqual(
269
+ yield* document(
270
+ policyKey(
271
+ [
272
+ organization,
273
+ dword("Clients", 0),
274
+ dword("AllowedDrivers", 0),
275
+ dword("Updates", 0),
276
+ dword("AllowNightly", 0),
277
+ dword("Telemetry", 0),
278
+ ],
279
+ disabledGroups,
280
+ ),
281
+ ),
282
+ { schemaVersion: 1, organization: "Société 日本 ✓", limits: { telemetry: false } },
283
+ );
284
+ // With nothing else configured, that is no policy rather than one missing Organization.
285
+ assert.isUndefined(
286
+ yield* document(
287
+ policyKey([dword("AllowedDrivers", 0)], {
288
+ AllowedDrivers: disabledGroups.AllowedDrivers,
289
+ }),
290
+ ),
291
+ );
292
+ assert.isUndefined(yield* document(policyKey([])));
293
+
294
+ // Anything the template does not write fails closed rather than being ignored.
295
+ for (const [registry, reason] of [
296
+ [policyKey([organization, dword("Telemetry", 2)]), "DWORD of 0 or 1"],
297
+ [policyKey([organization, text("MaxMode", "auto")]), "not a T3 Code policy value"],
298
+ [policyKey([organization], { Other: { x: 1 } }), "Other is not a T3 Code policy key"],
299
+ [
300
+ {
301
+ ...policyKey([organization, dword("Clients", 1)], { Clients: { desktop: 1 } }),
302
+ Clients: { values: [dword("desktop", 1)], subkeys: ["Nested"] },
303
+ },
304
+ "Clients\\Nested is not a T3 Code policy key",
305
+ ],
306
+ [policyKey([organization, text("Settings", "{")]), "not valid JSON"],
307
+ [policyKey([organization, dword("Clients", 2)]), "DWORD of 0 or 1"],
308
+ [
309
+ policyKey([organization, dword("Clients", 1)], { Clients: { UnknownClient: 1 } }),
310
+ "does not match the policy schema",
311
+ ],
312
+ [
313
+ policyKey([organization, dword("Clients", 1)], { Clients: { desktop: 0 } }),
314
+ "does not match the policy schema",
315
+ ],
316
+ [policyKey([dword("Organization", 1)]), "Organization must be a string"],
317
+ // REG_EXPAND_SZ would fill in the reading user's variables.
318
+ [policyKey([{ name: "Organization", type: "other" }]), "Organization must be a string"],
319
+ [
320
+ policyKey([text("MaxRuntimeMode", "auto-accept-edits")]),
321
+ "set the Organization policy whenever another T3 Code policy is set",
322
+ ],
323
+ ] as const) {
324
+ assert.include(yield* document(registry), reason);
325
+ }
326
+ }),
327
+ );
328
+
329
it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
170
- "reads REG_SZ values through the Win32 API, and refuses other types",
330
+ "lists registry values and subkeys through the Win32 API",
331
() =>
332
Effect.gen(function* () {
333
const registry = yield* WindowsRegistry;
174
- const version = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
175
- assert.match((yield* registry.readMachineString(version, "ProductName")) ?? "", /Windows/);
176
- assert.isUndefined(yield* registry.readMachineString(version, "T3CodeNoSuchValue"));
177
- assert.isUndefined(
178
- yield* registry.readMachineString("SOFTWARE\\T3CodeNoSuchKey", "Policy"),
334
+ const version = yield* registry.readMachineKey(
335
+ "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
336
);
180
- // REG_DWORD, and REG_EXPAND_SZ, which would otherwise expand the user's variables.
181
- for (const [key, value] of [
182
- [version, "CurrentMajorVersionNumber"],
183
- ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProgramFilesPath"],
184
- ] as const) {
185
- const error = yield* registry.readMachineString(key, value).pipe(Effect.flip);
186
- assert.equal(error.code, 1630);
187
- }
337
+ const value = (name: string) => version?.values.find((entry) => entry.name === name);
338
+ const product = value("ProductName");
339
+ assert.match(product?.type === "REG_SZ" ? product.data : "", /Windows/);
340
+ assert.equal(value("CurrentMajorVersionNumber")?.type, "REG_DWORD");
341
+ assert.isUndefined(yield* registry.readMachineKey("SOFTWARE\\T3CodeNoSuchKey"));
342
+ const windows = yield* registry.readMachineKey(
343
+ "SOFTWARE\\Microsoft\\Windows\\CurrentVersion",
344
+ );
345
+ // REG_EXPAND_SZ, which would otherwise expand the user's variables.
346
+ assert.equal(
347
+ windows?.values.find((entry) => entry.name === "ProgramFilesPath")?.type,
348
+ "other",
349
+ );
350
+ const parent = yield* registry.readMachineKey("SOFTWARE\\Microsoft\\Windows NT");
351
+ assert.isTrue(parent?.subkeys.includes("CurrentVersion"));
352
}).pipe(Effect.provide(layerWindowsRegistry(() => import("ffi-rs")))),
353
);
354
});
packages/shared/src/managedPolicyFile.ts
+339
-72
@@ -1,4 +1,8 @@
1
-import { ManagedPolicyDocument, SERVER_EXIT_CODE_MANAGED_POLICY } from "@t3tools/contracts";
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";
@@ -94,8 +98,41 @@ export const readManagedPolicyFile = Effect.fn("readManagedPolicyFile")(function
98
export const MACOS_MANAGED_PREFERENCES_PATH =
99
"/Library/Managed Preferences/com.t3tools.t3code.plist";
100
const WINDOWS_POLICY_SUBKEY = "SOFTWARE\\Policies\\T3Tools\\T3Code";
97
-/** The registry key Group Policy and Intune write to on Windows; `Policy` holds the JSON. */
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
+ 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`. */
127
+export 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.
132
+export 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.
137
const PLUTIL = "/usr/bin/plutil";
138
@@ -112,30 +149,50 @@ export class WindowsRegistryError extends Schema.TaggedError<WindowsRegistryErro
149
}
150
}
151
152
+/** A registry value; REG_EXPAND_SZ and every other type read as `other`. */
153
+export 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
+
158
+export interface RegistryKey {
159
+ readonly values: ReadonlyArray<RegistryValue>;
160
+ readonly subkeys: ReadonlyArray<string>;
161
+}
162
+
163
/**
116
- * Reads the registry through the Win32 API in this process. A missing value and a failed read
117
- * come back apart, and blocked registry tools such as reg.exe do not matter.
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
*/
167
export class WindowsRegistry extends Context.Service<
168
WindowsRegistry,
169
{
122
- /** The REG_SZ `value` of HKLM\\`subkey` in the 64-bit view; undefined when either is absent. */
123
- readonly readMachineString: (
170
+ /** The values and subkey names of HKLM\\`subkey` in the 64-bit view; undefined when absent. */
171
+ readonly readMachineKey: (
172
subkey: string,
125
- value: string,
126
- ) => Effect.Effect<string | undefined, WindowsRegistryError>;
173
+ ) => Effect.Effect<RegistryKey | undefined, WindowsRegistryError>;
174
}
175
>()("@t3tools/shared/managedPolicyFile/WindowsRegistry") {}
176
177
// (HKEY)(LONG)0x80000002, sign-extended to 64 bits.
178
const HKEY_LOCAL_MACHINE = -0x7ffffffen;
132
-const RRF_RT_REG_SZ = 0x2;
133
-const RRF_SUBKEY_WOW6464KEY = 0x10000;
134
-// Without it a REG_EXPAND_SZ value passes as REG_SZ, with the user's variables filled in.
135
-const RRF_NOEXPAND = 0x10000000;
179
+const KEY_READ = 0x20019;
180
+const KEY_WOW64_64KEY = 0x100;
181
+const REG_SZ = 1;
182
+const REG_DWORD = 4;
183
const ERROR_FILE_NOT_FOUND = 2;
184
const ERROR_MORE_DATA = 234;
138
-const ERROR_UNSUPPORTED_TYPE = 1630;
185
+const ERROR_NO_MORE_ITEMS = 259;
186
+// Value and key names are at most 16,383 characters.
187
+const MAX_NAME_CHARS = 16_384;
188
+
189
+class Win32Failure extends Error {
190
+ readonly code: number;
191
+ constructor(code: number) {
192
+ super(`Windows error ${code}`);
193
+ this.code = code;
194
+ }
195
+}
196
197
/**
198
* Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only
@@ -146,67 +203,129 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-r
203
WindowsRegistry,
204
Effect.gen(function* () {
205
const architecture = yield* HostProcess.Architecture;
149
- const loadGetValue = yield* Effect.cached(
206
+ const loadApi = yield* Effect.cached(
207
Effect.tryPromise({
208
try: async () => {
152
- // HKEY_LOCAL_MACHINE and the pointer arguments below are 64-bit.
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" });
158
- return (subkey: string, value: string, data: Buffer, size: Buffer): number =>
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",
161
- funcName: "RegGetValueW",
222
+ funcName,
223
retType: DataType.I32,
163
- paramsType: [
164
- DataType.BigInt,
165
- DataType.WString,
166
- DataType.WString,
167
- DataType.U32,
168
- DataType.BigInt,
169
- DataType.U8Array,
170
- DataType.U8Array,
171
- ],
172
- paramsValue: [
173
- HKEY_LOCAL_MACHINE,
174
- subkey,
175
- value,
176
- RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY | RRF_NOEXPAND,
177
- 0n,
178
- data,
179
- size,
180
- ],
181
- });
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({
187
- readMachineString: Effect.fn("WindowsRegistry.readMachineString")(
188
- function* (subkey, value) {
189
- const getValue = yield* loadGetValue;
190
- const attempt = (bytes: number) =>
191
- Effect.try({
192
- try: () => {
193
- const data = Buffer.alloc(bytes);
194
- const size = Buffer.alloc(4);
195
- size.writeUInt32LE(bytes);
196
- const code = getValue(subkey, value, data, size);
197
- return { code, data, bytes: size.readUInt32LE() };
198
- },
199
- catch: (cause) => new WindowsRegistryError({ cause }),
200
- });
201
- let result = yield* attempt(64 * 1024);
202
- // The value grew past the buffer; the API reported the size it needs.
203
- if (result.code === ERROR_MORE_DATA) result = yield* attempt(result.bytes);
204
- if (result.code === ERROR_FILE_NOT_FOUND) return undefined;
205
- if (result.code !== 0) return yield* new WindowsRegistryError({ code: result.code });
206
- // The size counts the terminating null RegGetValueW adds.
207
- return result.data.subarray(0, result.bytes).toString("utf16le").replace(/\0+$/, "");
208
- },
209
- ),
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
);
@@ -229,6 +348,115 @@ const run = Effect.fnUntraced(
348
);
349
350
const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
351
+type PolicyRegistryValue = RegistryValue & {
352
+ /** The list subkey the value sits in, or "" for the policy key itself. */
353
+ readonly key: string;
354
+};
355
+
356
+const 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
+
364
+const 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
+ */
377
+function 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 };
458
+}
459
+
460
// Strict: keys beside the wrapper, or more than one entry, decode as a plain document and fail.
461
const decodeForcedExit = Schema.decodeUnknownExit(
462
Schema.Struct({
@@ -261,7 +489,10 @@ function unwrapForced(json: string): unknown {
489
}
490
491
/** Read the policy a configuration profile or Group Policy set; absent means no such policy. */
264
-const readPlatformPolicy = Effect.fnUntraced(function* (platform: NodeJS.Platform) {
492
+const 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)
@@ -286,26 +517,61 @@ const readPlatformPolicy = Effect.fnUntraced(function* (platform: NodeJS.Platfor
517
}
518
if (platform === "win32") {
519
const path = WINDOWS_POLICY_KEY;
289
- const raw = yield* (yield* WindowsRegistry)
290
- .readMachineString(WINDOWS_POLICY_SUBKEY, "Policy")
291
- .pipe(
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:
297
- cause.code === ERROR_UNSUPPORTED_TYPE
298
- ? "its Policy value is not a string (REG_SZ)"
299
- : cause.code === undefined
300
- ? "this T3 Code install cannot load its registry reader; reinstall T3 Code"
301
- : `the registry cannot be read (${cause.message})`,
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
);
306
- return raw === undefined
307
- ? undefined
308
- : { source: path, document: yield* decodeDocument(path, raw) };
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
});
@@ -317,10 +583,11 @@ const readPlatformPolicy = Effect.fnUntraced(function* (platform: NodeJS.Platfor
583
*/
584
export 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([
323
- readPlatformPolicy(platform),
590
+ readPlatformPolicy(platform, knownDrivers),
591
readManagedPolicyFile(filePath),
592
]);
593
if (platformPolicy !== undefined && file !== undefined) {