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

main
ts 234 lines 8.79 KB
Raw
1 import * as zones from "@distilled.cloud/cloudflare/zones";
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 "./lookup.ts";
11
12 const TypeId = "Cloudflare.Zone.Hold" as const;
13 type TypeId = typeof TypeId;
14
15 export type HoldProps = {
16 /**
17 * Zone to place the hold on. Stable — changing the zone triggers a
18 * replacement (the hold is removed from the old zone and placed on the
19 * new one).
20 */
21 zoneId: string;
22 /**
23 * Extend the hold to block any subdomain of the zone, as well as
24 * SSL4SaaS Custom Hostnames. For example, a hold on `example.com` with
25 * `includeSubdomains: true` also blocks `staging.example.com` from
26 * being added to another account.
27 *
28 * Mutable — patched in place.
29 * @default false
30 */
31 includeSubdomains?: boolean;
32 };
33
34 export type HoldAttributes = {
35 /** Zone the hold is placed on. */
36 zoneId: string;
37 /** Whether the hold is currently active. */
38 hold: boolean;
39 /**
40 * If present and future-dated, the hold is temporarily disabled and
41 * will automatically re-enable at this RFC3339 timestamp.
42 */
43 holdAfter: string | undefined;
44 /** Whether the hold also blocks subdomains and SSL4SaaS Custom Hostnames. */
45 includeSubdomains: boolean;
46 };
47
48 export type Hold = Resource<TypeId, HoldProps, HoldAttributes, never, Providers>;
49
50 /**
51 * A Cloudflare zone hold (`/zones/{zone_id}/hold`) — prevents the zone's
52 * hostname (and optionally its subdomains) from being added to another
53 * Cloudflare account while the hold is active.
54 *
55 * Zone holds are only available on **Enterprise** zones. On other plans
56 * every create/patch fails with Cloudflare code 1005, surfaced as the typed
57 * `ZoneHoldsRequireEnterprise` error.
58 *
59 * Destroying the resource removes the hold. The delete is idempotent —
60 * removing a hold that is already gone (or whose zone was deleted
61 * out-of-band) succeeds.
62 * ### Holding a zone
63 * **Example:** Place a hold on a zone
64 * ```typescript
65 * const hold = yield* Cloudflare.Zone.Hold("MyHold", {
66 * zoneId: zone.zoneId,
67 * });
68 * ```
69 *
70 * **Example:** Hold the zone and all of its subdomains
71 * ```typescript
72 * yield* Cloudflare.Zone.Hold("MyHold", {
73 * zoneId: zone.zoneId,
74 * includeSubdomains: true,
75 * });
76 * ```
77 *
78 * ### Adopting an existing hold
79 * **Example:** Take over a hold that was placed outside Alchemy
80 * ```typescript
81 * import { adopt } from "alchemy/AdoptPolicy";
82 * // A hold carries no ownership markers, so the engine refuses to take
83 * // over a pre-existing hold unless you opt in with `adopt(true)`.
84 * const hold = yield* Cloudflare.Zone.Hold("MyHold", {
85 * zoneId: zone.zoneId,
86 * }).pipe(adopt(true));
87 * ```
88 *
89 * @see https://developers.cloudflare.com/fundamentals/account/account-security/zone-holds/
90 *
91 * @resource
92 * @product Zones
93 * @category Domains & DNS
94 */
95 export const Hold = Resource<Hold>(TypeId);
96
97 /**
98 * Returns true if the given value is a Hold resource.
99 */
100 export const isHold = (value: unknown): value is Hold =>
101 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
102
103 // Cloudflare can transiently fail to authenticate a valid token, surfacing as
104 // `Forbidden`. Retry with exponential backoff capped at 5s, bounded to ~8
105 // attempts so a persistently-unauthorized call still fails fast.
106 const forbiddenRetrySchedule = Schedule.max([
107 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("5 seconds")]),
108 Schedule.recurs(8),
109 ]);
110
111 export const HoldProvider = () =>
112 Provider.succeed(Hold, {
113 stables: ["zoneId"],
114
115 list: Effect.fn(function* () {
116 const { accountId } = yield* yield* CloudflareEnvironment;
117 // A hold is a per-zone singleton — `getHold` always returns a record
118 // for every zone (default `hold: false`), and there is no account-wide
119 // enumeration API. Enumerate every zone and read its hold state.
120 const allZones = yield* listAllZones(accountId);
121 const rows = yield* Effect.forEach(
122 allZones.map((zone) => zone.id),
123 (zoneId) =>
124 zones.getHold({ zoneId }).pipe(
125 // Cloudflare intermittently rejects a *valid* token with
126 // `Forbidden` (a transient edge auth failure). It is retryable —
127 // back off and try again rather than dropping the zone, so a
128 // genuinely accessible zone (e.g. the standing test zone) never
129 // silently falls out of the enumeration on a blip.
130 Effect.retry({
131 while: (e) => e._tag === "Forbidden",
132 schedule: forbiddenRetrySchedule,
133 }),
134 Effect.map((observed) => toAttributes(zoneId, observed)),
135 // Zone deleted out-of-band mid-enumeration — drop it.
136 Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined),
137 ),
138 { concurrency: 10 },
139 );
140 return rows.filter((row): row is HoldAttributes => row !== undefined);
141 }),
142
143 diff: Effect.fn(function* ({ olds = {}, news, output }) {
144 const o = olds as HoldProps;
145 const n = news as HoldProps;
146 // zoneId is the hold's identity (one hold per zone). It is
147 // Input<string>; compare only once both sides are concrete.
148 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
149 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
150 return { action: "replace" } as const;
151 }
152 return undefined;
153 }),
154
155 read: Effect.fn(function* ({ output, olds }) {
156 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
157 if (!zoneId) return undefined;
158 const observed = yield* zones.getHold({ zoneId }).pipe(
159 // Zone deleted out-of-band — the hold is gone with it.
160 Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined),
161 );
162 if (observed === undefined || observed.hold !== true) return undefined;
163 const attrs = toAttributes(zoneId, observed);
164 // Cold read: a hold exists but we have no state for it. Holds carry
165 // no ownership markers, so gate the takeover behind `--adopt`.
166 return output === undefined ? Unowned(attrs) : attrs;
167 }),
168
169 reconcile: Effect.fn(function* ({ news }) {
170 // Inputs have been resolved to concrete strings by Plan.
171 const zoneId = news.zoneId as string;
172 const desiredIncludeSubdomains = news.includeSubdomains ?? false;
173
174 // 1. Observe — is the zone currently held?
175 const observed = yield* zones.getHold({ zoneId });
176
177 // 2. Ensure — place the hold if the zone is not held.
178 if (observed.hold !== true) {
179 const created = yield* zones.createHold({
180 zoneId,
181 includeSubdomains: desiredIncludeSubdomains,
182 });
183 return toAttributes(zoneId, created);
184 }
185
186 // 3. Sync — patch includeSubdomains when the observed value differs.
187 if (normalizeIncludeSubdomains(observed.includeSubdomains) !== desiredIncludeSubdomains) {
188 const patched = yield* zones
189 .patchHold({
190 zoneId,
191 includeSubdomains: desiredIncludeSubdomains,
192 })
193 .pipe(
194 // The hold vanished between observe and patch (out-of-band
195 // removal race) — place it fresh with the desired settings.
196 Effect.catchTag("ZoneHoldNotFound", () =>
197 zones.createHold({
198 zoneId,
199 includeSubdomains: desiredIncludeSubdomains,
200 }),
201 ),
202 );
203 return toAttributes(zoneId, patched);
204 }
205
206 return toAttributes(zoneId, observed);
207 }),
208
209 delete: Effect.fn(function* ({ output }) {
210 // Removing a hold is naturally idempotent — Cloudflare returns the
211 // (un-held) hold state even when no hold exists. Tolerate the zone
212 // itself having been deleted out-of-band.
213 yield* zones
214 .deleteHold({ zoneId: output.zoneId })
215 .pipe(Effect.catchTag("InvalidZoneIdentifier", () => Effect.void));
216 }),
217 });
218
219 /**
220 * Normalize Cloudflare's `include_subdomains` response value. The live API
221 * returns a boolean, while Cloudflare's published schema declares a string
222 * (`"true"`/`"false"`) — accept both.
223 */
224 const normalizeIncludeSubdomains = (value: unknown): boolean => value === true || value === "true";
225
226 const toAttributes = (
227 zoneId: string,
228 hold: zones.GetHoldResponse | zones.CreateHoldResponse | zones.PatchHoldResponse,
229 ): HoldAttributes => ({
230 zoneId,
231 hold: hold.hold === true,
232 holdAfter: hold.holdAfter ?? undefined,
233 includeSubdomains: normalizeIncludeSubdomains(hold.includeSubdomains),
234 });