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

main
ts 276 lines 10.2 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
7 import type { Providers } from "../Providers.ts";
8
9 const TypeId = "Cloudflare.Devices.Settings" as const;
10 type TypeId = typeof TypeId;
11
12 /**
13 * A snapshot of the account's WARP device settings, as observed on
14 * Cloudflare. Captured before Alchemy first patches the singleton and
15 * restored on destroy.
16 */
17 export interface DeviceSettingsSnapshot {
18 /** Time limit, in seconds, that a user can bypass WARP with an override code. */
19 disableForTime?: number;
20 /** Whether the external emergency disconnect feature is enabled. */
21 externalEmergencySignalEnabled?: boolean;
22 /** SHA-256 fingerprint pinning the emergency-signal server certificate. */
23 externalEmergencySignalFingerprint?: string;
24 /** Polling interval for the emergency disconnect signal (e.g. `"5m"`). */
25 externalEmergencySignalInterval?: string;
26 /** HTTPS URL the emergency disconnect signal is fetched from. */
27 externalEmergencySignalUrl?: string;
28 /** Whether Gateway proxy filtering on TCP is enabled. */
29 gatewayProxyEnabled?: boolean;
30 /** Whether Gateway proxy filtering on UDP is enabled. */
31 gatewayUdpProxyEnabled?: boolean;
32 /** Whether the Cloudflare-managed root certificate is installed on devices. */
33 rootCertificateInstallationEnabled?: boolean;
34 /** Whether CGNAT virtual IPv4 addressing is used. */
35 useZtVirtualIp?: boolean;
36 }
37
38 export interface DeviceSettingsProps {
39 /**
40 * Sets the time limit, in seconds, that a user can use an override code
41 * to bypass WARP. `0` disables override codes.
42 */
43 disableForTime?: number;
44 /**
45 * Controls whether the external emergency disconnect feature is enabled.
46 */
47 externalEmergencySignalEnabled?: boolean;
48 /**
49 * The SHA-256 fingerprint (64 hexadecimal characters) of the HTTPS
50 * server certificate for {@link externalEmergencySignalUrl}. When set,
51 * the WARP client uses it to verify the server's identity.
52 */
53 externalEmergencySignalFingerprint?: string;
54 /**
55 * The interval at which the WARP client fetches the emergency disconnect
56 * signal, as a duration string (e.g. `"5m"`, `"2m30s"`, `"1h"`).
57 * Minimum 30 seconds.
58 */
59 externalEmergencySignalInterval?: string;
60 /**
61 * The HTTPS URL from which to fetch the emergency disconnect signal.
62 * Must use HTTPS with an IPv4 or IPv6 address as the host.
63 */
64 externalEmergencySignalUrl?: string;
65 /**
66 * Enable Gateway proxy filtering on TCP.
67 */
68 gatewayProxyEnabled?: boolean;
69 /**
70 * Enable Gateway proxy filtering on UDP.
71 */
72 gatewayUdpProxyEnabled?: boolean;
73 /**
74 * Enable installation of the Cloudflare-managed root certificate on
75 * enrolled devices.
76 */
77 rootCertificateInstallationEnabled?: boolean;
78 /**
79 * Enable using CGNAT virtual IPv4 addressing.
80 */
81 useZtVirtualIp?: boolean;
82 }
83
84 export type DeviceSettingsAttributes = DeviceSettingsSnapshot & {
85 /** Account that owns the device settings singleton. */
86 accountId: string;
87 /**
88 * The settings the account had before Alchemy first patched them.
89 * Restored (via PUT, which resets unspecified fields) on destroy, so
90 * deleting the resource puts the account back the way it was found.
91 */
92 initialSettings: DeviceSettingsSnapshot;
93 };
94
95 export type DeviceSettings = Resource<
96 TypeId,
97 DeviceSettingsProps,
98 DeviceSettingsAttributes,
99 never,
100 Providers
101 >;
102
103 /**
104 * Manages the **singleton** Cloudflare Zero Trust **device settings** for
105 * an account (`/accounts/{accountId}/devices/settings`) — account-wide
106 * WARP toggles like the Gateway TCP/UDP proxy, managed root certificate
107 * installation, and CGNAT virtual IP.
108 *
109 * The singleton always exists, so reconcile patches only the declared
110 * fields in place. The pre-management snapshot is captured on first touch
111 * and restored on destroy (capture-and-restore), returning the account to
112 * the state Alchemy found it in.
113 * ### Managing device settings
114 * **Example:** Enable the Gateway proxy
115 * ```typescript
116 * yield* Cloudflare.Devices.DeviceSettings("Devices", {
117 * gatewayProxyEnabled: true,
118 * gatewayUdpProxyEnabled: true,
119 * });
120 * ```
121 *
122 * **Example:** Allow one-hour WARP override codes
123 * ```typescript
124 * yield* Cloudflare.Devices.DeviceSettings("Devices", {
125 * disableForTime: 3600,
126 * });
127 * ```
128 *
129 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/
130 *
131 * @resource
132 * @product Devices
133 * @category Cloudflare One (Zero Trust)
134 */
135 export const DeviceSettings = Resource<DeviceSettings>(TypeId);
136
137 /**
138 * Returns true if the given value is a DeviceSettings resource.
139 */
140 export const isDeviceSettings = (value: unknown): value is DeviceSettings =>
141 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
142
143 export const DeviceSettingsProvider = () =>
144 Provider.succeed(DeviceSettings, {
145 nuke: { singleton: true },
146 stables: ["accountId", "initialSettings"],
147
148 // Account singleton: there is exactly one device-settings object per
149 // account and no enumeration API. Mirror `read` — observe the single
150 // singleton and return it as a one-element array. With no prior
151 // output, the observed snapshot is itself the restore target.
152 list: Effect.fn(function* () {
153 const { accountId } = yield* yield* CloudflareEnvironment;
154 const observed = yield* observeSettings(accountId);
155 return [toAttributes(accountId, observed, observed)];
156 }),
157
158 read: Effect.fn(function* ({ output }) {
159 const { accountId } = yield* yield* CloudflareEnvironment;
160 const acct = output?.accountId ?? accountId;
161 const observed = yield* observeSettings(acct);
162 // The singleton always exists with account defaults — there is
163 // nothing to "own", so a cold read adopts freely. The observed
164 // snapshot at adoption time becomes the restore target.
165 const initialSettings = output?.initialSettings ?? observed;
166 return toAttributes(acct, observed, initialSettings);
167 }),
168
169 reconcile: Effect.fn(function* ({ news, output }) {
170 const { accountId } = yield* yield* CloudflareEnvironment;
171
172 // 1. Observe — the singleton always exists; read its live state.
173 const observed = yield* observeSettings(accountId);
174
175 // 2. Capture — the pre-management snapshot, restored on destroy.
176 // `output` (including an adoption read) already carries it;
177 // otherwise this is our first touch.
178 const initialSettings = output?.initialSettings ?? observed;
179
180 // 3. Sync — patch only the declared fields that differ.
181 const changes: Partial<DeviceSettingsSnapshot> = {};
182 const assign = <K extends keyof DeviceSettingsSnapshot>(
183 key: K,
184 value: DeviceSettingsSnapshot[K],
185 ) => {
186 changes[key] = value;
187 };
188 let dirty = false;
189 for (const key of SETTING_KEYS) {
190 const desired = news[key];
191 if (desired === undefined) continue;
192 if (observed[key] !== desired) {
193 assign(key, desired);
194 dirty = true;
195 }
196 }
197 if (!dirty) {
198 return toAttributes(accountId, observed, initialSettings);
199 }
200 yield* zeroTrust.patchDeviceSetting({ accountId, ...changes });
201
202 // 4. Return — re-read so attrs reflect post-sync truth.
203 const final = yield* observeSettings(accountId);
204 return toAttributes(accountId, final, initialSettings);
205 }),
206
207 delete: Effect.fn(function* ({ output }) {
208 const { accountId, initialSettings } = output;
209 // Observe — skip the restore when the account already matches the
210 // captured snapshot (idempotent re-delete after a crashed run).
211 const observed = yield* observeSettings(accountId);
212 if (sameSnapshot(observed, initialSettings)) return;
213 // Restore via PUT: fields absent from the captured snapshot were
214 // unset before we managed the singleton, and PUT resets them.
215 yield* zeroTrust.putDeviceSetting({ accountId, ...initialSettings });
216 }),
217 });
218
219 const SETTING_KEYS = [
220 "disableForTime",
221 "externalEmergencySignalEnabled",
222 "externalEmergencySignalFingerprint",
223 "externalEmergencySignalInterval",
224 "externalEmergencySignalUrl",
225 "gatewayProxyEnabled",
226 "gatewayUdpProxyEnabled",
227 "rootCertificateInstallationEnabled",
228 "useZtVirtualIp",
229 ] as const satisfies readonly (keyof DeviceSettingsSnapshot)[];
230
231 /**
232 * Read the live settings, normalized to a `null`-free snapshot.
233 */
234 const observeSettings = (accountId: string) =>
235 zeroTrust.getDeviceSetting({ accountId }).pipe(
236 Effect.map((s): DeviceSettingsSnapshot => {
237 const snapshot: DeviceSettingsSnapshot = {};
238 if (s.disableForTime != null) snapshot.disableForTime = s.disableForTime;
239 if (s.externalEmergencySignalEnabled != null) {
240 snapshot.externalEmergencySignalEnabled = s.externalEmergencySignalEnabled;
241 }
242 if (s.externalEmergencySignalFingerprint != null) {
243 snapshot.externalEmergencySignalFingerprint = s.externalEmergencySignalFingerprint;
244 }
245 if (s.externalEmergencySignalInterval != null) {
246 snapshot.externalEmergencySignalInterval = s.externalEmergencySignalInterval;
247 }
248 if (s.externalEmergencySignalUrl != null) {
249 snapshot.externalEmergencySignalUrl = s.externalEmergencySignalUrl;
250 }
251 if (s.gatewayProxyEnabled != null) {
252 snapshot.gatewayProxyEnabled = s.gatewayProxyEnabled;
253 }
254 if (s.gatewayUdpProxyEnabled != null) {
255 snapshot.gatewayUdpProxyEnabled = s.gatewayUdpProxyEnabled;
256 }
257 if (s.rootCertificateInstallationEnabled != null) {
258 snapshot.rootCertificateInstallationEnabled = s.rootCertificateInstallationEnabled;
259 }
260 if (s.useZtVirtualIp != null) snapshot.useZtVirtualIp = s.useZtVirtualIp;
261 return snapshot;
262 }),
263 );
264
265 const toAttributes = (
266 accountId: string,
267 observed: DeviceSettingsSnapshot,
268 initialSettings: DeviceSettingsSnapshot,
269 ): DeviceSettingsAttributes => ({
270 ...observed,
271 accountId,
272 initialSettings,
273 });
274
275 const sameSnapshot = (a: DeviceSettingsSnapshot, b: DeviceSettingsSnapshot): boolean =>
276 SETTING_KEYS.every((key) => a[key] === b[key]);