The best way to control Claude Code, Codex and more from any computer or phone

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