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

main
ts 501 lines 17.2 KB
Raw
1 import * as dnsFirewall from "@distilled.cloud/cloudflare/dns-firewall";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.DNS.Firewall" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Attack mitigation settings for a DNS Firewall cluster.
18 */
19 export type AttackMitigation = {
20 /**
21 * When enabled, automatically mitigate random-prefix attacks to protect
22 * upstream DNS servers.
23 * @default false
24 */
25 enabled?: boolean;
26 /**
27 * Only mitigate attacks when upstream servers seem unhealthy.
28 * @default false
29 */
30 onlyWhenUpstreamUnhealthy?: boolean;
31 };
32
33 export type FirewallProps = {
34 /**
35 * DNS Firewall cluster name. Changing the name triggers a replacement —
36 * the name is the identity used for cold-state recovery. If omitted, a
37 * unique name is generated from the app, stage, and logical ID.
38 * @default ${app}-${stage}-${id}
39 */
40 name?: string;
41 /**
42 * Upstream DNS server IPs the cluster forwards queries to. At least one
43 * is required.
44 */
45 upstreamIps: string[];
46 /**
47 * Attack mitigation settings.
48 * @default disabled
49 */
50 attackMitigation?: AttackMitigation;
51 /**
52 * Whether to refuse to answer queries for the ANY type.
53 * @default false
54 */
55 deprecateAnyRequests?: boolean;
56 /**
57 * Whether to forward the client IP (resolver) subnet if no EDNS Client
58 * Subnet is sent.
59 * @default false
60 */
61 ecsFallback?: boolean;
62 /**
63 * Upper bound (in seconds) on how long responses are cached, regardless
64 * of the TTL received from the upstream nameservers.
65 * @default 900
66 */
67 maximumCacheTtl?: number;
68 /**
69 * Lower bound (in seconds) on how long responses are cached, regardless
70 * of the TTL received from the upstream nameservers.
71 * @default 60
72 */
73 minimumCacheTtl?: number;
74 /**
75 * How long (in seconds) DNS Firewall caches negative responses (e.g.
76 * NXDOMAIN) from the upstream servers. `null` uses Cloudflare's default
77 * behavior.
78 * @default null
79 */
80 negativeCacheTtl?: number | null;
81 /**
82 * Ratelimit in queries per second per datacenter, applied to queries
83 * sent to the upstream nameservers. `null` disables the limit.
84 * @default null
85 */
86 ratelimit?: number | null;
87 /**
88 * Number of retries for fetching DNS responses from upstream nameservers
89 * (not counting the initial attempt).
90 * @default 2
91 */
92 retries?: number;
93 /**
94 * Reverse DNS (PTR) mappings for the cluster's assigned IPs — a map of
95 * cluster IP address to PTR record content. Only the entries listed here
96 * are managed: entries are upserted, and removing an entry from this map
97 * leaves the PTR in place (clear it explicitly with an empty string).
98 */
99 reverseDns?: Record<string, string>;
100 };
101
102 export type FirewallAttributes = {
103 /**
104 * DNS Firewall cluster identifier (UUID).
105 */
106 dnsFirewallId: string;
107 /**
108 * The Cloudflare account the cluster belongs to.
109 */
110 accountId: string;
111 /**
112 * DNS Firewall cluster name.
113 */
114 name: string;
115 /**
116 * The Cloudflare-assigned anycast IPs of the cluster. Point NS glue
117 * records at these.
118 */
119 dnsFirewallIps: string[];
120 /**
121 * Upstream DNS server IPs the cluster forwards queries to.
122 */
123 upstreamIps: string[];
124 /**
125 * Attack mitigation settings.
126 */
127 attackMitigation: {
128 enabled: boolean;
129 onlyWhenUpstreamUnhealthy: boolean;
130 };
131 /**
132 * Whether queries for the ANY type are refused.
133 */
134 deprecateAnyRequests: boolean;
135 /**
136 * Whether the client IP (resolver) subnet is forwarded when no EDNS
137 * Client Subnet is sent.
138 */
139 ecsFallback: boolean;
140 /**
141 * Upper bound (in seconds) on response cache duration.
142 */
143 maximumCacheTtl: number;
144 /**
145 * Lower bound (in seconds) on response cache duration.
146 */
147 minimumCacheTtl: number;
148 /**
149 * Negative response cache duration (in seconds), or `null` for
150 * Cloudflare's default behavior.
151 */
152 negativeCacheTtl: number | null;
153 /**
154 * Ratelimit in queries per second per datacenter, or `null` when
155 * disabled.
156 */
157 ratelimit: number | null;
158 /**
159 * Number of retries for fetching DNS responses from upstream
160 * nameservers.
161 */
162 retries: number;
163 /**
164 * Reverse DNS (PTR) mappings managed on the cluster, when the
165 * `reverseDns` prop is set.
166 */
167 reverseDns: Record<string, string> | undefined;
168 /**
169 * Last modification time of the cluster.
170 */
171 modifiedOn: string;
172 };
173
174 export type Firewall = Resource<TypeId, FirewallProps, FirewallAttributes, never, Providers>;
175
176 /**
177 * A Cloudflare DNS Firewall cluster.
178 *
179 * DNS Firewall sits in front of your authoritative DNS infrastructure,
180 * caching responses on Cloudflare's anycast network and shielding the
181 * upstream nameservers from attack traffic. Creating a cluster assigns a
182 * set of Cloudflare anycast IPs (`dnsFirewallIps`) that you point NS glue
183 * records at; queries hitting those IPs are answered from cache or
184 * forwarded to your `upstreamIps`.
185 *
186 * DNS Firewall is a paid add-on (typically Enterprise / contract). On
187 * accounts without the entitlement, creation fails with the typed
188 * `DnsFirewallNotEntitled` error (Cloudflare error code 10101).
189 *
190 * All settings are mutable in place; only `name` (the cold-state recovery
191 * identity) triggers a replacement.
192 * ### Creating a Cluster
193 * **Example:** Basic cluster
194 * ```typescript
195 * const cluster = yield* Cloudflare.DNS.Firewall("dns-shield", {
196 * upstreamIps: ["192.0.2.1", "192.0.2.2"],
197 * });
198 * // Point NS glue records at the assigned anycast IPs:
199 * const ips = cluster.dnsFirewallIps;
200 * ```
201 *
202 * **Example:** Tuned caching and attack mitigation
203 * ```typescript
204 * const cluster = yield* Cloudflare.DNS.Firewall("dns-shield", {
205 * upstreamIps: ["192.0.2.1"],
206 * minimumCacheTtl: 120,
207 * maximumCacheTtl: 3600,
208 * negativeCacheTtl: 300,
209 * ratelimit: 600,
210 * retries: 2,
211 * attackMitigation: {
212 * enabled: true,
213 * onlyWhenUpstreamUnhealthy: true,
214 * },
215 * });
216 * ```
217 *
218 * ### Reverse DNS
219 * **Example:** Managing PTR records for cluster IPs
220 * ```typescript
221 * const cluster = yield* Cloudflare.DNS.Firewall("dns-shield", {
222 * upstreamIps: ["192.0.2.1"],
223 * reverseDns: {
224 * "203.0.113.1": "ns1.example.com",
225 * },
226 * });
227 * ```
228 *
229 * @see https://developers.cloudflare.com/dns/dns-firewall/
230 *
231 * @resource
232 * @product DNS Firewall
233 * @category Domains & DNS
234 */
235 export const Firewall = Resource<Firewall>(TypeId, {
236 aliases: ["Cloudflare.DnsFirewall"],
237 });
238
239 /**
240 * Returns true if the given value is a DnsFirewall resource.
241 */
242 export const isFirewall = (value: unknown): value is Firewall =>
243 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
244
245 export const FirewallProvider = () =>
246 Provider.succeed(Firewall, {
247 stables: ["dnsFirewallId", "accountId", "dnsFirewallIps"],
248 diff: Effect.fn(function* ({ id, olds, news, output }) {
249 const { accountId } = yield* yield* CloudflareEnvironment;
250 if (!isResolved(news)) return undefined;
251 if ((output?.accountId ?? accountId) !== accountId) {
252 return { action: "replace" } as const;
253 }
254 // The name is the cold-state recovery identity — renames replace.
255 const oldName = output?.name ?? (yield* createClusterName(id, olds.name));
256 // Auto-generated names are engine-owned: the deployed name stays
257 // authoritative even if the generator would name this id differently
258 // today. Only an explicit user-provided name can force a replace.
259 const name = news.name ?? oldName;
260 if (name !== oldName) {
261 return { action: "replace" } as const;
262 }
263 return undefined;
264 }),
265 read: Effect.fn(function* ({ id, output, olds }) {
266 const { accountId } = yield* yield* CloudflareEnvironment;
267 const acct = output?.accountId ?? accountId;
268
269 if (output?.dnsFirewallId) {
270 const observed = yield* getCluster(acct, output.dnsFirewallId);
271 if (!observed) return undefined;
272 const reverseDns =
273 olds?.reverseDns !== undefined ? yield* getReverseDns(acct, observed.id) : undefined;
274 return toAttributes(observed, acct, reverseDns);
275 }
276
277 // Cold read — recover from lost state by matching the deterministic
278 // physical name. Cluster names are not guaranteed unique and carry
279 // no ownership markers, so report the match as `Unowned`: the
280 // engine refuses to take it over unless `adopt` is set.
281 const name = yield* createClusterName(id, olds?.name);
282 const match = yield* findByName(acct, name);
283 if (!match) return undefined;
284 const reverseDns =
285 olds?.reverseDns !== undefined ? yield* getReverseDns(acct, match.id) : undefined;
286 return Unowned(toAttributes(match, acct, reverseDns));
287 }),
288 list: Effect.fn(function* () {
289 // Account-scoped collection: exhaustively paginate the DNS Firewall
290 // list for the ambient account. Each list item already carries the
291 // full cluster shape (identical to `getDnsFirewall`), so it maps
292 // directly into the `read` Attributes shape — no per-item hydration
293 // needed. `reverseDns` is left `undefined` (the same shape `read`
294 // produces when no managed PTR map is tracked).
295 const { accountId } = yield* yield* CloudflareEnvironment;
296 return yield* dnsFirewall.listDnsFirewalls.pages({ accountId }).pipe(
297 Stream.runCollect,
298 Effect.map((chunk) =>
299 Array.from(chunk).flatMap((page) =>
300 page.result.map((cluster) =>
301 toAttributes({ ...cluster, accountId }, accountId, undefined),
302 ),
303 ),
304 ),
305 );
306 }),
307 reconcile: Effect.fn(function* ({ id, news, output }) {
308 const { accountId } = yield* yield* CloudflareEnvironment;
309 // Prefer the deployed name: regenerating would rename the deployed
310 // cluster if the generator's output for this id ever drifts.
311 const name = output?.name ?? (yield* createClusterName(id, news.name));
312
313 // Observe — the id cached on `output` is a hint, not a guarantee: a
314 // missing cluster falls through to "missing" and we recreate.
315 const observed = output?.dnsFirewallId
316 ? yield* getCluster(output.accountId ?? accountId, output.dnsFirewallId)
317 : undefined;
318
319 let synced: ObservedCluster;
320 if (!observed) {
321 // Ensure — greenfield (or out-of-band delete): create with the
322 // full desired body. Names are not unique on Cloudflare's side,
323 // so there is no AlreadyExists race to tolerate.
324 const created = yield* dnsFirewall.createDnsFirewall({
325 accountId,
326 name,
327 upstreamIps: news.upstreamIps,
328 attackMitigation: news.attackMitigation,
329 deprecateAnyRequests: news.deprecateAnyRequests,
330 ecsFallback: news.ecsFallback,
331 maximumCacheTtl: news.maximumCacheTtl,
332 minimumCacheTtl: news.minimumCacheTtl,
333 negativeCacheTtl: news.negativeCacheTtl,
334 ratelimit: news.ratelimit,
335 retries: news.retries,
336 });
337 synced = { ...created, accountId };
338 } else {
339 // Sync — diff observed cloud state against the desired settings
340 // (props with their documented defaults applied) and PATCH only
341 // when something actually differs.
342 const desired = {
343 name,
344 upstreamIps: news.upstreamIps,
345 attackMitigation: {
346 enabled: news.attackMitigation?.enabled ?? false,
347 onlyWhenUpstreamUnhealthy: news.attackMitigation?.onlyWhenUpstreamUnhealthy ?? false,
348 },
349 deprecateAnyRequests: news.deprecateAnyRequests ?? false,
350 ecsFallback: news.ecsFallback ?? false,
351 maximumCacheTtl: news.maximumCacheTtl ?? 900,
352 minimumCacheTtl: news.minimumCacheTtl ?? 60,
353 negativeCacheTtl: news.negativeCacheTtl ?? null,
354 ratelimit: news.ratelimit ?? null,
355 retries: news.retries ?? 2,
356 };
357 const observedMitigation = normalizeMitigation(observed.attackMitigation);
358 const dirty =
359 observed.name !== desired.name ||
360 !sameIps(observed.upstreamIps, desired.upstreamIps) ||
361 observedMitigation.enabled !== desired.attackMitigation.enabled ||
362 observedMitigation.onlyWhenUpstreamUnhealthy !==
363 desired.attackMitigation.onlyWhenUpstreamUnhealthy ||
364 observed.deprecateAnyRequests !== desired.deprecateAnyRequests ||
365 observed.ecsFallback !== desired.ecsFallback ||
366 observed.maximumCacheTtl !== desired.maximumCacheTtl ||
367 observed.minimumCacheTtl !== desired.minimumCacheTtl ||
368 observed.negativeCacheTtl !== desired.negativeCacheTtl ||
369 observed.ratelimit !== desired.ratelimit ||
370 observed.retries !== desired.retries;
371
372 synced = dirty
373 ? {
374 ...(yield* dnsFirewall.patchDnsFirewall({
375 accountId: observed.accountId,
376 dnsFirewallId: observed.id,
377 ...desired,
378 })),
379 accountId: observed.accountId,
380 }
381 : observed;
382 }
383
384 // Sync reverse DNS (PTR) entries when managed. Only the entries in
385 // the desired map are reconciled — observed entries outside the map
386 // are left untouched.
387 let reverseDns: Record<string, string> | undefined;
388 if (news.reverseDns !== undefined) {
389 const observedPtr = yield* getReverseDns(synced.accountId, synced.id);
390 const dirtyPtr = Object.entries(news.reverseDns).some(
391 ([ip, ptr]) => observedPtr[ip] !== ptr,
392 );
393 if (dirtyPtr) {
394 yield* dnsFirewall.patchReverseDn({
395 accountId: synced.accountId,
396 dnsFirewallId: synced.id,
397 ptr: news.reverseDns,
398 });
399 }
400 reverseDns = { ...observedPtr, ...news.reverseDns };
401 }
402
403 return toAttributes(synced, synced.accountId, reverseDns);
404 }),
405 delete: Effect.fn(function* ({ output }) {
406 yield* dnsFirewall
407 .deleteDnsFirewall({
408 accountId: output.accountId,
409 dnsFirewallId: output.dnsFirewallId,
410 })
411 .pipe(Effect.catchTag("DnsFirewallNotFound", () => Effect.void));
412 }),
413 });
414
415 type ObservedCluster = dnsFirewall.GetDnsFirewallResponse & {
416 accountId: string;
417 };
418
419 /**
420 * Read a cluster by id, mapping "gone" (`DnsFirewallNotFound`, Cloudflare
421 * error code 11001) to `undefined`.
422 */
423 const getCluster = (accountId: string, dnsFirewallId: string) =>
424 dnsFirewall.getDnsFirewall({ accountId, dnsFirewallId }).pipe(
425 Effect.map((c): ObservedCluster => ({ ...c, accountId })),
426 Effect.catchTag("DnsFirewallNotFound", () => Effect.undefined),
427 );
428
429 /**
430 * Read the reverse DNS (PTR) map of a cluster, narrowing the distilled
431 * `Record<string, unknown>` values to strings.
432 */
433 const getReverseDns = (accountId: string, dnsFirewallId: string) =>
434 dnsFirewall
435 .getReverseDn({ accountId, dnsFirewallId })
436 .pipe(
437 Effect.map((r) =>
438 Object.fromEntries(
439 Object.entries(r.ptr).flatMap(([ip, ptr]) =>
440 typeof ptr === "string" && ptr !== "" ? [[ip, ptr]] : [],
441 ),
442 ),
443 ),
444 );
445
446 /**
447 * Find a cluster by exact name. The list API has no name filter, so scan
448 * the (paginated) account list client-side. If several clusters carry the
449 * same name, pick the lexicographically smallest id for determinism.
450 */
451 const findByName = (accountId: string, name: string) =>
452 dnsFirewall.listDnsFirewalls.items({ accountId }).pipe(
453 Stream.filter((c) => c.name === name),
454 Stream.runCollect,
455 Effect.map((chunk) =>
456 Array.from(chunk)
457 .sort((a, b) => a.id.localeCompare(b.id))
458 .at(0),
459 ),
460 Effect.map((match) =>
461 match ? ({ ...match, accountId } satisfies ObservedCluster) : undefined,
462 ),
463 );
464
465 const createClusterName = (id: string, name: string | undefined) =>
466 Effect.gen(function* () {
467 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
468 });
469
470 const normalizeMitigation = (
471 mitigation: dnsFirewall.GetDnsFirewallResponse["attackMitigation"],
472 ) => ({
473 enabled: mitigation?.enabled ?? false,
474 onlyWhenUpstreamUnhealthy: mitigation?.onlyWhenUpstreamUnhealthy ?? false,
475 });
476
477 const sameIps = (observed: readonly string[], desired: readonly string[]) =>
478 observed.length === desired.length &&
479 [...observed].sort().join(",") === [...desired].sort().join(",");
480
481 const toAttributes = (
482 cluster: ObservedCluster,
483 accountId: string,
484 reverseDns: Record<string, string> | undefined,
485 ): FirewallAttributes => ({
486 dnsFirewallId: cluster.id,
487 accountId,
488 name: cluster.name,
489 dnsFirewallIps: [...cluster.dnsFirewallIps],
490 upstreamIps: [...cluster.upstreamIps],
491 attackMitigation: normalizeMitigation(cluster.attackMitigation),
492 deprecateAnyRequests: cluster.deprecateAnyRequests,
493 ecsFallback: cluster.ecsFallback,
494 maximumCacheTtl: cluster.maximumCacheTtl,
495 minimumCacheTtl: cluster.minimumCacheTtl,
496 negativeCacheTtl: cluster.negativeCacheTtl,
497 ratelimit: cluster.ratelimit,
498 retries: cluster.retries,
499 reverseDns,
500 modifiedOn: cluster.modifiedOn,
501 });