The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as acm from "@distilled.cloud/cloudflare/acm"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 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 "../Zone/lookup.ts"; |
| 11 | |
| 12 | const TypeId = "Cloudflare.Acm.TotalTls" as const; |
| 13 | type TypeId = typeof TypeId; |
| 14 | |
| 15 | /** |
| 16 | * The Certificate Authority Total TLS certificates are issued through. |
| 17 | */ |
| 18 | export type TotalTlsCertificateAuthority = "google" | "lets_encrypt" | "ssl_com"; |
| 19 | |
| 20 | export interface TotalTlsProps { |
| 21 | /** |
| 22 | * Zone whose Total TLS setting is managed. Stable — changing the zone |
| 23 | * triggers a replacement (the old zone's setting is restored to the |
| 24 | * state it had before Alchemy managed it). |
| 25 | */ |
| 26 | zoneId: string; |
| 27 | /** |
| 28 | * Whether Total TLS is enabled. When enabled, Cloudflare orders a |
| 29 | * hostname-specific TLS certificate for every proxied A, AAAA, or CNAME |
| 30 | * record in the zone. Mutable — updated in place. |
| 31 | */ |
| 32 | enabled: boolean; |
| 33 | /** |
| 34 | * The Certificate Authority that Total TLS certificates will be issued |
| 35 | * through. When omitted, Cloudflare picks one. Mutable — updated in |
| 36 | * place. |
| 37 | */ |
| 38 | certificateAuthority?: TotalTlsCertificateAuthority; |
| 39 | } |
| 40 | |
| 41 | export interface TotalTlsAttributes { |
| 42 | /** Zone the setting belongs to — this is the singleton's identity. */ |
| 43 | zoneId: string; |
| 44 | /** Whether Total TLS is currently enabled on the zone. */ |
| 45 | enabled: boolean; |
| 46 | /** |
| 47 | * The Certificate Authority issuing Total TLS certificates, if |
| 48 | * Cloudflare reports one. |
| 49 | */ |
| 50 | certificateAuthority: string | undefined; |
| 51 | /** |
| 52 | * The validity period in days for certificates ordered via Total TLS |
| 53 | * (currently always 90), if Cloudflare reports it. |
| 54 | */ |
| 55 | validityPeriod: number | undefined; |
| 56 | /** |
| 57 | * Whether Total TLS was enabled before Alchemy first touched the zone. |
| 58 | * Restored on destroy, so deleting the resource puts the zone back the |
| 59 | * way it was found. |
| 60 | */ |
| 61 | initialEnabled: boolean; |
| 62 | /** |
| 63 | * The Certificate Authority configured before Alchemy first touched the |
| 64 | * zone, restored on destroy alongside `initialEnabled`. |
| 65 | */ |
| 66 | initialCertificateAuthority: string | undefined; |
| 67 | } |
| 68 | |
| 69 | export type TotalTls = Resource<TypeId, TotalTlsProps, TotalTlsAttributes, never, Providers>; |
| 70 | |
| 71 | /** |
| 72 | * The Total TLS setting of a Cloudflare zone |
| 73 | * (`/zones/{zone_id}/acm/total_tls`). |
| 74 | * |
| 75 | * Total TLS orders a hostname-specific TLS certificate for every proxied |
| 76 | * A, AAAA, or CNAME record in the zone, covering deep subdomains that the |
| 77 | * universal certificate's single-level wildcard cannot. The setting is a |
| 78 | * zone **singleton** — it always exists (default disabled), so this |
| 79 | * resource never creates or deletes anything physical. Reconcile posts the |
| 80 | * setting when the observed state differs from the desired one; destroy |
| 81 | * restores the state the zone had before Alchemy first managed it |
| 82 | * (captured as `initialEnabled` / `initialCertificateAuthority`). |
| 83 | * |
| 84 | * **Entitlement-gated**: configuring Total TLS requires the Advanced |
| 85 | * Certificate Manager add-on on the zone. Without it, every write fails |
| 86 | * with the typed `AdvancedCertificateManagerRequired` (code 1450) error |
| 87 | * (reads succeed and report `enabled: false`). |
| 88 | * |
| 89 | * Only one `TotalTls` resource per zone makes sense — two instances |
| 90 | * managing the same zone would fight over the singleton. |
| 91 | * ### Managing Total TLS |
| 92 | * **Example:** Enable Total TLS on a zone |
| 93 | * ```typescript |
| 94 | * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" }); |
| 95 | * |
| 96 | * yield* Cloudflare.Acm.TotalTls("TotalTls", { |
| 97 | * zoneId: zone.zoneId, |
| 98 | * enabled: true, |
| 99 | * }); |
| 100 | * ``` |
| 101 | * |
| 102 | * **Example:** Pin the issuing Certificate Authority |
| 103 | * ```typescript |
| 104 | * yield* Cloudflare.Acm.TotalTls("TotalTls", { |
| 105 | * zoneId: zone.zoneId, |
| 106 | * enabled: true, |
| 107 | * certificateAuthority: "lets_encrypt", |
| 108 | * }); |
| 109 | * ``` |
| 110 | * |
| 111 | * @see https://developers.cloudflare.com/ssl/edge-certificates/additional-options/total-tls/ |
| 112 | * |
| 113 | * @resource |
| 114 | * @product ACM |
| 115 | * @category SSL/TLS & Certificates |
| 116 | */ |
| 117 | export const TotalTls = Resource<TotalTls>(TypeId); |
| 118 | |
| 119 | /** |
| 120 | * Returns true if the given value is a TotalTls resource. |
| 121 | */ |
| 122 | export const isTotalTls = (value: unknown): value is TotalTls => |
| 123 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 124 | |
| 125 | export const TotalTlsProvider = () => |
| 126 | Provider.succeed(TotalTls, { |
| 127 | nuke: { singleton: true }, |
| 128 | stables: ["zoneId", "initialEnabled", "initialCertificateAuthority"], |
| 129 | |
| 130 | list: Effect.fn(function* () { |
| 131 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 132 | // No account-wide API for this zone singleton — enumerate every |
| 133 | // zone in the account and read its setting (every zone has one, |
| 134 | // defaulting to disabled; reads succeed even without the ACM |
| 135 | // entitlement). |
| 136 | const allZones = yield* listAllZones(accountId); |
| 137 | const rows = yield* Effect.forEach( |
| 138 | allZones.map((zone) => zone.id), |
| 139 | (zoneId) => |
| 140 | acm.getTotalTl({ zoneId }).pipe( |
| 141 | Effect.map((observed) => |
| 142 | toAttributes(zoneId, observed, initialStateOf(undefined, observed)), |
| 143 | ), |
| 144 | // Zone deleted out-of-band between enumeration and read. |
| 145 | Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined), |
| 146 | ), |
| 147 | { concurrency: 10 }, |
| 148 | ); |
| 149 | return rows.filter((row): row is TotalTlsAttributes => row !== undefined); |
| 150 | }), |
| 151 | |
| 152 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 153 | if (!isResolved(news)) return undefined; |
| 154 | // zoneId is Input<string>; compare only once both sides are concrete. |
| 155 | const oldZoneId = |
| 156 | output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined); |
| 157 | if (oldZoneId !== undefined && typeof news.zoneId === "string" && oldZoneId !== news.zoneId) { |
| 158 | return { action: "replace" } as const; |
| 159 | } |
| 160 | return undefined; |
| 161 | }), |
| 162 | |
| 163 | read: Effect.fn(function* ({ output, olds }) { |
| 164 | const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined); |
| 165 | if (!zoneId) return undefined; |
| 166 | const observed = yield* acm.getTotalTl({ zoneId }).pipe( |
| 167 | // Zone deleted out-of-band — the setting is gone with it. |
| 168 | Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined), |
| 169 | ); |
| 170 | if (observed === undefined) return undefined; |
| 171 | // The setting is a singleton that always exists with a Cloudflare |
| 172 | // default — there is nothing to "own", so a cold read adopts freely |
| 173 | // (never `Unowned`). The observed state at adoption time becomes the |
| 174 | // initial state restored on destroy. |
| 175 | return toAttributes(zoneId, observed, initialStateOf(output, observed)); |
| 176 | }), |
| 177 | |
| 178 | reconcile: Effect.fn(function* ({ news, output }) { |
| 179 | // Inputs have been resolved to concrete strings by Plan. |
| 180 | const zoneId = news.zoneId as string; |
| 181 | |
| 182 | // 1. Observe — the setting always exists; read its live state. |
| 183 | // (Reads succeed even on zones without the ACM entitlement.) |
| 184 | const observed = yield* acm.getTotalTl({ zoneId }); |
| 185 | |
| 186 | // 2. Capture — the pre-management state, restored on destroy. |
| 187 | // `output` (including an adoption read) already carries it; |
| 188 | // otherwise this is our first touch and the observed state is |
| 189 | // the zone's original. |
| 190 | const initial = initialStateOf(output, observed); |
| 191 | |
| 192 | // 3. Sync — post only when the observed state differs. Zones |
| 193 | // without the ACM entitlement fail here with the typed |
| 194 | // `AdvancedCertificateManagerRequired` error. |
| 195 | if (matchesDesired(observed, news)) { |
| 196 | return toAttributes(zoneId, observed, initial); |
| 197 | } |
| 198 | const updated = yield* acm |
| 199 | .updateTotalTl({ |
| 200 | zoneId, |
| 201 | enabled: news.enabled, |
| 202 | certificateAuthority: news.certificateAuthority, |
| 203 | }) |
| 204 | .pipe( |
| 205 | // A concurrent actor already applied the same state — converge |
| 206 | // by re-reading instead of failing. |
| 207 | Effect.catchTag("NoStateChange", () => acm.getTotalTl({ zoneId })), |
| 208 | // Cloudflare serializes Total TLS jobs per zone; ride out a |
| 209 | // previous job finishing (bounded). |
| 210 | Effect.retry({ |
| 211 | while: (e) => e._tag === "PreviousJobInProgress", |
| 212 | schedule: Schedule.spaced("3 seconds"), |
| 213 | times: 10, |
| 214 | }), |
| 215 | ); |
| 216 | return toAttributes(zoneId, updated, initial); |
| 217 | }), |
| 218 | |
| 219 | delete: Effect.fn(function* ({ output }) { |
| 220 | const { zoneId, initialEnabled, initialCertificateAuthority } = output; |
| 221 | // Observe — if the zone itself is gone, so is the setting. |
| 222 | const observed = yield* acm |
| 223 | .getTotalTl({ zoneId }) |
| 224 | .pipe(Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined)); |
| 225 | if (observed === undefined) return; |
| 226 | // Restore the pre-management state; skip the call when it already |
| 227 | // matches (idempotent re-delete after a crashed run). |
| 228 | if ( |
| 229 | (observed.enabled ?? false) === initialEnabled && |
| 230 | (initialCertificateAuthority === undefined || |
| 231 | (observed.certificateAuthority ?? undefined) === initialCertificateAuthority) |
| 232 | ) { |
| 233 | return; |
| 234 | } |
| 235 | yield* acm |
| 236 | .updateTotalTl({ |
| 237 | zoneId, |
| 238 | enabled: initialEnabled, |
| 239 | // The request type accepts any string (`(string & {})`), so the |
| 240 | // captured initial CA round-trips without a cast. |
| 241 | certificateAuthority: initialCertificateAuthority, |
| 242 | }) |
| 243 | .pipe( |
| 244 | Effect.catchTags({ |
| 245 | InvalidObjectIdentifier: () => Effect.void, |
| 246 | NoStateChange: () => Effect.void, |
| 247 | }), |
| 248 | // The zone lost its ACM entitlement since we configured it — |
| 249 | // Cloudflare already refuses Total TLS writes, so there is |
| 250 | // nothing left to restore. |
| 251 | Effect.catchTag("AdvancedCertificateManagerRequired", () => Effect.void), |
| 252 | Effect.retry({ |
| 253 | while: (e) => e._tag === "PreviousJobInProgress", |
| 254 | schedule: Schedule.spaced("3 seconds"), |
| 255 | times: 10, |
| 256 | }), |
| 257 | Effect.asVoid, |
| 258 | ); |
| 259 | }), |
| 260 | }); |
| 261 | |
| 262 | // --------------------------------------------------------------------------- |
| 263 | // Helpers |
| 264 | // --------------------------------------------------------------------------- |
| 265 | |
| 266 | type ObservedTotalTls = acm.GetTotalTlResponse | acm.UpdateTotalTlResponse; |
| 267 | |
| 268 | /** |
| 269 | * The pre-management state restored on destroy: carried forward on |
| 270 | * `output` once captured, otherwise derived from the first observation. |
| 271 | */ |
| 272 | const initialStateOf = ( |
| 273 | output: TotalTlsAttributes | undefined, |
| 274 | observed: ObservedTotalTls, |
| 275 | ): Pick<TotalTlsAttributes, "initialEnabled" | "initialCertificateAuthority"> => |
| 276 | output !== undefined |
| 277 | ? { |
| 278 | initialEnabled: output.initialEnabled, |
| 279 | initialCertificateAuthority: output.initialCertificateAuthority, |
| 280 | } |
| 281 | : { |
| 282 | initialEnabled: observed.enabled ?? false, |
| 283 | initialCertificateAuthority: observed.certificateAuthority ?? undefined, |
| 284 | }; |
| 285 | |
| 286 | /** |
| 287 | * Whether the observed setting already matches the desired props — the |
| 288 | * certificate authority only participates when explicitly requested |
| 289 | * (Cloudflare picks one otherwise). |
| 290 | */ |
| 291 | const matchesDesired = (observed: ObservedTotalTls, news: TotalTlsProps): boolean => |
| 292 | (observed.enabled ?? false) === news.enabled && |
| 293 | (news.certificateAuthority === undefined || |
| 294 | (observed.certificateAuthority ?? undefined) === news.certificateAuthority); |
| 295 | |
| 296 | const toAttributes = ( |
| 297 | zoneId: string, |
| 298 | setting: ObservedTotalTls, |
| 299 | initial: Pick<TotalTlsAttributes, "initialEnabled" | "initialCertificateAuthority">, |
| 300 | ): TotalTlsAttributes => ({ |
| 301 | zoneId, |
| 302 | enabled: setting.enabled ?? false, |
| 303 | certificateAuthority: setting.certificateAuthority ?? undefined, |
| 304 | validityPeriod: setting.validityPeriod ?? undefined, |
| 305 | ...initial, |
| 306 | }); |