@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, 04:45 UTC

main
ts 389 lines 13.4 KB
Raw
1 import * as addressing from "@distilled.cloud/cloudflare/addressing";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 export class AddressMapUnexpectedResponse extends Data.TaggedError("AddressMapUnexpectedResponse")<{
12 readonly message: string;
13 readonly cause?: unknown;
14 }> {}
15
16 const TypeId = "Cloudflare.Addressing.AddressMap" as const;
17 type TypeId = typeof TypeId;
18
19 /**
20 * A zone or account membership on an Address Map. Zones (or whole accounts)
21 * listed here are assigned the IPs on the map. A zone membership takes
22 * priority over an account membership.
23 */
24 export interface AddressMapMembership {
25 /**
26 * The zone id (for `kind: "zone"`) or account id (for `kind: "account"`)
27 * to assign the map's IPs to.
28 *
29 * Note: due to the shape of the Cloudflare API, account memberships can
30 * only target the account that owns the Address Map.
31 */
32 identifier: string;
33 /**
34 * Whether the membership targets a zone or a whole account.
35 */
36 kind: "zone" | "account";
37 }
38
39 export interface AddressMapProps {
40 /**
41 * An optional description used to describe the types of IPs or zones on
42 * the map. Mutable — patched in place.
43 */
44 description?: string;
45 /**
46 * Whether the Address Map is enabled. Cloudflare's DNS will not respond
47 * with the map's IP addresses until the map is enabled. Mutable.
48 * @default false
49 */
50 enabled?: boolean;
51 /**
52 * Default SNI to present to legacy TLS clients that do not send the TLS
53 * server name indicator. Mutable — patch-only (set in a post-create sync
54 * step).
55 */
56 defaultSni?: string;
57 /**
58 * The set of IPs on the Address Map. Mutable — synced per-IP via
59 * PUT/DELETE against observed cloud state.
60 * @default []
61 */
62 ips?: string[];
63 /**
64 * Zones and accounts assigned IPs on this Address Map. Mutable — synced
65 * per-membership via PUT/DELETE against observed cloud state.
66 * @default []
67 */
68 memberships?: AddressMapMembership[];
69 }
70
71 export interface AddressMapAttributes {
72 /** Cloudflare-assigned identifier of the Address Map. */
73 addressMapId: string;
74 /** The Cloudflare account the Address Map belongs to. */
75 accountId: string;
76 /**
77 * If `false`, the Address Map cannot be deleted via the API (true for
78 * Cloudflare-managed maps).
79 */
80 canDelete: boolean;
81 /**
82 * If `false`, the IPs on the Address Map cannot be modified via the API
83 * (true for Cloudflare-managed maps).
84 */
85 canModifyIps: boolean;
86 /** The map's description, if set. */
87 description: string | undefined;
88 /** Whether the Address Map is enabled. */
89 enabled: boolean;
90 /** Default SNI presented to legacy TLS clients, if set. */
91 defaultSni: string | undefined;
92 /** The set of IPs currently on the Address Map. */
93 ips: string[];
94 /** Zone/account memberships currently on the Address Map. */
95 memberships: { identifier: string; kind: "zone" | "account" }[];
96 /** ISO8601 creation timestamp. */
97 createdAt: string | undefined;
98 /** ISO8601 last-modified timestamp. */
99 modifiedAt: string | undefined;
100 }
101
102 export type AddressMap = Resource<TypeId, AddressMapProps, AddressMapAttributes, never, Providers>;
103
104 /**
105 * A Cloudflare Address Map — assigns account-owned or Cloudflare-assigned
106 * static IPs to zones (BYOIP / Enterprise static IPs).
107 *
108 * Requires the BYOIP add-on or Cloudflare-assigned static IPs on the
109 * account; without the entitlement every mutating call fails with the typed
110 * `FeatureNotEnabled` error (`address_maps_not_enabled_on_account`).
111 * ### Creating an Address Map
112 * **Example:** Disabled map with a description
113 * ```typescript
114 * const map = yield* Cloudflare.Addressing.AddressMap("static-ips", {
115 * description: "static ingress IPs",
116 * enabled: false,
117 * });
118 * ```
119 *
120 * **Example:** Map with IPs and zone memberships
121 * ```typescript
122 * const map = yield* Cloudflare.Addressing.AddressMap("ingress", {
123 * description: "ingress",
124 * enabled: true,
125 * ips: ["192.0.2.1"],
126 * memberships: [{ identifier: zone.zoneId, kind: "zone" }],
127 * });
128 * ```
129 *
130 * ### Legacy TLS clients
131 * **Example:** Default SNI for clients without SNI
132 * ```typescript
133 * const map = yield* Cloudflare.Addressing.AddressMap("legacy", {
134 * enabled: true,
135 * defaultSni: "example.com",
136 * });
137 * ```
138 *
139 * @see https://developers.cloudflare.com/byoip/address-maps/
140 *
141 * @resource
142 * @product Addressing
143 * @category Network
144 */
145 export const AddressMap = Resource<AddressMap>(TypeId);
146
147 /**
148 * Returns true if the given value is an AddressMap resource.
149 */
150 export const isAddressMap = (value: unknown): value is AddressMap =>
151 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
152
153 export const AddressMapProvider = () =>
154 Provider.succeed(AddressMap, {
155 stables: ["addressMapId", "accountId", "canDelete", "canModifyIps", "createdAt"],
156
157 list: Effect.fn(function* () {
158 const { accountId } = yield* yield* CloudflareEnvironment;
159 // The account-scoped list endpoint omits `ips` and `memberships`,
160 // so enumerate ids exhaustively, then hydrate each into the exact
161 // `read` shape via `getAddressMap` (typed per-item not-found).
162 const ids = yield* addressing.listAddressMaps.pages({ accountId }).pipe(
163 Stream.runCollect,
164 Effect.map((chunk) =>
165 Array.from(chunk).flatMap((page) =>
166 (page.result ?? []).flatMap((m) => (m.id ? [m.id] : [])),
167 ),
168 ),
169 );
170 const rows = yield* Effect.forEach(
171 ids,
172 (addressMapId) =>
173 getMap(accountId, addressMapId).pipe(
174 Effect.map((observed) => (observed ? toAttributes(observed, accountId) : undefined)),
175 ),
176 { concurrency: 10 },
177 );
178 return rows.filter((row): row is AddressMapAttributes => row !== undefined);
179 }),
180
181 read: Effect.fn(function* ({ output }) {
182 // Address Maps have no name field to match on, so there is no
183 // reliable cold-lookup — lost state is treated as gone and the
184 // engine recreates.
185 if (!output?.addressMapId) return undefined;
186 const observed = yield* getMap(output.accountId, output.addressMapId);
187 return observed ? toAttributes(observed, output.accountId) : undefined;
188 }),
189
190 reconcile: Effect.fn(function* ({ news, output }) {
191 const { accountId } = yield* yield* CloudflareEnvironment;
192 const acct = output?.accountId ?? accountId;
193
194 // 1. Observe — the map id cached on `output` is a hint, not a
195 // guarantee: a missing map falls through to create.
196 let observed = output?.addressMapId ? yield* getMap(acct, output.addressMapId) : undefined;
197
198 // 2. Ensure — create with the full desired body (ips + memberships
199 // are accepted inline on create). `defaultSni` is patch-only and
200 // handled by the sync step below.
201 if (!observed) {
202 const created = yield* addressing.createAddressMap({
203 accountId,
204 description: news.description,
205 enabled: news.enabled ?? false,
206 ips: desiredIps(news),
207 memberships: desiredMemberships(news),
208 });
209 if (!created.id) {
210 return yield* new AddressMapUnexpectedResponse({
211 message: "Cloudflare did not return an Address Map id",
212 });
213 }
214 // Re-observe so every sync step diffs against authoritative state.
215 observed = yield* getMap(accountId, created.id);
216 if (!observed) {
217 return yield* new AddressMapUnexpectedResponse({
218 message: "Address Map disappeared right after creation",
219 });
220 }
221 }
222
223 const addressMapId = observed.id!;
224
225 // 3a. Sync scalar fields (description / enabled / defaultSni) —
226 // skip the patch entirely on a no-op.
227 const scalarDirty =
228 (news.description ?? "") !== (observed.description ?? "") ||
229 (news.enabled ?? false) !== (observed.enabled ?? false) ||
230 (news.defaultSni !== undefined && news.defaultSni !== (observed.defaultSni ?? undefined));
231 if (scalarDirty) {
232 yield* addressing.patchAddressMap({
233 accountId: acct,
234 addressMapId,
235 description: news.description ?? "",
236 enabled: news.enabled ?? false,
237 defaultSni: news.defaultSni,
238 });
239 }
240
241 // 3b. Sync IPs — diff observed cloud IPs against desired, apply
242 // only the per-IP delta.
243 const observedIps = (observed.ips ?? []).flatMap((ip) => (ip.ip ? [ip.ip] : []));
244 const wantedIps = desiredIps(news);
245 for (const ip of wantedIps) {
246 if (!observedIps.includes(ip)) {
247 yield* addressing.putAddressMapIp({
248 accountId: acct,
249 addressMapId,
250 ipAddress: ip,
251 });
252 }
253 }
254 for (const ip of observedIps) {
255 if (!wantedIps.includes(ip)) {
256 yield* addressing.deleteAddressMapIp({
257 accountId: acct,
258 addressMapId,
259 ipAddress: ip,
260 });
261 }
262 }
263
264 // 3c. Sync memberships — same observed-vs-desired delta, routed to
265 // the zone/account variant per membership kind.
266 const observedMemberships = narrowMemberships(observed.memberships);
267 const wantedMemberships = desiredMemberships(news);
268 for (const m of wantedMemberships) {
269 const present = observedMemberships.some(
270 (o) => o.identifier === m.identifier && o.kind === m.kind,
271 );
272 if (!present) {
273 yield* m.kind === "zone"
274 ? addressing.putAddressMapZone({
275 accountId: acct,
276 addressMapId,
277 zoneId: m.identifier,
278 })
279 : addressing.putAddressMapAccount({
280 accountId: acct,
281 addressMapId,
282 memberAccountId: m.identifier,
283 });
284 }
285 }
286 for (const m of observedMemberships) {
287 const wanted = wantedMemberships.some(
288 (w) => w.identifier === m.identifier && w.kind === m.kind,
289 );
290 if (!wanted) {
291 yield* m.kind === "zone"
292 ? addressing.deleteAddressMapZone({
293 accountId: acct,
294 addressMapId,
295 zoneId: m.identifier,
296 })
297 : addressing.deleteAddressMapAccount({
298 accountId: acct,
299 addressMapId,
300 memberAccountId: m.identifier,
301 });
302 }
303 }
304
305 // 4. Return — re-read so the persisted attributes reflect the final
306 // converged cloud state.
307 const final = yield* getMap(acct, addressMapId);
308 if (!final) {
309 return yield* new AddressMapUnexpectedResponse({
310 message: "Address Map disappeared during reconcile",
311 });
312 }
313 return toAttributes(final, acct);
314 }),
315
316 delete: Effect.fn(function* ({ output }) {
317 // Cloudflare-managed maps cannot (and must not) be deleted.
318 if (output.canDelete === false) return;
319 yield* addressing
320 .deleteAddressMap({
321 accountId: output.accountId,
322 addressMapId: output.addressMapId,
323 })
324 .pipe(Effect.catchTag("AddressMapNotFound", () => Effect.void));
325 }),
326 });
327
328 /**
329 * Read an Address Map by id, mapping "gone" (`AddressMapNotFound`,
330 * Cloudflare error code 1000 `not_found`) to `undefined`.
331 */
332 const getMap = (accountId: string, addressMapId: string) =>
333 addressing
334 .getAddressMap({ accountId, addressMapId })
335 .pipe(Effect.catchTag("AddressMapNotFound", () => Effect.undefined));
336
337 /** Desired IPs — inputs have been resolved to concrete strings by Plan. */
338 const desiredIps = (news: AddressMapProps): string[] => (news.ips ?? []).map((ip) => ip as string);
339
340 /** Desired memberships with inputs resolved to concrete strings. */
341 const desiredMemberships = (
342 news: AddressMapProps,
343 ): { identifier: string; kind: "zone" | "account" }[] =>
344 (news.memberships ?? []).map((m) => ({
345 identifier: m.identifier as string,
346 kind: m.kind,
347 }));
348
349 /**
350 * Narrow distilled memberships (whose `kind` is widened to an open string
351 * union) down to the closed `"zone" | "account"` literals, dropping any
352 * membership without an identifier or with an unknown kind.
353 */
354 const narrowMemberships = (
355 memberships:
356 | readonly {
357 identifier?: string | null;
358 kind?: string | null;
359 }[]
360 | null
361 | undefined,
362 ): { identifier: string; kind: "zone" | "account" }[] =>
363 (memberships ?? []).flatMap((m): { identifier: string; kind: "zone" | "account" }[] => {
364 if (!m.identifier) return [];
365 if (m.kind === "zone") {
366 return [{ identifier: m.identifier, kind: "zone" }];
367 }
368 if (m.kind === "account") {
369 return [{ identifier: m.identifier, kind: "account" }];
370 }
371 return [];
372 });
373
374 const toAttributes = (
375 map: addressing.GetAddressMapResponse,
376 accountId: string,
377 ): AddressMapAttributes => ({
378 addressMapId: map.id ?? "",
379 accountId,
380 canDelete: map.canDelete ?? true,
381 canModifyIps: map.canModifyIps ?? true,
382 description: map.description ?? undefined,
383 enabled: map.enabled ?? false,
384 defaultSni: map.defaultSni ?? undefined,
385 ips: (map.ips ?? []).flatMap((ip) => (ip.ip ? [ip.ip] : [])),
386 memberships: narrowMemberships(map.memberships),
387 createdAt: map.createdAt ?? undefined,
388 modifiedAt: map.modifiedAt ?? undefined,
389 });