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

policyTemplates.ts

400 lines15.5 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: "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("&", "&amp;")
195 .replaceAll("<", "&lt;")
196 .replaceAll(">", "&gt;")
197 .replaceAll('"', "&quot;")
198 // XML parsers can normalize literal carriage returns before decoding text.
199 .replaceAll("\r", "&#13;");
200​
201// ADMX keys are relative to the hive the policy class picks.
202const ADMX_KEY = WINDOWS_POLICY_KEY.replace(/^HKLM\\/, "");
203const elementId = (element: Element) =>
204 element.kind === "checkbox" && element.list !== undefined
205 ? `${element.list}_${element.name}`
206 : element.name;
207​
208const admxElement = (element: Element) => {
209 const id = elementId(element);
210 switch (element.kind) {
211 case "text":
212 return `<text id="${id}" valueName="${element.name}"${
213 element.name === "Organization" ? ' required="true"' : ""
214 }${element.json ? ' maxLength="32767"' : ""} />`;
215 case "enum":
216 return [
217 `<enum id="${id}" valueName="${element.name}" required="true">`,
218 ...element.items.map(
219 (item) =>
220 ` <item displayName="$(string.${id}_${item.value})"><value><string>${item.value}</string></value></item>`,
221 ),
222 "</enum>",
223 ].join("\n ");
224 case "checkbox":
225 return `<boolean id="${id}"${
226 element.list === undefined ? "" : ` key="${ADMX_KEY}\\${element.list}"`
227 } valueName="${escapeXml(element.name)}"><trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue></boolean>`;
228 }
229};
230​
231/** The language-neutral Group Policy template. */
232export function windowsAdmx(): string {
233 const body = policies().map((policy) => {
234 const head = `<policy name="${policy.id}" class="Machine" displayName="$(string.${policy.id})" explainText="$(string.${policy.id}_Help)" key="${ADMX_KEY}"`;
235 const common = `<parentCategory ref="T3Code" />\n <supportedOn ref="SUPPORTED_T3Code" />`;
236 if (policy.toggle !== undefined) {
237 return ` ${head} valueName="${policy.toggle}">
238 ${common}
239 <enabledValue><decimal value="1" /></enabledValue>
240 <disabledValue><decimal value="0" /></disabledValue>
241 </policy>`;
242 }
243 const grouped = Object.hasOwn(WINDOWS_POLICY_GROUPS, policy.id);
244 return ` ${head}${grouped ? ` valueName="${policy.id}"` : ""} presentation="$(presentation.${policy.id})">
245 ${common}${grouped ? '\n <enabledValue><decimal value="1" /></enabledValue>\n <disabledValue><decimal value="0" /></disabledValue>' : ""}
246 <elements>
247 ${(policy.elements ?? []).map(admxElement).join("\n ")}
248 </elements>
249 </policy>`;
250 });
251 return `<?xml version="1.0" encoding="utf-8"?>
252<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">
253 <policyNamespaces>
254 <target prefix="t3code" namespace="T3Tools.Policies.T3Code" />
255 </policyNamespaces>
256 <resources minRequiredRevision="1.0" />
257 <supportedOn>
258 <definitions>
259 <definition name="SUPPORTED_T3Code" displayName="$(string.SUPPORTED_T3Code)" />
260 </definitions>
261 </supportedOn>
262 <categories>
263 <category name="T3Code" displayName="$(string.T3Code)" />
264 </categories>
265 <policies>
266${body.join("\n")}
267 </policies>
268</policyDefinitions>
269`;
271​
272const presentationElement = (element: Element) => {
273 const id = elementId(element);
274 switch (element.kind) {
275 case "text":
276 return `<textBox refId="${id}"><label>${escapeXml(element.label)}</label></textBox>`;
277 case "enum":
278 return `<dropdownList refId="${id}" noSort="true" defaultItem="${element.defaultItem}">${escapeXml(element.label)}</dropdownList>`;
279 case "checkbox":
280 return `<checkBox refId="${id}" defaultChecked="${element.defaultChecked}">${escapeXml(element.label)}</checkBox>`;
281 }
282};
283​
284/** The en-US strings and dialog layouts for `windowsAdmx`. */
285export function windowsAdml(): string {
286 const strings: Array<readonly [string, string]> = [
287 ["T3Code", "T3 Code"],
288 ["SUPPORTED_T3Code", "T3 Code with managed policy support"],
289 ];
290 const presentations: Array<string> = [];
291 for (const policy of policies()) {
292 strings.push([policy.id, policy.title], [`${policy.id}_Help`, policy.help]);
293 for (const element of policy.elements ?? []) {
294 if (element.kind === "enum") {
295 for (const item of element.items) {
296 strings.push([`${elementId(element)}_${item.value}`, item.label]);
297 }
298 }
299 }
300 if (policy.elements !== undefined) {
301 presentations.push(
302 ` <presentation id="${policy.id}">\n ${policy.elements.map(presentationElement).join("\n ")}\n </presentation>`,
303 );
304 }
305 }
306 return `<?xml version="1.0" encoding="utf-8"?>
307<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">
308 <displayName>T3 Code</displayName>
309 <description>Policies for T3 Code</description>
310 <resources>
311 <stringTable>
312${strings.map(([id, text]) => ` <string id="${id}">${escapeXml(text)}</string>`).join("\n")}
313 </stringTable>
314 <presentationTable>
315${presentations.join("\n")}
316 </presentationTable>
317 </resources>
318</policyDefinitionResources>
319`;
321​
322const plistValue = (value: unknown, indent: string): string => {
323 const inner = `${indent} `;
324 if (typeof value === "string") return `${indent}<string>${escapeXml(value)}</string>`;
325 if (typeof value === "boolean") return `${indent}<${value} />`;
326 if (typeof value === "number") {
327 return Number.isInteger(value)
328 ? `${indent}<integer>${value}</integer>`
329 : `${indent}<real>${value}</real>`;
330 }
331 if (Array.isArray(value)) {
332 return `${indent}<array>\n${value.map((item) => plistValue(item, inner)).join("\n")}\n${indent}</array>`;
333 }
334 const entries = Object.entries(value as Record<string, unknown>);
335 return `${indent}<dict>\n${entries
336 .map(([key, item]) => `${inner}<key>${escapeXml(key)}</key>\n${plistValue(item, inner)}`)
337 .join("\n")}\n${indent}</dict>`;
338};
339​
340/** Where `value` holds a `null`, as path segments, or undefined when it holds none. */
341const nullPath = (
342 value: unknown,
343 path: ReadonlyArray<string>,
344): ReadonlyArray<string> | undefined => {
345 if (value === null) return path;
346 if (typeof value !== "object") return undefined;
347 for (const [key, item] of Object.entries(value)) {
348 const found = nullPath(item, [...path, key]);
349 if (found !== undefined) return found;
350 }
351 return undefined;
352};
353​
354/** A device configuration profile that installs `document` for `com.t3tools.t3code`. */
355export function macosProfile(
356 document: ManagedPolicyDocument,
357 uuids: { readonly profile: string; readonly payload: string },
358):
359 | { readonly _tag: "Valid"; readonly profile: string }
360 | { readonly _tag: "Invalid"; readonly reason: string } {
361 // A plist has no null, and a setting may be locked empty.
362 const empty = nullPath(document, []);
363 if (empty !== undefined) {
364 const setting =
365 empty[0] === "settings" && empty.at(-1) === "value" ? empty.slice(0, -1) : empty;
366 return {
367 _tag: "Invalid",
368 reason: `${setting.join(".")} is null, which a configuration profile cannot hold; deploy this policy as a file.`,
369 };
370 }
371 const profile = {
372 PayloadContent: [
373 {
374 PayloadDisplayName: "T3 Code policy",
375 PayloadIdentifier: `com.t3tools.t3code.policy.${uuids.payload}`,
376 PayloadType: "com.t3tools.t3code",
377 PayloadUUID: uuids.payload,
378 PayloadVersion: 1,
379 ...document,
380 },
381 ],
382 PayloadDescription: "Configures T3 Code for every user on this Mac.",
383 PayloadDisplayName: `T3 Code policy for ${document.organization}`,
384 PayloadIdentifier: `com.t3tools.t3code.policy`,
385 PayloadOrganization: document.organization,
386 PayloadScope: "System",
387 PayloadType: "Configuration",
388 PayloadUUID: uuids.profile,
389 PayloadVersion: 1,
390 };
391 return {
392 _tag: "Valid",
393 profile: `<?xml version="1.0" encoding="UTF-8"?>
394<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
395<plist version="1.0">
396${plistValue(profile, "")}
397</plist>
398`,
399 };