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

main
ts 620 lines 20.6 KB
Raw
1 import * as dns from "@distilled.cloud/cloudflare/dns";
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 "../Zone/lookup.ts";
9
10 const TypeId = "Cloudflare.DNS.ZoneSettings" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * Nameserver assignment for the zone. `cloudflare.advanced` selects
15 * Foundation DNS Advanced Nameservers (paid add-on); `custom.*` types
16 * require Business/Enterprise account-level custom nameservers (ACNS).
17 */
18 export interface ZoneDnsNameservers {
19 /**
20 * Nameserver kind: Cloudflare's standard pair, Foundation DNS
21 * Advanced Nameservers, or custom nameservers defined at the account,
22 * tenant, or zone level.
23 */
24 type:
25 | "cloudflare.standard"
26 | "cloudflare.advanced"
27 | "custom.account"
28 | "custom.tenant"
29 | "custom.zone"
30 | (string & {});
31 /**
32 * Which configured nameserver set to use (for `custom.account` /
33 * `custom.tenant`).
34 */
35 nsSet?: number;
36 }
37
38 /**
39 * Components of the zone's SOA record. Every field is optional —
40 * omitted fields keep their current value.
41 */
42 export interface ZoneDnsSoa {
43 /** Time in seconds after which secondaries stop answering (`expire`). */
44 expire?: number;
45 /** Negative-caching TTL in seconds (`minimum`). */
46 minTtl?: number;
47 /** Primary nameserver (`MNAME`). */
48 mname?: string;
49 /** Secondary refresh interval in seconds. */
50 refresh?: number;
51 /** Secondary retry interval in seconds. */
52 retry?: number;
53 /** Zone administrator mailbox (`RNAME`). */
54 rname?: string;
55 /** TTL of the SOA record itself. */
56 ttl?: number;
57 }
58
59 export interface ZoneDnsSettingsProps {
60 /**
61 * Zone whose DNS settings are managed. Stable — the settings object
62 * is a per-zone singleton, so changing the zone triggers a
63 * replacement (the old zone's managed settings are restored to their
64 * pre-management values).
65 */
66 zoneId: string;
67 /**
68 * Flatten all CNAME records in the zone (a CNAME at the zone apex is
69 * always flattened regardless).
70 *
71 * Mutable — patched in place.
72 *
73 * @default false
74 */
75 flattenAllCnames?: boolean;
76 /**
77 * Settings for internal zones (Enterprise Internal DNS only).
78 *
79 * Mutable — patched in place.
80 */
81 internalDns?: {
82 /** Zone to resolve from when this internal zone has no match. */
83 referenceZoneId?: string;
84 };
85 /**
86 * Enable multi-provider DNS — activates the zone even when
87 * non-Cloudflare NS records exist and respects apex NS records during
88 * outbound zone transfers.
89 *
90 * Mutable — patched in place.
91 *
92 * @default false
93 */
94 multiProvider?: boolean;
95 /**
96 * Nameservers through which the zone should be available. Set
97 * `type: "cloudflare.advanced"` to enable Foundation DNS Advanced
98 * Nameservers (this replaces the removed `foundationDns` boolean,
99 * which Cloudflare rejects from 2026-11-23); set
100 * `type: "cloudflare.standard"` to turn them off.
101 *
102 * Mutable — patched in place.
103 *
104 * @default { type: "cloudflare.standard" }
105 */
106 nameservers?: ZoneDnsNameservers;
107 /**
108 * TTL (seconds) of the zone's NS records.
109 *
110 * Mutable — patched in place.
111 *
112 * @default 86400
113 */
114 nsTtl?: number;
115 /**
116 * Allow a secondary zone to use proxied override records and CNAME
117 * flattening at the apex (secondary zones only).
118 *
119 * Mutable — patched in place.
120 *
121 * @default false
122 */
123 secondaryOverrides?: boolean;
124 /**
125 * Components of the zone's SOA record. Only the fields you provide
126 * are compared and patched; the rest keep their live values.
127 *
128 * Mutable — patched in place.
129 */
130 soa?: ZoneDnsSoa;
131 /**
132 * Whether the zone is a regular, CDN-only, or DNS-only zone.
133 *
134 * Mutable — patched in place.
135 *
136 * @default "standard"
137 */
138 zoneMode?: "standard" | "cdn_only" | "dns_only";
139 }
140
141 /**
142 * Fully-resolved snapshot of a zone's DNS settings as Cloudflare
143 * reports them (`GET /zones/{zone_id}/dns_settings`).
144 */
145 export interface ZoneDnsSettingsSnapshot {
146 /** Whether all CNAMEs are flattened. */
147 flattenAllCnames: boolean;
148 /** Internal DNS reference zone, if configured. */
149 internalDns: { referenceZoneId: string | undefined };
150 /** Whether multi-provider DNS is enabled. */
151 multiProvider: boolean;
152 /** Resolved nameserver assignment. */
153 nameservers: { type: string; nsSet: number | undefined };
154 /** TTL of the zone's NS records. */
155 nsTtl: number;
156 /** Whether secondary overrides are enabled. */
157 secondaryOverrides: boolean;
158 /** Resolved SOA components. */
159 soa: {
160 expire: number | undefined;
161 minTtl: number | undefined;
162 mname: string | undefined;
163 refresh: number | undefined;
164 retry: number | undefined;
165 rname: string | undefined;
166 ttl: number | undefined;
167 };
168 /** Zone mode. */
169 zoneMode: string;
170 }
171
172 export interface ZoneDnsSettingsAttributes extends ZoneDnsSettingsSnapshot {
173 /** Zone whose DNS settings are managed. */
174 zoneId: string;
175 /**
176 * Snapshot of every DNS setting taken before Alchemy first patched
177 * the zone. The managed fields are restored from it on destroy, so
178 * deleting the resource puts the zone back the way it was found.
179 */
180 initialSettings: ZoneDnsSettingsSnapshot;
181 /**
182 * Which top-level settings this resource has managed (union across
183 * all reconciles). Only these are restored on destroy — settings the
184 * user never touched are left alone.
185 */
186 managedKeys: ReadonlyArray<string>;
187 }
188
189 export type ZoneDnsSettings = Resource<
190 TypeId,
191 ZoneDnsSettingsProps,
192 ZoneDnsSettingsAttributes,
193 never,
194 Providers
195 >;
196
197 /**
198 * The DNS settings of a Cloudflare zone
199 * (`/zones/{zone_id}/dns_settings`) — nameserver assignment, NS TTL,
200 * SOA components, CNAME flattening, multi-provider mode, and zone mode.
201 *
202 * The settings object is a per-zone singleton — it always exists with
203 * Cloudflare defaults, so this resource never creates or deletes
204 * anything physical. Reconcile patches only the fields you declare
205 * (and only when the observed value differs); destroy restores the
206 * managed fields to the values they had before Alchemy first touched
207 * the zone (captured as `initialSettings`).
208 *
209 * Some fields are plan-gated: `nameservers.type: "cloudflare.advanced"`
210 * (Foundation DNS Advanced Nameservers) is a paid add-on,
211 * `nameservers.type: "custom.*"` requires account custom nameservers,
212 * `internalDns` and `secondaryOverrides` are Enterprise features.
213 *
214 * ### Basic settings
215 * **Example:** Lower the NS record TTL
216 * ```typescript
217 * yield* Cloudflare.DNS.ZoneDnsSettings("DnsSettings", {
218 * zoneId: zone.zoneId,
219 * nsTtl: 3600,
220 * });
221 * ```
222 *
223 * **Example:** Flatten every CNAME in the zone
224 * ```typescript
225 * yield* Cloudflare.DNS.ZoneDnsSettings("DnsSettings", {
226 * zoneId: zone.zoneId,
227 * flattenAllCnames: true,
228 * });
229 * ```
230 *
231 * ### SOA tuning
232 * **Example:** Shorten the negative-caching TTL
233 * ```typescript
234 * yield* Cloudflare.DNS.ZoneDnsSettings("DnsSettings", {
235 * zoneId: zone.zoneId,
236 * soa: { minTtl: 300 },
237 * });
238 * ```
239 *
240 * ### Multi-provider DNS
241 * **Example:** Serve the zone alongside another DNS provider
242 * ```typescript
243 * yield* Cloudflare.DNS.ZoneDnsSettings("DnsSettings", {
244 * zoneId: zone.zoneId,
245 * multiProvider: true,
246 * });
247 * ```
248 *
249 * ### Advanced Nameservers
250 * **Example:** Serve the zone from Foundation DNS Advanced Nameservers
251 * ```typescript
252 * // Paid add-on. Replaces the removed `foundationDns: true`.
253 * yield* Cloudflare.DNS.ZoneDnsSettings("DnsSettings", {
254 * zoneId: zone.zoneId,
255 * nameservers: { type: "cloudflare.advanced" },
256 * });
257 * ```
258 *
259 * @resource
260 * @product DNS
261 * @category Domains & DNS
262 */
263 export const ZoneDnsSettings = Resource<ZoneDnsSettings>(TypeId, {
264 aliases: ["Cloudflare.Dns.ZoneSettings"],
265 });
266
267 /**
268 * Returns true if the given value is a ZoneDnsSettings resource.
269 */
270 export const isZoneDnsSettings = (value: unknown): value is ZoneDnsSettings =>
271 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
272
273 export const ZoneDnsSettingsProvider = () =>
274 Provider.succeed(ZoneDnsSettings, {
275 stables: ["zoneId", "initialSettings", "managedKeys"],
276
277 list: Effect.fn(function* () {
278 const { accountId } = yield* yield* CloudflareEnvironment;
279 // The settings object is a per-zone singleton with no account-wide
280 // list API — enumerate every zone and read its settings (every live
281 // zone always has one). Unmanaged here, so the observed snapshot is
282 // both the current state and the captured baseline.
283 const allZones = yield* listAllZones(accountId);
284 const rows = yield* Effect.forEach(
285 allZones.map((zone) => zone.id),
286 (zoneId) =>
287 dns.getSettingZone({ zoneId }).pipe(
288 Effect.map((observed) => {
289 const snapshot = toSnapshot(observed);
290 const attributes: ZoneDnsSettingsAttributes = {
291 zoneId,
292 ...snapshot,
293 initialSettings: snapshot,
294 managedKeys: [],
295 };
296 return attributes;
297 }),
298 // Plan-gated or partial zones reject the route; skip them.
299 // (Transient 403/429 "Authentication error" blips under
300 // concurrency are retried globally by the Cloudflare retry policy,
301 // so they never reach here as a real failure.)
302 Effect.catchTag("InvalidRoute", () => Effect.undefined),
303 ),
304 { concurrency: 10 },
305 );
306 return rows.filter((row): row is ZoneDnsSettingsAttributes => row !== undefined);
307 }),
308
309 diff: Effect.fn(function* ({ olds = {}, news, output }) {
310 const o = olds as ZoneDnsSettingsProps;
311 const n = news as ZoneDnsSettingsProps;
312 // zoneId is the resource's identity (the settings object is a
313 // zone singleton). Input<string> — compare only once concrete.
314 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
315 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
316 return { action: "replace" } as const;
317 }
318 return undefined;
319 }),
320
321 read: Effect.fn(function* ({ output, olds }) {
322 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
323 if (!zoneId) return undefined;
324 const observed = yield* dns.getSettingZone({ zoneId }).pipe(
325 // Zone deleted out-of-band — its settings are gone with it.
326 Effect.catchTag("InvalidRoute", () => Effect.undefined),
327 );
328 if (observed === undefined) return undefined;
329 const snapshot = toSnapshot(observed);
330 // Settings are a singleton that always exists with Cloudflare
331 // defaults — there is nothing to "own", so a cold read adopts
332 // freely (never `Unowned`). The observed snapshot at adoption
333 // time becomes the baseline restored on destroy.
334 return {
335 zoneId,
336 ...snapshot,
337 initialSettings: output?.initialSettings ?? snapshot,
338 managedKeys: output?.managedKeys ?? [],
339 } satisfies ZoneDnsSettingsAttributes;
340 }),
341
342 reconcile: Effect.fn(function* ({ news, output }) {
343 // Inputs have been resolved to concrete strings by Plan.
344 const zoneId = news.zoneId as string;
345
346 // 1. Observe — the settings object always exists for a live zone.
347 const observed = yield* dns.getSettingZone({ zoneId });
348 let snapshot = toSnapshot(observed);
349
350 // 2. Capture — the pre-management snapshot, restored on destroy.
351 const initialSettings = output?.initialSettings ?? snapshot;
352 // Track every key we have ever managed so destroy restores fields
353 // even after the user drops them from props.
354 const managedKeys = [
355 ...new Set([...(output?.managedKeys ?? []), ...declaredKeys(news)]),
356 ].sort();
357
358 // 3. Sync — patch only the declared fields whose observed value
359 // differs from the desired one; skip the API on no delta.
360 const delta = computeDelta(news, snapshot);
361 if (delta !== undefined) {
362 const patched = yield* dns.patchSettingZone({ zoneId, ...delta });
363 snapshot = toSnapshot(patched);
364 }
365
366 return {
367 zoneId,
368 ...snapshot,
369 initialSettings,
370 managedKeys,
371 } satisfies ZoneDnsSettingsAttributes;
372 }),
373
374 delete: Effect.fn(function* ({ output }) {
375 const { zoneId, initialSettings, managedKeys } = output;
376 // Observe — if the zone itself is gone, so are its settings.
377 const observed = yield* dns
378 .getSettingZone({ zoneId })
379 .pipe(Effect.catchTag("InvalidRoute", () => Effect.undefined));
380 if (observed === undefined) return;
381 const snapshot = toSnapshot(observed);
382 // Restore only the fields this resource managed, and only the
383 // ones that still differ (idempotent re-delete after a crash).
384 const restore = computeRestore(managedKeys, initialSettings, snapshot);
385 if (restore === undefined) return;
386 yield* dns
387 .patchSettingZone({ zoneId, ...restore })
388 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
389 }),
390 });
391
392 // ---------------------------------------------------------------------------
393 // Snapshot + diff helpers
394 // ---------------------------------------------------------------------------
395
396 type SettingsResponse = dns.GetSettingZoneResponse | dns.PatchSettingZoneResponse;
397
398 type PatchBody = Omit<dns.PatchSettingZoneRequest, "zoneId">;
399
400 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
401
402 const toSnapshot = (r: SettingsResponse): ZoneDnsSettingsSnapshot => ({
403 flattenAllCnames: r.flattenAllCnames,
404 internalDns: { referenceZoneId: undef(r.internalDns.referenceZoneId) },
405 multiProvider: r.multiProvider,
406 nameservers: {
407 type: r.nameservers.type,
408 nsSet: "nsSet" in r.nameservers ? undef(r.nameservers.nsSet) : undefined,
409 },
410 nsTtl: r.nsTtl,
411 secondaryOverrides: r.secondaryOverrides,
412 soa: {
413 expire: undef(r.soa.expire),
414 minTtl: undef(r.soa.minTtl),
415 mname: undef(r.soa.mname),
416 refresh: undef(r.soa.refresh),
417 retry: undef(r.soa.retry),
418 rname: undef(r.soa.rname),
419 ttl: undef(r.soa.ttl),
420 },
421 zoneMode: r.zoneMode,
422 });
423
424 /** Top-level prop keys (besides `zoneId`) the user declared. */
425 const declaredKeys = (news: ZoneDnsSettingsProps): string[] =>
426 (
427 [
428 "flattenAllCnames",
429 "internalDns",
430 "multiProvider",
431 "nameservers",
432 "nsTtl",
433 "secondaryOverrides",
434 "soa",
435 "zoneMode",
436 ] as const
437 ).filter((k) => news[k] !== undefined);
438
439 /**
440 * Merge desired SOA subfields over the observed SOA so the PATCH always
441 * carries a complete, consistent record (Cloudflare validates SOA as a
442 * whole). Drops fields that are unknown on both sides.
443 */
444 const mergedSoa = (
445 desired: ZoneDnsSoa,
446 observed: ZoneDnsSettingsSnapshot["soa"],
447 ): NonNullable<PatchBody["soa"]> => ({
448 expire: desired.expire ?? observed.expire,
449 minTtl: desired.minTtl ?? observed.minTtl,
450 mname: desired.mname ?? observed.mname,
451 refresh: desired.refresh ?? observed.refresh,
452 retry: desired.retry ?? observed.retry,
453 rname: desired.rname ?? observed.rname,
454 ttl: desired.ttl ?? observed.ttl,
455 });
456
457 const soaDiffers = (desired: ZoneDnsSoa, observed: ZoneDnsSettingsSnapshot["soa"]): boolean =>
458 (desired.expire !== undefined && desired.expire !== observed.expire) ||
459 (desired.minTtl !== undefined && desired.minTtl !== observed.minTtl) ||
460 (desired.mname !== undefined && desired.mname !== observed.mname) ||
461 (desired.refresh !== undefined && desired.refresh !== observed.refresh) ||
462 (desired.retry !== undefined && desired.retry !== observed.retry) ||
463 (desired.rname !== undefined && desired.rname !== observed.rname) ||
464 (desired.ttl !== undefined && desired.ttl !== observed.ttl);
465
466 const nameserversDiffer = (
467 desired: ZoneDnsNameservers,
468 observed: ZoneDnsSettingsSnapshot["nameservers"],
469 ): boolean =>
470 desired.type !== observed.type ||
471 (desired.nsSet !== undefined && desired.nsSet !== observed.nsSet);
472
473 /**
474 * Build the PATCH body converging observed → desired for the fields the
475 * user declared. Returns `undefined` when nothing differs.
476 */
477 const computeDelta = (
478 news: ZoneDnsSettingsProps,
479 observed: ZoneDnsSettingsSnapshot,
480 ): PatchBody | undefined => {
481 const body: PatchBody = {};
482 let dirty = false;
483 if (news.flattenAllCnames !== undefined && news.flattenAllCnames !== observed.flattenAllCnames) {
484 body.flattenAllCnames = news.flattenAllCnames;
485 dirty = true;
486 }
487 if (
488 news.internalDns?.referenceZoneId !== undefined &&
489 news.internalDns.referenceZoneId !== observed.internalDns.referenceZoneId
490 ) {
491 body.internalDns = { referenceZoneId: news.internalDns.referenceZoneId };
492 dirty = true;
493 }
494 if (news.multiProvider !== undefined && news.multiProvider !== observed.multiProvider) {
495 body.multiProvider = news.multiProvider;
496 dirty = true;
497 }
498 if (news.nameservers !== undefined && nameserversDiffer(news.nameservers, observed.nameservers)) {
499 body.nameservers = {
500 type: news.nameservers.type,
501 nsSet: news.nameservers.nsSet,
502 };
503 dirty = true;
504 }
505 if (news.nsTtl !== undefined && news.nsTtl !== observed.nsTtl) {
506 body.nsTtl = news.nsTtl;
507 dirty = true;
508 }
509 if (
510 news.secondaryOverrides !== undefined &&
511 news.secondaryOverrides !== observed.secondaryOverrides
512 ) {
513 body.secondaryOverrides = news.secondaryOverrides;
514 dirty = true;
515 }
516 if (news.soa !== undefined && soaDiffers(news.soa, observed.soa)) {
517 body.soa = mergedSoa(news.soa, observed.soa);
518 dirty = true;
519 }
520 if (news.zoneMode !== undefined && news.zoneMode !== observed.zoneMode) {
521 body.zoneMode = news.zoneMode;
522 dirty = true;
523 }
524 return dirty ? body : undefined;
525 };
526
527 /**
528 * Build the PATCH body that restores the managed fields to their
529 * pre-management values. Returns `undefined` when nothing drifted.
530 */
531 const computeRestore = (
532 managedKeys: ReadonlyArray<string>,
533 initial: ZoneDnsSettingsSnapshot,
534 observed: ZoneDnsSettingsSnapshot,
535 ): PatchBody | undefined => {
536 const body: PatchBody = {};
537 let dirty = false;
538 for (const key of managedKeys) {
539 switch (key) {
540 case "flattenAllCnames":
541 if (initial.flattenAllCnames !== observed.flattenAllCnames) {
542 body.flattenAllCnames = initial.flattenAllCnames;
543 dirty = true;
544 }
545 break;
546 case "internalDns":
547 if (
548 initial.internalDns.referenceZoneId !== observed.internalDns.referenceZoneId &&
549 initial.internalDns.referenceZoneId !== undefined
550 ) {
551 body.internalDns = {
552 referenceZoneId: initial.internalDns.referenceZoneId,
553 };
554 dirty = true;
555 }
556 break;
557 case "multiProvider":
558 if (initial.multiProvider !== observed.multiProvider) {
559 body.multiProvider = initial.multiProvider;
560 dirty = true;
561 }
562 break;
563 case "nameservers":
564 if (
565 initial.nameservers.type !== observed.nameservers.type ||
566 initial.nameservers.nsSet !== observed.nameservers.nsSet
567 ) {
568 body.nameservers = {
569 type: initial.nameservers.type,
570 nsSet: initial.nameservers.nsSet,
571 };
572 dirty = true;
573 }
574 break;
575 case "nsTtl":
576 if (initial.nsTtl !== observed.nsTtl) {
577 body.nsTtl = initial.nsTtl;
578 dirty = true;
579 }
580 break;
581 case "secondaryOverrides":
582 if (initial.secondaryOverrides !== observed.secondaryOverrides) {
583 body.secondaryOverrides = initial.secondaryOverrides;
584 dirty = true;
585 }
586 break;
587 case "soa":
588 if (
589 initial.soa.expire !== observed.soa.expire ||
590 initial.soa.minTtl !== observed.soa.minTtl ||
591 initial.soa.mname !== observed.soa.mname ||
592 initial.soa.refresh !== observed.soa.refresh ||
593 initial.soa.retry !== observed.soa.retry ||
594 initial.soa.rname !== observed.soa.rname ||
595 initial.soa.ttl !== observed.soa.ttl
596 ) {
597 body.soa = {
598 expire: initial.soa.expire,
599 minTtl: initial.soa.minTtl,
600 mname: initial.soa.mname,
601 refresh: initial.soa.refresh,
602 retry: initial.soa.retry,
603 rname: initial.soa.rname,
604 ttl: initial.soa.ttl,
605 };
606 dirty = true;
607 }
608 break;
609 case "zoneMode":
610 if (initial.zoneMode !== observed.zoneMode) {
611 body.zoneMode = initial.zoneMode;
612 dirty = true;
613 }
614 break;
615 default:
616 break;
617 }
618 }
619 return dirty ? body : undefined;
620 };