@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 432 lines 15.4 KB
Raw
1 import * as dns from "@distilled.cloud/cloudflare/dns";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Schedule from "effect/Schedule";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11
12 const TypeId = "Cloudflare.DNS.Dnssec" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Live DNSSEC status as Cloudflare reports it. `pending` /
17 * `pending-disabled` are the eventually-consistent transitions toward
18 * `active` / `disabled`; reaching `active` additionally requires the DS
19 * record to be submitted at the registrar.
20 */
21 export type DnssecStatus =
22 | "active"
23 | "pending"
24 | "disabled"
25 | "pending-disabled"
26 | "error"
27 | (string & {});
28
29 /**
30 * The user-desired DNSSEC state — Cloudflare's PATCH endpoint only
31 * accepts these two values.
32 */
33 export type DnssecDesiredStatus = "active" | "disabled";
34
35 export interface DnssecProps {
36 /**
37 * Zone whose DNSSEC configuration is managed. Stable — DNSSEC is a
38 * per-zone singleton, so changing the zone triggers a replacement
39 * (the old zone's DNSSEC is restored to its pre-management state).
40 */
41 zoneId: string;
42 /**
43 * Desired DNSSEC state. `"active"` signs the zone; `"disabled"` turns
44 * signing off. Activation is eventually consistent — Cloudflare
45 * reports `pending` until the registrar-side DS record is in place.
46 *
47 * Mutable — patched in place.
48 *
49 * @default "active"
50 */
51 status?: DnssecDesiredStatus;
52 /**
53 * Enable multi-signer DNSSEC, allowing multiple providers to serve a
54 * DNSSEC-signed zone at the same time (required for user-managed
55 * DNSKEY records).
56 *
57 * Mutable — patched in place.
58 *
59 * @default false
60 */
61 dnssecMultiSigner?: boolean;
62 /**
63 * Allow Cloudflare to transfer in a pre-signed zone (signatures
64 * included) from an external provider without signing on the fly.
65 *
66 * Mutable — patched in place.
67 *
68 * @default false
69 */
70 dnssecPresigned?: boolean;
71 /**
72 * Use NSEC3 together with DNSSEC. Combined with `dnssecPresigned`,
73 * enables NSEC3 records when transferring in from an external
74 * provider (live signing with NSEC3 requires Foundation DNS).
75 *
76 * Mutable — patched in place.
77 *
78 * @default false
79 */
80 dnssecUseNsec3?: boolean;
81 }
82
83 export interface DnssecAttributes {
84 /** Zone whose DNSSEC configuration is managed. */
85 zoneId: string;
86 /**
87 * Live DNSSEC status. Stays `pending` until the DS record is
88 * submitted at the registrar — that final hop is outside Cloudflare's
89 * (and Alchemy's) control.
90 */
91 status: DnssecStatus;
92 /** Whether multi-signer DNSSEC is enabled. */
93 dnssecMultiSigner: boolean | undefined;
94 /** Whether pre-signed zone transfers are enabled. */
95 dnssecPresigned: boolean | undefined;
96 /** Whether NSEC3 is enabled. */
97 dnssecUseNsec3: boolean | undefined;
98 /** DNSSEC algorithm key code (e.g. `"13"`). */
99 algorithm: string | undefined;
100 /** Digest hash for the DS record. */
101 digest: string | undefined;
102 /** Digest algorithm name (e.g. `"SHA256"`). */
103 digestAlgorithm: string | undefined;
104 /** Coded digest algorithm type (e.g. `"2"`). */
105 digestType: string | undefined;
106 /**
107 * Full DS record string — this is what users paste at their registrar
108 * to complete DNSSEC activation.
109 */
110 ds: string | undefined;
111 /** DNSKEY flags field (e.g. `257` for KSK). */
112 flags: number | undefined;
113 /** DS key tag. */
114 keyTag: number | undefined;
115 /** Algorithm key type (e.g. `"ECDSAP256SHA256"`). */
116 keyType: string | undefined;
117 /** Public key for the DS record. */
118 publicKey: string | undefined;
119 /** When DNSSEC was last modified. */
120 modifiedOn: string | undefined;
121 /**
122 * The desired-state family DNSSEC was in before Alchemy first managed
123 * it (`pending` normalises to `active`, `pending-disabled` to
124 * `disabled`). Restored on destroy.
125 */
126 initialStatus: DnssecDesiredStatus;
127 /** `dnssecMultiSigner` before Alchemy first managed the zone. */
128 initialMultiSigner: boolean | undefined;
129 /** `dnssecPresigned` before Alchemy first managed the zone. */
130 initialPresigned: boolean | undefined;
131 /** `dnssecUseNsec3` before Alchemy first managed the zone. */
132 initialUseNsec3: boolean | undefined;
133 }
134
135 export type Dnssec = Resource<TypeId, DnssecProps, DnssecAttributes, never, Providers>;
136
137 /**
138 * DNSSEC configuration for a Cloudflare zone
139 * (`/zones/{zone_id}/dnssec`).
140 *
141 * DNSSEC is a per-zone singleton — it always exists in either an
142 * enabled or disabled state, so this resource never creates or deletes
143 * anything physical. Reconcile patches the configuration toward the
144 * desired state; destroy restores the state the zone had before
145 * Alchemy first managed it (enabled stays enabled, previously-disabled
146 * zones are deactivated again).
147 *
148 * Activation is eventually consistent: after enabling, Cloudflare
149 * reports `pending` until the `ds` attribute (the DS record) is
150 * submitted at the domain's registrar. The reconciler polls with
151 * bounded retries for the zone to leave the `disabled` state but does
152 * not wait for full `active` — that depends on the registrar.
153 *
154 * Safety: when there is no prior state and DNSSEC is already enabled
155 * on the zone, `read` reports it as `Unowned` and the engine refuses
156 * to take it over unless `--adopt` (or `adopt(true)`) is set.
157 * ### Enabling DNSSEC
158 * **Example:** Sign the zone
159 * ```typescript
160 * const dnssec = yield* Cloudflare.DNS.Dnssec("ZoneDnssec", {
161 * zoneId: zone.zoneId,
162 * });
163 * // Paste `dnssec.ds` at your registrar to complete activation.
164 * ```
165 *
166 * **Example:** Multi-signer DNSSEC
167 * ```typescript
168 * yield* Cloudflare.DNS.Dnssec("ZoneDnssec", {
169 * zoneId: zone.zoneId,
170 * dnssecMultiSigner: true,
171 * });
172 * ```
173 *
174 * ### Disabling DNSSEC
175 * **Example:** Keep DNSSEC explicitly off
176 * ```typescript
177 * yield* Cloudflare.DNS.Dnssec("ZoneDnssec", {
178 * zoneId: zone.zoneId,
179 * status: "disabled",
180 * });
181 * ```
182 *
183 * @resource
184 * @product DNS
185 * @category Domains & DNS
186 */
187 export const Dnssec = Resource<Dnssec>(TypeId, {
188 aliases: ["Cloudflare.Dns.Dnssec"],
189 });
190
191 /**
192 * Returns true if the given value is a Dnssec resource.
193 */
194 export const issec = (value: unknown): value is Dnssec =>
195 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
196
197 export const DnssecProvider = () =>
198 Provider.succeed(Dnssec, {
199 stables: [
200 "zoneId",
201 "initialStatus",
202 "initialMultiSigner",
203 "initialPresigned",
204 "initialUseNsec3",
205 ],
206
207 list: Effect.fn(function* () {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209 // No account-wide API for this zone singleton — enumerate every
210 // zone in the account and read its DNSSEC config (every zone has
211 // one). Disabled zones are "not created" for this resource (same
212 // as a cold `read`), so they're skipped; the observed state of an
213 // active zone becomes its captured initial state.
214 const allZones = yield* listAllZones(accountId);
215 const rows = yield* Effect.forEach(
216 allZones.map((zone) => zone.id),
217 (zoneId) =>
218 dns.getDnssec({ zoneId }).pipe(
219 Effect.map((observed) =>
220 statusFamily(observed.status) === "disabled"
221 ? undefined
222 : toAttributes(zoneId, observed, captureInitial(observed)),
223 ),
224 // Plan-gated or partial zones reject the route; skip them.
225 Effect.catchTag("InvalidRoute", () => Effect.undefined),
226 ),
227 { concurrency: 10 },
228 );
229 return rows.filter((row): row is DnssecAttributes => row !== undefined);
230 }),
231
232 diff: Effect.fn(function* ({ olds = {}, news, output }) {
233 const o = olds as DnssecProps;
234 const n = news as DnssecProps;
235 // zoneId is the resource's identity (DNSSEC is a zone singleton).
236 // It is Input<string>; compare only once both sides are concrete.
237 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
238 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
239 return { action: "replace" } as const;
240 }
241 return undefined;
242 }),
243
244 read: Effect.fn(function* ({ output, olds }) {
245 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
246 if (!zoneId) return undefined;
247 const observed = yield* dns.getDnssec({ zoneId }).pipe(
248 // Zone deleted out-of-band — DNSSEC config is gone with it.
249 Effect.catchTag("InvalidRoute", () => Effect.undefined),
250 );
251 if (observed === undefined) return undefined;
252 if (output !== undefined) {
253 // Owned path — refresh, keeping the captured pre-management state.
254 return toAttributes(zoneId, observed, {
255 status: output.initialStatus,
256 multiSigner: output.initialMultiSigner,
257 presigned: output.initialPresigned,
258 useNsec3: output.initialUseNsec3,
259 });
260 }
261 // Cold read: DNSSEC disabled means "not created" for this resource.
262 if (statusFamily(observed.status) === "disabled") return undefined;
263 // DNSSEC is enabled but we have no state and no ownership markers
264 // exist — gate takeover behind the adopt policy.
265 return Unowned(toAttributes(zoneId, observed, captureInitial(observed)));
266 }),
267
268 reconcile: Effect.fn(function* ({ news, output }) {
269 // Inputs have been resolved to concrete strings by Plan.
270 const zoneId = news.zoneId as string;
271 const desiredStatus: DnssecDesiredStatus = news.status ?? "active";
272
273 // 1. Observe — DNSSEC config always exists for a live zone.
274 let observed = yield* dns.getDnssec({ zoneId });
275
276 // 2. Capture — the pre-management state, restored on destroy.
277 // `output` (including an adoption read) already carries it;
278 // otherwise this is our first touch.
279 const initial: InitialDnssec =
280 output !== undefined
281 ? {
282 status: output.initialStatus,
283 multiSigner: output.initialMultiSigner,
284 presigned: output.initialPresigned,
285 useNsec3: output.initialUseNsec3,
286 }
287 : captureInitial(observed);
288
289 // 3. Sync — patch only when the observed state differs from the
290 // desired one.
291 if (!matchesDesired(observed, news, desiredStatus)) {
292 observed = yield* dns.patchDnssec({
293 zoneId,
294 status: desiredStatus,
295 dnssecMultiSigner: news.dnssecMultiSigner,
296 dnssecPresigned: news.dnssecPresigned,
297 dnssecUseNsec3: news.dnssecUseNsec3,
298 });
299 }
300
301 // 4. Wait — activation/deactivation is eventually consistent.
302 // Poll (bounded) for the status to reach the desired family;
303 // "active" is satisfied by `pending` since full activation
304 // requires the registrar-side DS record.
305 if (statusFamily(observed.status) !== desiredStatus) {
306 observed = yield* dns.getDnssec({ zoneId }).pipe(
307 Effect.repeat({
308 schedule: Schedule.spaced("2 seconds"),
309 until: (o) => statusFamily(o.status) === desiredStatus,
310 times: 15,
311 }),
312 );
313 }
314
315 return toAttributes(zoneId, observed, initial);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 const zoneId = output.zoneId;
320 // Observe — if the zone itself is gone, so is its DNSSEC config.
321 const observed = yield* dns
322 .getDnssec({ zoneId })
323 .pipe(Effect.catchTag("InvalidRoute", () => Effect.undefined));
324 if (observed === undefined) return;
325 if (output.initialStatus === "disabled") {
326 // The zone had DNSSEC off before we managed it — deactivate.
327 // Cloudflare's DELETE endpoint only clears DNSSEC records *after*
328 // signing has been disabled, so deactivation goes through PATCH.
329 // Skip the call when it's already off (idempotent re-delete).
330 if (statusFamily(observed.status) === "disabled") return;
331 yield* dns
332 .patchDnssec({ zoneId, status: "disabled" })
333 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
334 return;
335 }
336 // The zone had DNSSEC on before we managed it — restore the
337 // enabled state and the flags it had at capture time.
338 if (
339 statusFamily(observed.status) === "active" &&
340 flag(observed.dnssecMultiSigner) === flag(output.initialMultiSigner) &&
341 flag(observed.dnssecPresigned) === flag(output.initialPresigned) &&
342 flag(observed.dnssecUseNsec3) === flag(output.initialUseNsec3)
343 ) {
344 return;
345 }
346 yield* dns
347 .patchDnssec({
348 zoneId,
349 status: "active",
350 dnssecMultiSigner: output.initialMultiSigner,
351 dnssecPresigned: output.initialPresigned,
352 dnssecUseNsec3: output.initialUseNsec3,
353 })
354 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
355 }),
356 });
357
358 interface InitialDnssec {
359 readonly status: DnssecDesiredStatus;
360 readonly multiSigner: boolean | undefined;
361 readonly presigned: boolean | undefined;
362 readonly useNsec3: boolean | undefined;
363 }
364
365 /**
366 * Collapse Cloudflare's five-state live status into the two-state
367 * desired family (`pending` is on its way to `active`,
368 * `pending-disabled` / `error` / unknown collapse to `disabled`).
369 */
370 const statusFamily = (status: string | null | undefined): DnssecDesiredStatus =>
371 status === "active" || status === "pending" ? "active" : "disabled";
372
373 const flag = (v: boolean | null | undefined): boolean => v ?? false;
374
375 const captureInitial = (observed: dns.GetDnssecResponse): InitialDnssec => ({
376 status: statusFamily(observed.status),
377 multiSigner: observed.dnssecMultiSigner ?? undefined,
378 presigned: observed.dnssecPresigned ?? undefined,
379 useNsec3: observed.dnssecUseNsec3 ?? undefined,
380 });
381
382 const matchesDesired = (
383 observed: dns.GetDnssecResponse,
384 news: DnssecProps,
385 desiredStatus: DnssecDesiredStatus,
386 ): boolean => {
387 if (statusFamily(observed.status) !== desiredStatus) return false;
388 if (
389 news.dnssecMultiSigner !== undefined &&
390 news.dnssecMultiSigner !== flag(observed.dnssecMultiSigner)
391 ) {
392 return false;
393 }
394 if (
395 news.dnssecPresigned !== undefined &&
396 news.dnssecPresigned !== flag(observed.dnssecPresigned)
397 ) {
398 return false;
399 }
400 if (news.dnssecUseNsec3 !== undefined && news.dnssecUseNsec3 !== flag(observed.dnssecUseNsec3)) {
401 return false;
402 }
403 return true;
404 };
405
406 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
407
408 const toAttributes = (
409 zoneId: string,
410 observed: dns.GetDnssecResponse | dns.PatchDnssecResponse,
411 initial: InitialDnssec,
412 ): DnssecAttributes => ({
413 zoneId,
414 status: observed.status ?? "disabled",
415 dnssecMultiSigner: undef(observed.dnssecMultiSigner),
416 dnssecPresigned: undef(observed.dnssecPresigned),
417 dnssecUseNsec3: undef(observed.dnssecUseNsec3),
418 algorithm: undef(observed.algorithm),
419 digest: undef(observed.digest),
420 digestAlgorithm: undef(observed.digestAlgorithm),
421 digestType: undef(observed.digestType),
422 ds: undef(observed.ds),
423 flags: undef(observed.flags),
424 keyTag: undef(observed.keyTag),
425 keyType: undef(observed.keyType),
426 publicKey: undef(observed.publicKey),
427 modifiedOn: undef(observed.modifiedOn),
428 initialStatus: initial.status,
429 initialMultiSigner: initial.multiSigner,
430 initialPresigned: initial.presigned,
431 initialUseNsec3: initial.useNsec3,
432 });