Open History to see the last commit
1import type { ManagedPolicyDocument } from "@t3tools/contracts";
2import {
3 WINDOWS_POLICY_KEY,
4 WINDOWS_POLICY_GROUPS,
5 WINDOWS_POLICY_LISTS,
6 WINDOWS_POLICY_VALUES,
7} from "@t3tools/shared/managedPolicyFile";
8
9import { knownDriverLabels } from "./managedProviders.ts";
10
11type ValueName = keyof typeof WINDOWS_POLICY_VALUES;
12type ListKey = keyof typeof WINDOWS_POLICY_LISTS;
13
14type 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
36interface 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
45const 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
52const 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: "PreviewTunnel",
124 title: "Allow the preview tunnel",
125 help: "Disabled stops other devices from opening this machine's local servers through T3 Code: no in-app browser tabs loaded on the device, no Open on this device, no port forwarding. Browser tabs still stream from this machine.",
126 toggle: "PreviewTunnel",
127 },
128 {
129 id: "WorktreeLayoutCommands",
130 title: "Allow project worktree layout commands",
131 help: "Disabled stops T3 Code from running the worktreeLayout commands a project's t3.json declares, whether or not a user approved them. Such a project gets no new worktree threads; existing thread folders are restored and removed without the project's commands.",
132 toggle: "WorktreeLayoutCommands",
133 },
134 {
135 id: "Telemetry",
136 title: "Allow usage data",
137 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.",
138 toggle: "Telemetry",
139 },
140 {
141 id: "AllowedDrivers",
142 title: "Allowed providers",
143 help: "Only the checked providers may run. Threads on other providers stay, marked unavailable.\n\nDisabled or Not Configured: no restriction.",
144 elements: knownDriverLabels().map(({ driver, label }) => ({
145 kind: "checkbox" as const,
146 list: "AllowedDrivers" as const,
147 name: driver,
148 label,
149 defaultChecked: driver === "codex" || driver === "claudeAgent",
150 })),
151 },
152 {
153 id: "Updates",
154 title: "Updates",
155 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.",
156 elements: [
157 {
158 kind: "enum",
159 name: "UpdatesMode",
160 label: "Updates",
161 items: [
162 { value: "auto", label: "Automatic" },
163 { value: "off", label: "Off" },
164 ],
165 defaultItem: 0,
166 },
167 { kind: "text", name: "UpdatesFeedUrl", label: "Feed URL (optional)" },
168 {
169 kind: "checkbox",
170 name: "AllowNightly",
171 label: "Allow the nightly channel",
172 defaultChecked: true,
173 },
174 ],
175 },
176 {
177 id: "Settings",
178 title: "Managed settings (JSON)",
179 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.',
180 elements: [{ kind: "text", name: "Settings", label: "Settings JSON", json: true }],
181 },
182 {
183 id: "ProviderInstances",
184 title: "Provider settings (JSON)",
185 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.',
186 elements: [
187 { kind: "text", name: "ProviderInstances", label: "Provider settings JSON", json: true },
188 ],
189 },
190];
191
192const escapeXml = (text: string) =>
193 text
194 .replaceAll("&", "&")
195 .replaceAll("<", "<")
196 .replaceAll(">", ">")
197 .replaceAll('"', """);
198
199// ADMX keys are relative to the hive the policy class picks.
200const ADMX_KEY = WINDOWS_POLICY_KEY.replace(/^HKLM\\/, "");
201const elementId = (element: Element) =>
202 element.kind === "checkbox" && element.list !== undefined
203 ? `${element.list}_${element.name}`
204 : element.name;
205
206const admxElement = (element: Element) => {
207 const id = elementId(element);
208 switch (element.kind) {
209 case "text":
210 return `<text id="${id}" valueName="${element.name}"${
211 element.name === "Organization" ? ' required="true"' : ""
212 }${element.json ? ' maxLength="32767"' : ""} />`;
213 case "enum":
214 return [
215 `<enum id="${id}" valueName="${element.name}" required="true">`,
216 ...element.items.map(
217 (item) =>
218 ` <item displayName="$(string.${id}_${item.value})"><value><string>${item.value}</string></value></item>`,
219 ),
220 "</enum>",
221 ].join("\n ");
222 case "checkbox":
223 return `<boolean id="${id}"${
224 element.list === undefined ? "" : ` key="${ADMX_KEY}\\${element.list}"`
225 } valueName="${escapeXml(element.name)}"><trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue></boolean>`;
226 }
227};
228
229/** The language-neutral Group Policy template. */
230export function windowsAdmx(): string {
231 const body = policies().map((policy) => {
232 const head = `<policy name="${policy.id}" class="Machine" displayName="$(string.${policy.id})" explainText="$(string.${policy.id}_Help)" key="${ADMX_KEY}"`;
233 const common = `<parentCategory ref="T3Code" />\n <supportedOn ref="SUPPORTED_T3Code" />`;
234 if (policy.toggle !== undefined) {
235 return ` ${head} valueName="${policy.toggle}">
236 ${common}
237 <enabledValue><decimal value="1" /></enabledValue>
238 <disabledValue><decimal value="0" /></disabledValue>
239 </policy>`;
240 }
241 const grouped = Object.hasOwn(WINDOWS_POLICY_GROUPS, policy.id);
242 return ` ${head}${grouped ? ` valueName="${policy.id}"` : ""} presentation="$(presentation.${policy.id})">
243 ${common}${grouped ? '\n <enabledValue><decimal value="1" /></enabledValue>\n <disabledValue><decimal value="0" /></disabledValue>' : ""}
244 <elements>
245 ${(policy.elements ?? []).map(admxElement).join("\n ")}
246 </elements>
247 </policy>`;
248 });
249 return `<?xml version="1.0" encoding="utf-8"?>
250<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">
251 <policyNamespaces>
252 <target prefix="t3code" namespace="T3Tools.Policies.T3Code" />
253 </policyNamespaces>
254 <resources minRequiredRevision="1.0" />
255 <supportedOn>
256 <definitions>
257 <definition name="SUPPORTED_T3Code" displayName="$(string.SUPPORTED_T3Code)" />
258 </definitions>
259 </supportedOn>
260 <categories>
261 <category name="T3Code" displayName="$(string.T3Code)" />
262 </categories>
263 <policies>
264${body.join("\n")}
265 </policies>
266</policyDefinitions>
267`;
268}
269
270const presentationElement = (element: Element) => {
271 const id = elementId(element);
272 switch (element.kind) {
273 case "text":
274 return `<textBox refId="${id}"><label>${escapeXml(element.label)}</label></textBox>`;
275 case "enum":
276 return `<dropdownList refId="${id}" noSort="true" defaultItem="${element.defaultItem}">${escapeXml(element.label)}</dropdownList>`;
277 case "checkbox":
278 return `<checkBox refId="${id}" defaultChecked="${element.defaultChecked}">${escapeXml(element.label)}</checkBox>`;
279 }
280};
281
282/** The en-US strings and dialog layouts for `windowsAdmx`. */
283export function windowsAdml(): string {
284 const strings: Array<readonly [string, string]> = [
285 ["T3Code", "T3 Code"],
286 ["SUPPORTED_T3Code", "T3 Code with managed policy support"],
287 ];
288 const presentations: Array<string> = [];
289 for (const policy of policies()) {
290 strings.push([policy.id, policy.title], [`${policy.id}_Help`, policy.help]);
291 for (const element of policy.elements ?? []) {
292 if (element.kind === "enum") {
293 for (const item of element.items) {
294 strings.push([`${elementId(element)}_${item.value}`, item.label]);
295 }
296 }
297 }
298 if (policy.elements !== undefined) {
299 presentations.push(
300 ` <presentation id="${policy.id}">\n ${policy.elements.map(presentationElement).join("\n ")}\n </presentation>`,
301 );
302 }
303 }
304 return `<?xml version="1.0" encoding="utf-8"?>
305<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">
306 <displayName>T3 Code</displayName>
307 <description>Policies for T3 Code</description>
308 <resources>
309 <stringTable>
310${strings.map(([id, text]) => ` <string id="${id}">${escapeXml(text)}</string>`).join("\n")}
311 </stringTable>
312 <presentationTable>
313${presentations.join("\n")}
314 </presentationTable>
315 </resources>
316</policyDefinitionResources>
317`;
318}
319
320const plistValue = (value: unknown, indent: string): string => {
321 const inner = `${indent} `;
322 if (typeof value === "string") return `${indent}<string>${escapeXml(value)}</string>`;
323 if (typeof value === "boolean") return `${indent}<${value} />`;
324 if (typeof value === "number") {
325 return Number.isInteger(value)
326 ? `${indent}<integer>${value}</integer>`
327 : `${indent}<real>${value}</real>`;
328 }
329 if (Array.isArray(value)) {
330 return `${indent}<array>\n${value.map((item) => plistValue(item, inner)).join("\n")}\n${indent}</array>`;
331 }
332 const entries = Object.entries(value as Record<string, unknown>);
333 return `${indent}<dict>\n${entries
334 .map(([key, item]) => `${inner}<key>${escapeXml(key)}</key>\n${plistValue(item, inner)}`)
335 .join("\n")}\n${indent}</dict>`;
336};
337
338/** Where `value` holds a `null`, as path segments, or undefined when it holds none. */
339const nullPath = (
340 value: unknown,
341 path: ReadonlyArray<string>,
342): ReadonlyArray<string> | undefined => {
343 if (value === null) return path;
344 if (typeof value !== "object") return undefined;
345 for (const [key, item] of Object.entries(value)) {
346 const found = nullPath(item, [...path, key]);
347 if (found !== undefined) return found;
348 }
349 return undefined;
350};
351
352/** A device configuration profile that installs `document` for `com.t3tools.t3code`. */
353export function macosProfile(
354 document: ManagedPolicyDocument,
355 uuids: { readonly profile: string; readonly payload: string },
356):
357 | { readonly _tag: "Valid"; readonly profile: string }
358 | { readonly _tag: "Invalid"; readonly reason: string } {
359 // A plist has no null, and a setting may be locked empty.
360 const empty = nullPath(document, []);
361 if (empty !== undefined) {
362 const setting =
363 empty[0] === "settings" && empty.at(-1) === "value" ? empty.slice(0, -1) : empty;
364 return {
365 _tag: "Invalid",
366 reason: `${setting.join(".")} is null, which a configuration profile cannot hold; deploy this policy as a file.`,
367 };
368 }
369 const profile = {
370 PayloadContent: [
371 {
372 PayloadDisplayName: "T3 Code policy",
373 PayloadIdentifier: `com.t3tools.t3code.policy.${uuids.payload}`,
374 PayloadType: "com.t3tools.t3code",
375 PayloadUUID: uuids.payload,
376 PayloadVersion: 1,
377 ...document,
378 },
379 ],
380 PayloadDescription: "Configures T3 Code for every user on this Mac.",
381 PayloadDisplayName: `T3 Code policy for ${document.organization}`,
382 PayloadIdentifier: `com.t3tools.t3code.policy`,
383 PayloadOrganization: document.organization,
384 PayloadScope: "System",
385 PayloadType: "Configuration",
386 PayloadUUID: uuids.profile,
387 PayloadVersion: 1,
388 };
389 return {
390 _tag: "Valid",
391 profile: `<?xml version="1.0" encoding="UTF-8"?>
392<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
393<plist version="1.0">
394${plistValue(profile, "")}
395</plist>
396`,
397 };
398}