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

policyTemplates.ts

386 lines14.7 KB

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>;
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: "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​
180const escapeXml = (text: string) =>
181 text
182 .replaceAll("&", "&amp;")
183 .replaceAll("<", "&lt;")
184 .replaceAll(">", "&gt;")
185 .replaceAll('"', "&quot;");
186​
187// ADMX keys are relative to the hive the policy class picks.
188const ADMX_KEY = WINDOWS_POLICY_KEY.replace(/^HKLM\\/, "");
189const elementId = (element: Element) =>
190 element.kind === "checkbox" && element.list !== undefined
191 ? `${element.list}_${element.name}`
192 : element.name;
193​
194const 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. */
218export 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`;
257​
258const 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`. */
271export 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`;
307​
308const 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. */
327const 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`. */
341export 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 };