@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 276 lines 9.34 KB
Raw
1 import * as dns from "@distilled.cloud/cloudflare/dns";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.DNS.ZoneTransferPeer" as const;
13 type TypeId = typeof TypeId;
14
15 export interface ZoneTransferPeerProps {
16 /**
17 * Human-readable name of the peer. If omitted, a unique name is
18 * generated from the app, stage, and logical ID.
19 *
20 * Mutable — updated in place (PUT).
21 * @default ${app}-${stage}-${id}
22 */
23 name?: string;
24 /**
25 * IPv4/IPv6 address of the primary or secondary nameserver, depending
26 * on what zone this peer is linked to. For primary (outgoing) zones
27 * this is the secondary nameserver Cloudflare will NOTIFY; for
28 * secondary (incoming) zones it is the primary Cloudflare transfers
29 * from.
30 *
31 * Mutable — updated in place (PUT).
32 */
33 ip?: string;
34 /**
35 * DNS port of the primary or secondary nameserver.
36 *
37 * Mutable — updated in place (PUT).
38 * @default 53
39 */
40 port?: number;
41 /**
42 * TSIG used to authenticate zone transfers with this peer. Reference
43 * a {@link ZoneTransferTsig} via its `tsigId` attribute.
44 *
45 * Mutable — updated in place (PUT).
46 */
47 tsigId?: string;
48 /**
49 * Use the IXFR (incremental) transfer protocol instead of AXFR. Only
50 * applicable to secondary zones.
51 *
52 * Mutable — updated in place (PUT).
53 * @default false
54 */
55 ixfrEnable?: boolean;
56 }
57
58 export interface ZoneTransferPeerAttributes {
59 /** Identifier of the peer. */
60 peerId: string;
61 /** The Cloudflare account the peer belongs to. */
62 accountId: string;
63 /** Human-readable name of the peer. */
64 name: string;
65 /** Nameserver IP, if configured. */
66 ip: string | undefined;
67 /** Nameserver DNS port, if configured. */
68 port: number | undefined;
69 /** TSIG used to authenticate transfers, if configured. */
70 tsigId: string | undefined;
71 /** Whether IXFR transfers are enabled. */
72 ixfrEnable: boolean | undefined;
73 }
74
75 export type ZoneTransferPeer = Resource<
76 TypeId,
77 ZoneTransferPeerProps,
78 ZoneTransferPeerAttributes,
79 never,
80 Providers
81 >;
82
83 /**
84 * A Secondary DNS zone-transfer peer
85 * (`/accounts/{account_id}/secondary_dns/peers`) — an external
86 * nameserver Cloudflare exchanges zone transfers with. Link peers to a
87 * zone via {@link ZoneTransferIncoming} (secondary zones) or
88 * {@link ZoneTransferOutgoing} (primary zones).
89 *
90 * Requires the Secondary DNS (zone transfer) entitlement on the
91 * account. Cloudflare's create API only accepts a name; the provider
92 * follows up with an update when `ip`, `port`, `tsigId`, or
93 * `ixfrEnable` are declared, all of which remain mutable in place.
94 * ### Creating a Peer
95 * **Example:** Primary nameserver to transfer from
96 * ```typescript
97 * const peer = yield* Cloudflare.DNS.ZoneTransferPeer("Primary", {
98 * ip: "192.0.2.53",
99 * port: 53,
100 * });
101 * ```
102 *
103 * **Example:** Peer with TSIG authentication
104 * ```typescript
105 * const tsig = yield* Cloudflare.DNS.ZoneTransferTsig("TransferKey", {
106 * algo: "hmac-sha512.",
107 * secret: Redacted.make(process.env.TSIG_SECRET!),
108 * });
109 * const peer = yield* Cloudflare.DNS.ZoneTransferPeer("Primary", {
110 * ip: "192.0.2.53",
111 * tsigId: tsig.tsigId,
112 * ixfrEnable: true,
113 * });
114 * ```
115 *
116 * @see https://developers.cloudflare.com/dns/zone-setups/zone-transfers/
117 *
118 * @resource
119 * @product DNS
120 * @category Domains & DNS
121 */
122 export const ZoneTransferPeer = Resource<ZoneTransferPeer>(TypeId, {
123 aliases: ["Cloudflare.Dns.ZoneTransferPeer"],
124 });
125
126 /**
127 * Returns true if the given value is a ZoneTransferPeer resource.
128 */
129 export const isZoneTransferPeer = (value: unknown): value is ZoneTransferPeer =>
130 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
131
132 export const ZoneTransferPeerProvider = () =>
133 Provider.succeed(ZoneTransferPeer, {
134 stables: ["peerId", "accountId"],
135
136 list: Effect.fn(function* () {
137 const { accountId } = yield* yield* CloudflareEnvironment;
138 // Account-scoped collection (pattern b) — secondary_dns peers
139 // live under the account, not a zone. Exhaustively paginate and
140 // hydrate each row into the exact `read` Attributes shape.
141 return yield* dns.listZoneTransferPeers.pages({ accountId }).pipe(
142 Stream.runCollect,
143 Effect.map((chunk) =>
144 Array.from(chunk).flatMap((page) =>
145 (page.result ?? []).map((peer) => toAttributes(peer, accountId)),
146 ),
147 ),
148 );
149 }),
150
151 diff: Effect.fn(function* ({ output }) {
152 const { accountId } = yield* yield* CloudflareEnvironment;
153 if (output !== undefined && output.accountId !== accountId) {
154 return { action: "replace" } as const;
155 }
156 return undefined;
157 }),
158
159 read: Effect.fn(function* ({ id, output, olds }) {
160 const { accountId } = yield* yield* CloudflareEnvironment;
161 const acct = output?.accountId ?? accountId;
162
163 if (output?.peerId) {
164 const observed = yield* getPeer(acct, output.peerId);
165 return observed ? toAttributes(observed, acct) : undefined;
166 }
167 // Cold read — recover from lost state by matching the
168 // deterministic physical name. Peers carry no ownership markers,
169 // so gate takeover behind adoption.
170 const name = yield* createPeerName(id, olds?.name);
171 const match = yield* findByName(acct, name);
172 return match ? Unowned(toAttributes(match, acct)) : undefined;
173 }),
174
175 reconcile: Effect.fn(function* ({ id, news, output }) {
176 const { accountId } = yield* yield* CloudflareEnvironment;
177 const name = yield* createPeerName(id, news.name);
178 // Inputs are resolved to concrete values by Plan.
179 const desired = {
180 name,
181 ip: news.ip as string | undefined,
182 port: news.port,
183 tsigId: news.tsigId as string | undefined,
184 ixfrEnable: news.ixfrEnable,
185 };
186
187 // Observe — the id cached on `output` is a hint, not a guarantee.
188 let observed = output?.peerId
189 ? yield* getPeer(output.accountId ?? accountId, output.peerId)
190 : undefined;
191 const acct = observed ? (output?.accountId ?? accountId) : accountId;
192
193 if (!observed) {
194 // Ensure — Cloudflare's create only accepts `name`; the
195 // connection settings are applied by the sync step below.
196 observed = yield* dns.createZoneTransferPeer({ accountId, name });
197 }
198
199 // Sync — PUT with the full desired body; skip the call when no
200 // declared field differs from the observed cloud state.
201 const dirty =
202 observed.name !== desired.name ||
203 (desired.ip !== undefined && undef(observed.ip) !== desired.ip) ||
204 (desired.port !== undefined && undef(observed.port) !== desired.port) ||
205 (desired.tsigId !== undefined && undef(observed.tsigId) !== desired.tsigId) ||
206 (desired.ixfrEnable !== undefined && undef(observed.ixfrEnable) !== desired.ixfrEnable);
207
208 if (!dirty) {
209 return toAttributes(observed, acct);
210 }
211 const updated = yield* dns.updateZoneTransferPeer({
212 accountId: acct,
213 peerId: observed.id,
214 name: desired.name,
215 ip: desired.ip ?? undef(observed.ip),
216 port: desired.port ?? undef(observed.port),
217 tsigId: desired.tsigId ?? undef(observed.tsigId),
218 ixfrEnable: desired.ixfrEnable ?? undef(observed.ixfrEnable),
219 });
220 return toAttributes(updated, acct);
221 }),
222
223 delete: Effect.fn(function* ({ output }) {
224 yield* dns
225 .deleteZoneTransferPeer({
226 accountId: output.accountId,
227 peerId: output.peerId,
228 })
229 .pipe(Effect.catchTag("PeerNotFound", () => Effect.void));
230 }),
231 });
232
233 type ObservedPeer =
234 | dns.GetZoneTransferPeerResponse
235 | dns.CreateZoneTransferPeerResponse
236 | dns.UpdateZoneTransferPeerResponse;
237
238 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
239
240 /** Read a peer by id, mapping "gone" (404) to `undefined`. */
241 const getPeer = (accountId: string, peerId: string) =>
242 dns
243 .getZoneTransferPeer({ accountId, peerId })
244 .pipe(Effect.catchTag("PeerNotFound", () => Effect.undefined));
245
246 /**
247 * Find a peer by exact name. Names are not unique on Cloudflare's side;
248 * pick the lexicographically-first id for determinism.
249 */
250 const findByName = (accountId: string, name: string) =>
251 dns.listZoneTransferPeers.items({ accountId }).pipe(
252 Stream.filter((p) => p.name === name),
253 Stream.runCollect,
254 Effect.map((chunk) =>
255 Array.from(chunk)
256 .sort((a, b) => a.id.localeCompare(b.id))
257 .at(0),
258 ),
259 );
260
261 const createPeerName = (id: string, name: string | undefined) =>
262 Effect.gen(function* () {
263 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
264 });
265
266 const toAttributes = (peer: ObservedPeer, accountId: string): ZoneTransferPeerAttributes => ({
267 peerId: peer.id,
268 accountId,
269 name: peer.name,
270 // Cloudflare returns "" / 0 for unset ip/port on freshly-created
271 // peers — normalize those to undefined.
272 ip: undef(peer.ip) || undefined,
273 port: undef(peer.port) || undefined,
274 tsigId: undef(peer.tsigId) || undefined,
275 ixfrEnable: undef(peer.ixfrEnable),
276 });