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

main
ts 271 lines 9.53 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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.DNS.ZoneTransferOutgoing" as const;
12 type TypeId = typeof TypeId;
13
14 export interface ZoneTransferOutgoingProps {
15 /**
16 * Primary zone whose outgoing transfer configuration is managed.
17 * Stable — the configuration is a per-zone singleton, so changing the
18 * zone triggers a replacement.
19 */
20 zoneId: string;
21 /**
22 * Zone name (e.g. `example.com.`).
23 *
24 * Mutable — updated in place (PUT).
25 */
26 name: string;
27 /**
28 * Peers (by id) Cloudflare NOTIFYs and serves AXFR/IXFR to.
29 * Reference {@link ZoneTransferPeer} resources via their `peerId`
30 * attribute.
31 *
32 * Mutable — updated in place (PUT).
33 */
34 peers: string[];
35 /**
36 * Whether outgoing transfers are enabled for the zone. Mapped to the
37 * dedicated enable/disable endpoints, separate from the
38 * configuration's CRUD.
39 *
40 * Mutable — toggled in place.
41 * @default true
42 */
43 enabled?: boolean;
44 }
45
46 export interface ZoneTransferOutgoingAttributes {
47 /** Zone whose outgoing transfer configuration is managed. */
48 zoneId: string;
49 /** Identifier of the configuration (mirrors the zone id). */
50 id: string | undefined;
51 /** Zone name. */
52 name: string | undefined;
53 /** Peer ids the zone is served to. */
54 peers: string[];
55 /** Whether outgoing transfers are enabled. */
56 enabled: boolean;
57 /** SOA serial of the most recent transfer. */
58 soaSerial: number | undefined;
59 /** When the zone was last transferred out. */
60 lastTransferredTime: string | undefined;
61 /** When the zone was last checked. */
62 checkedTime: string | undefined;
63 /** When the configuration was created. */
64 createdTime: string | undefined;
65 }
66
67 export type ZoneTransferOutgoing = Resource<
68 TypeId,
69 ZoneTransferOutgoingProps,
70 ZoneTransferOutgoingAttributes,
71 never,
72 Providers
73 >;
74
75 /**
76 * The outgoing zone-transfer configuration of a primary zone
77 * (`/zones/{zone_id}/secondary_dns/outgoing`) — links the zone to the
78 * {@link ZoneTransferPeer | peers} Cloudflare NOTIFYs and serves
79 * AXFR/IXFR to, and toggles transfers on or off via the dedicated
80 * enable/disable endpoints.
81 *
82 * Requires the Secondary DNS (zone transfer) entitlement on the zone.
83 * The configuration is a per-zone singleton: `zoneId` is the identity
84 * (replacement on change), everything else is mutable in place.
85 * ### Configuring outgoing transfers
86 * **Example:** Serve a primary zone to an external secondary
87 * ```typescript
88 * const peer = yield* Cloudflare.DNS.ZoneTransferPeer("Secondary", {
89 * ip: "192.0.2.53",
90 * port: 53,
91 * });
92 * yield* Cloudflare.DNS.ZoneTransferOutgoing("Outgoing", {
93 * zoneId: zone.zoneId,
94 * name: "example.com.",
95 * peers: [peer.peerId],
96 * });
97 * ```
98 *
99 * **Example:** Configure transfers but keep them disabled
100 * ```typescript
101 * yield* Cloudflare.DNS.ZoneTransferOutgoing("Outgoing", {
102 * zoneId: zone.zoneId,
103 * name: "example.com.",
104 * peers: [peer.peerId],
105 * enabled: false,
106 * });
107 * ```
108 *
109 * @see https://developers.cloudflare.com/dns/zone-setups/zone-transfers/setup/
110 *
111 * @resource
112 * @product DNS
113 * @category Domains & DNS
114 */
115 export const ZoneTransferOutgoing = Resource<ZoneTransferOutgoing>(TypeId, {
116 aliases: ["Cloudflare.Dns.ZoneTransferOutgoing"],
117 });
118
119 /**
120 * Returns true if the given value is a ZoneTransferOutgoing resource.
121 */
122 export const isZoneTransferOutgoing = (value: unknown): value is ZoneTransferOutgoing =>
123 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
124
125 export const ZoneTransferOutgoingProvider = () =>
126 Provider.succeed(ZoneTransferOutgoing, {
127 stables: ["zoneId", "id", "createdTime"],
128
129 list: Effect.fn(function* () {
130 const { accountId } = yield* yield* CloudflareEnvironment;
131 // The outgoing transfer config is a per-zone singleton with no
132 // account-wide enumeration API — walk every zone and read its
133 // config. Most zones have none (or lack the Secondary DNS
134 // entitlement); skip those via the typed not-found/not-allowed
135 // tags rather than failing the whole enumeration.
136 const allZones = yield* listAllZones(accountId);
137 const rows = yield* Effect.forEach(
138 allZones.map((zone) => zone.id),
139 (zoneId) =>
140 getOutgoing(zoneId).pipe(
141 Effect.catchTag("OutgoingZoneTransfersNotAllowed", () => Effect.undefined),
142 Effect.flatMap((observed) =>
143 observed === undefined
144 ? Effect.undefined
145 : getEnabled(zoneId).pipe(
146 Effect.map((enabled) => toAttributes(observed, zoneId, enabled)),
147 ),
148 ),
149 ),
150 { concurrency: 10 },
151 );
152 return rows.filter((row): row is ZoneTransferOutgoingAttributes => row !== undefined);
153 }),
154
155 diff: Effect.fn(function* ({ olds = {}, news, output }) {
156 const o = olds as ZoneTransferOutgoingProps;
157 const n = news as ZoneTransferOutgoingProps;
158 // zoneId is the resource's identity (per-zone singleton).
159 // Input<string> — compare only once concrete.
160 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
161 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
162 return { action: "replace" } as const;
163 }
164 return undefined;
165 }),
166
167 read: Effect.fn(function* ({ output, olds }) {
168 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
169 if (!zoneId) return undefined;
170 const observed = yield* getOutgoing(zoneId);
171 if (observed === undefined) return undefined;
172 const enabled = yield* getEnabled(zoneId);
173 const attrs = toAttributes(observed, zoneId, enabled);
174 // The configuration carries no ownership markers. With no prior
175 // state, gate takeover of an existing configuration behind
176 // adoption.
177 return output === undefined ? Unowned(attrs) : attrs;
178 }),
179
180 reconcile: Effect.fn(function* ({ news }) {
181 // Inputs are resolved to concrete values by Plan.
182 const zoneId = news.zoneId as string;
183 const peers = news.peers as string[];
184 const desiredEnabled = news.enabled ?? true;
185
186 // Observe — singleton keyed by the zone itself.
187 let observed = yield* getOutgoing(zoneId);
188
189 if (!observed) {
190 // Ensure — first-time link of the zone to its peers.
191 observed = yield* dns.createZoneTransferOutgoing({
192 zoneId,
193 name: news.name,
194 peers,
195 });
196 } else {
197 // Sync — PUT with the full desired body; skip the call when the
198 // observed configuration already matches.
199 const dirty = undef(observed.name) !== news.name || !samePeers(observed.peers ?? [], peers);
200 if (dirty) {
201 observed = yield* dns.updateZoneTransferOutgoing({
202 zoneId,
203 name: news.name,
204 peers,
205 });
206 }
207 }
208
209 // Sync enabled state — the enable/disable toggle lives on its own
210 // endpoints; diff the observed status and only call on a delta.
211 const observedEnabled = yield* getEnabled(zoneId);
212 if (observedEnabled !== desiredEnabled) {
213 yield* desiredEnabled
214 ? dns.enableZoneTransferOutgoing({ zoneId })
215 : dns.disableZoneTransferOutgoing({ zoneId });
216 }
217
218 return toAttributes(observed, zoneId, desiredEnabled);
219 }),
220
221 delete: Effect.fn(function* ({ output }) {
222 yield* dns.deleteZoneTransferOutgoing({ zoneId: output.zoneId }).pipe(
223 Effect.catchTags({
224 OutgoingZoneTransferNotFound: () => Effect.void,
225 // Cloudflare answers DELETE on a zone without the outgoing
226 // entitlement (or with no configuration) with a 401 — if we
227 // could never have created it, there is nothing to delete.
228 OutgoingZoneTransfersNotAllowed: () => Effect.void,
229 }),
230 );
231 }),
232 });
233
234 type ObservedOutgoing =
235 | dns.GetZoneTransferOutgoingResponse
236 | dns.CreateZoneTransferOutgoingResponse
237 | dns.UpdateZoneTransferOutgoingResponse;
238
239 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
240
241 /** Read the outgoing configuration, mapping "not linked" to undefined. */
242 const getOutgoing = (zoneId: string) =>
243 dns
244 .getZoneTransferOutgoing({ zoneId })
245 .pipe(Effect.catchTag("OutgoingZoneTransferNotFound", () => Effect.undefined));
246
247 /** Observe the enable/disable toggle (reported as e.g. "Enabled"). */
248 const getEnabled = (zoneId: string) =>
249 dns
250 .getZoneTransferOutgoingStatus({ zoneId })
251 .pipe(Effect.map((status) => status.toLowerCase().startsWith("enabled")));
252
253 const samePeers = (observed: readonly string[], desired: readonly string[]) =>
254 observed.length === desired.length &&
255 [...observed].sort().join(",") === [...desired].sort().join(",");
256
257 const toAttributes = (
258 outgoing: ObservedOutgoing,
259 zoneId: string,
260 enabled: boolean,
261 ): ZoneTransferOutgoingAttributes => ({
262 zoneId,
263 id: undef(outgoing.id),
264 name: undef(outgoing.name),
265 peers: [...(undef(outgoing.peers) ?? [])],
266 enabled,
267 soaSerial: undef(outgoing.soaSerial),
268 lastTransferredTime: undef(outgoing.lastTransferredTime),
269 checkedTime: undef(outgoing.checkedTime),
270 createdTime: undef(outgoing.createdTime),
271 });