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

main
ts 452 lines 15.2 KB
Raw
1 import * as zones from "@distilled.cloud/cloudflare/zones";
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 import { listAllZones } from "./lookup.ts";
9
10 const TypeId = "Cloudflare.Zone.Setting" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * Identifier of a Cloudflare zone setting — every value Cloudflare
15 * recognises on `/zones/{zone_id}/settings/{settingId}`. The open
16 * `(string & {})` tail keeps the type forward-compatible with settings
17 * Cloudflare adds later.
18 */
19 export type SettingId =
20 | "0rtt"
21 | "advanced_ddos"
22 | "aegis"
23 | "always_online"
24 | "always_use_https"
25 | "automatic_https_rewrites"
26 | "automatic_platform_optimization"
27 | "brotli"
28 | "browser_cache_ttl"
29 | "browser_check"
30 | "cache_level"
31 | "challenge_ttl"
32 | "china_network_enabled"
33 | "ciphers"
34 | "cname_flattening"
35 | "content_converter"
36 | "development_mode"
37 | "early_hints"
38 | "edge_cache_ttl"
39 | "email_obfuscation"
40 | "h2_prioritization"
41 | "hotlink_protection"
42 | "http2"
43 | "http3"
44 | "image_resizing"
45 | "ip_geolocation"
46 | "ipv6"
47 | "max_upload"
48 | "min_tls_version"
49 | "mirage"
50 | "nel"
51 | "opportunistic_encryption"
52 | "opportunistic_onion"
53 | "orange_to_orange"
54 | "origin_error_page_pass_thru"
55 | "origin_h2_max_streams"
56 | "origin_max_http_version"
57 | "polish"
58 | "prefetch_preload"
59 | "privacy_pass"
60 | "proxy_read_timeout"
61 | "pseudo_ipv4"
62 | "redirects_for_ai_training"
63 | "replace_insecure_js"
64 | "response_buffering"
65 | "rocket_loader"
66 | "search_for_agents"
67 | "security_header"
68 | "security_level"
69 | "server_side_exclude"
70 | "sha1_support"
71 | "sort_query_string_for_cache"
72 | "ssl"
73 | "tls_1_2_only"
74 | "tls_1_3"
75 | "tls_client_auth"
76 | "transformations"
77 | "transformations_allowed_origins"
78 | "true_client_ip_header"
79 | "waf"
80 | "webp"
81 | "websockets"
82 | (string & {});
83
84 /**
85 * The concrete, enumerable members of {@link SettingId}. Cloudflare has no
86 * "list all settings" operation in the distilled `zones` service (only a
87 * per-setting `getSetting`), so `list()` fans out a `getSetting` over this
88 * known set on every zone. Forward-compatible settings (the `(string & {})`
89 * tail) cannot be enumerated and are skipped by definition.
90 */
91 const KNOWN_ZONE_SETTING_IDS = [
92 "0rtt",
93 "advanced_ddos",
94 "aegis",
95 "always_online",
96 "always_use_https",
97 "automatic_https_rewrites",
98 "automatic_platform_optimization",
99 "brotli",
100 "browser_cache_ttl",
101 "browser_check",
102 "cache_level",
103 "challenge_ttl",
104 "china_network_enabled",
105 "ciphers",
106 "cname_flattening",
107 "content_converter",
108 "development_mode",
109 "early_hints",
110 "edge_cache_ttl",
111 "email_obfuscation",
112 "h2_prioritization",
113 "hotlink_protection",
114 "http2",
115 "http3",
116 "image_resizing",
117 "ip_geolocation",
118 "ipv6",
119 "max_upload",
120 "min_tls_version",
121 "mirage",
122 "nel",
123 "opportunistic_encryption",
124 "opportunistic_onion",
125 "orange_to_orange",
126 "origin_error_page_pass_thru",
127 "origin_h2_max_streams",
128 "origin_max_http_version",
129 "polish",
130 "prefetch_preload",
131 "privacy_pass",
132 "proxy_read_timeout",
133 "pseudo_ipv4",
134 "redirects_for_ai_training",
135 "replace_insecure_js",
136 "response_buffering",
137 "rocket_loader",
138 "search_for_agents",
139 "security_header",
140 "security_level",
141 "server_side_exclude",
142 "sha1_support",
143 "sort_query_string_for_cache",
144 "ssl",
145 "tls_1_2_only",
146 "tls_1_3",
147 "tls_client_auth",
148 "transformations",
149 "transformations_allowed_origins",
150 "true_client_ip_header",
151 "waf",
152 "webp",
153 "websockets",
154 ] as const satisfies readonly SettingId[];
155
156 export type SettingProps = {
157 /**
158 * Zone the setting belongs to. Stable — changing the zone triggers a
159 * replacement (the old zone's setting is restored to the value it had
160 * before Alchemy managed it).
161 */
162 zoneId: string;
163 /**
164 * Which zone setting to manage (e.g. `always_online`,
165 * `browser_cache_ttl`, `min_tls_version`). Stable — the setting id is
166 * the resource's identity, so changing it triggers a replacement.
167 *
168 * Declared as plain `string` (narrowed to {@link SettingId}) so
169 * `diff` can compare without resolving an `Input`.
170 */
171 settingId: SettingId;
172 /**
173 * Desired value of the setting. The shape depends on `settingId` —
174 * on/off toggles take `"on"`/`"off"`, `browser_cache_ttl` takes a
175 * number of seconds, structured settings (e.g. `ciphers`,
176 * `security_header`) take arrays/objects.
177 *
178 * Mutable — patched in place.
179 */
180 value: unknown;
181 };
182
183 export type SettingAttributes = {
184 /** Zone the setting belongs to. */
185 zoneId: string;
186 /** The managed setting's identifier. */
187 settingId: string;
188 /** Resolved current value of the setting. */
189 value: unknown;
190 /**
191 * Whether the setting can be modified on the zone's current plan
192 * (`false` means the setting is plan-gated).
193 */
194 editable: boolean | undefined;
195 /** When the setting was last modified, if Cloudflare reports it. */
196 modifiedOn: string | undefined;
197 /**
198 * The value the setting had before Alchemy first patched it. Restored
199 * on destroy, so deleting the resource puts the zone back the way it
200 * was found.
201 */
202 initialValue: unknown;
203 };
204
205 export type Setting = Resource<TypeId, SettingProps, SettingAttributes, never, Providers>;
206
207 /**
208 * A single Cloudflare zone setting (`/zones/{zone_id}/settings/{settingId}`)
209 * pinned to a desired value.
210 *
211 * Zone settings are singletons — every setting always exists on every zone
212 * (with a Cloudflare default), so this resource never creates or deletes
213 * anything physical. Reconcile patches the setting when the observed value
214 * differs from the desired one; destroy restores the value the setting had
215 * before Alchemy first managed it (captured as `initialValue`).
216 *
217 * Many settings are plan-gated (`editable: false` on lower plans — e.g.
218 * `image_resizing`, `polish` need Pro+; `advanced_ddos` is Enterprise).
219 * Patching a non-editable setting fails with Cloudflare's "setting not
220 * editable" error.
221 * ### Toggle settings
222 * **Example:** Force HTTPS on the whole zone
223 * ```typescript
224 * yield* Cloudflare.Zone.Setting("AlwaysUseHttps", {
225 * zoneId: zone.zoneId,
226 * settingId: "always_use_https",
227 * value: "on",
228 * });
229 * ```
230 *
231 * **Example:** Disable Always Online
232 * ```typescript
233 * yield* Cloudflare.Zone.Setting("AlwaysOnline", {
234 * zoneId: zone.zoneId,
235 * settingId: "always_online",
236 * value: "off",
237 * });
238 * ```
239 *
240 * ### Numeric settings
241 * **Example:** Browser cache TTL of one hour
242 * ```typescript
243 * yield* Cloudflare.Zone.Setting("BrowserCacheTtl", {
244 * zoneId: zone.zoneId,
245 * settingId: "browser_cache_ttl",
246 * value: 3600,
247 * });
248 * ```
249 *
250 * ### TLS settings
251 * **Example:** Require at least TLS 1.2
252 * ```typescript
253 * yield* Cloudflare.Zone.Setting("MinTls", {
254 * zoneId: zone.zoneId,
255 * settingId: "min_tls_version",
256 * value: "1.2",
257 * });
258 * ```
259 *
260 * @see https://developers.cloudflare.com/api/resources/zones/subresources/settings/
261 *
262 * @resource
263 * @product Zones
264 * @category Domains & DNS
265 */
266 export const Setting = Resource<Setting>(TypeId);
267
268 /**
269 * Returns true if the given value is a Setting resource.
270 */
271 export const isSetting = (value: unknown): value is Setting =>
272 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
273
274 export const SettingProvider = () =>
275 Provider.succeed(Setting, {
276 stables: ["zoneId", "settingId", "initialValue"],
277
278 diff: Effect.fn(function* ({ olds = {}, news, output }) {
279 const o = olds as SettingProps;
280 const n = news as SettingProps;
281 // settingId is the resource's identity.
282 const oldSettingId = output?.settingId ?? o.settingId;
283 if (oldSettingId !== undefined && oldSettingId !== n.settingId) {
284 return { action: "replace" } as const;
285 }
286 // zoneId is Input<string>; compare only once both sides are concrete.
287 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
288 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
289 return { action: "replace" } as const;
290 }
291 return undefined;
292 }),
293
294 read: Effect.fn(function* ({ output, olds }) {
295 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
296 const settingId = output?.settingId ?? olds?.settingId;
297 if (!zoneId || !settingId) return undefined;
298 const observed = yield* zones.getSetting({ zoneId, settingId }).pipe(
299 // Zone deleted out-of-band — the setting is gone with it.
300 Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined),
301 );
302 if (observed === undefined) return undefined;
303 // Settings are singletons that always exist with a Cloudflare
304 // default — there is nothing to "own", so a cold read adopts
305 // freely (never `Unowned`). The observed value at adoption time
306 // becomes the `initialValue` restored on destroy.
307 const initialValue = output !== undefined ? output.initialValue : settingValue(observed);
308 return toAttributes(zoneId, settingId, observed, initialValue);
309 }),
310
311 reconcile: Effect.fn(function* ({ news, output }) {
312 // Inputs have been resolved to concrete strings by Plan.
313 const zoneId = news.zoneId as string;
314 const settingId = news.settingId;
315
316 // 1. Observe — the setting always exists; read its live value.
317 const observed = yield* zones.getSetting({ zoneId, settingId });
318
319 // 2. Capture — the pre-management value, restored on destroy.
320 // `output` (including an adoption read) already carries it;
321 // otherwise this is our first touch and the observed value is
322 // the zone's original.
323 const initialValue = output !== undefined ? output.initialValue : settingValue(observed);
324
325 // 3. Sync — patch only when the observed value differs.
326 if (deepValueEquals(settingValue(observed), news.value)) {
327 return toAttributes(zoneId, settingId, observed, initialValue);
328 }
329 const patched = yield* zones.patchSetting({
330 zoneId,
331 settingId,
332 value: news.value,
333 });
334 return toAttributes(zoneId, settingId, patched, initialValue);
335 }),
336
337 delete: Effect.fn(function* ({ output }) {
338 const { zoneId, settingId, initialValue } = output;
339 // Observe — if the zone itself is gone, so is the setting.
340 const observed = yield* zones
341 .getSetting({ zoneId, settingId })
342 .pipe(Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined));
343 if (observed === undefined) return;
344 // Restore the pre-management value; skip the call when it already
345 // matches (idempotent re-delete after a crashed run).
346 if (deepValueEquals(settingValue(observed), initialValue)) return;
347 yield* zones
348 .patchSetting({ zoneId, settingId, value: initialValue })
349 .pipe(Effect.catchTag("InvalidZoneIdentifier", () => Effect.void));
350 }),
351
352 // Zone settings are keyed by (zoneId, settingId): every setting exists on
353 // every zone with a Cloudflare default. There is no account-wide list, so
354 // enumerate every zone via `listAllZones` and read each known setting with
355 // the same `getSetting` call `read` uses — emitting one Attributes per
356 // (zone, setting), exactly matching `read`'s keying.
357 //
358 // The distilled `zones` service exposes only a per-setting `getSetting`
359 // (no bulk `/zones/{id}/settings` list op), so we fan out across the known
360 // setting ids. Adding a bulk-list operation to distilled would collapse
361 // each zone's N gets into one call — see the agent report's neededPatch.
362 list: Effect.fn(function* () {
363 const { accountId } = yield* yield* CloudflareEnvironment;
364 const allZones = yield* listAllZones(accountId);
365 const pairs = allZones.flatMap((zone) =>
366 KNOWN_ZONE_SETTING_IDS.map((settingId) => ({
367 zoneId: zone.id,
368 settingId,
369 })),
370 );
371 const rows = yield* Effect.forEach(
372 pairs,
373 ({ zoneId, settingId }) =>
374 zones.getSetting({ zoneId, settingId }).pipe(
375 Effect.map((observed) =>
376 // Unmanaged at discovery time, so the observed value is the
377 // setting's pre-management value (mirrors a cold `read`).
378 toAttributes(zoneId, settingId, observed, settingValue(observed)),
379 ),
380 // Zone removed out-of-band or the setting is plan-gated / not
381 // exposed to this token — skip it rather than fail the listing.
382 Effect.catchTag(["InvalidZoneIdentifier", "Forbidden"], () => Effect.undefined),
383 // A handful of structured settings (e.g.
384 // `automatic_platform_optimization`) can return a scalar value
385 // (`"off"`) that distilled's `GetSettingResponse` union doesn't
386 // model, surfacing as an untyped `CloudflareHttpError` (status
387 // 200, "Schema decode failed"). The Cloudflare patch system only
388 // types errors, not response schemas, so this can't be patched
389 // here — skip the undecodable setting rather than failing the
390 // whole listing. See the agent report's neededPatch (widen the
391 // `GetSettingResponse` member to accept the scalar form).
392 Effect.orElseSucceed(() => undefined),
393 ),
394 { concurrency: 10 },
395 );
396 return rows.filter((row): row is SettingAttributes => row !== undefined);
397 }),
398 });
399
400 /**
401 * Pull the `value` out of a distilled setting response. Every member of the
402 * response union carries `value` (a couple type it optional), so widen
403 * rather than switch on all sixty setting ids.
404 */
405 const settingValue = (setting: zones.GetSettingResponse | zones.PatchSettingResponse): unknown =>
406 (setting as { value?: unknown }).value;
407
408 const toAttributes = (
409 zoneId: string,
410 settingId: string,
411 setting: zones.GetSettingResponse | zones.PatchSettingResponse,
412 initialValue: unknown,
413 ): SettingAttributes => {
414 const s = setting as {
415 value?: unknown;
416 editable?: boolean | null;
417 modifiedOn?: string | null;
418 };
419 return {
420 zoneId,
421 settingId,
422 value: s.value,
423 editable: s.editable ?? undefined,
424 modifiedOn: s.modifiedOn ?? undefined,
425 initialValue,
426 };
427 };
428
429 /**
430 * Structural equality for setting values — primitives, arrays, and plain
431 * objects (`null`-tolerant). Setting values are plain JSON, so this is
432 * sufficient and avoids key-order false negatives that `JSON.stringify`
433 * comparison would produce.
434 */
435 const deepValueEquals = (a: unknown, b: unknown): boolean => {
436 if (a === b) return true;
437 if (a === null || b === null) return false;
438 if (Array.isArray(a) || Array.isArray(b)) {
439 if (!Array.isArray(a) || !Array.isArray(b)) return false;
440 if (a.length !== b.length) return false;
441 return a.every((v, i) => deepValueEquals(v, b[i]));
442 }
443 if (typeof a === "object" && typeof b === "object") {
444 const ak = Object.keys(a as Record<string, unknown>);
445 const bk = Object.keys(b as Record<string, unknown>);
446 if (ak.length !== bk.length) return false;
447 return ak.every((k) =>
448 deepValueEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),
449 );
450 }
451 return false;
452 };