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

main
ts 517 lines 19.4 KB
Raw
1 import * as ssl from "@distilled.cloud/cloudflare/ssl";
2 import * as workers from "@distilled.cloud/cloudflare/workers";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { listAllZones } from "../Zone/lookup.ts";
14
15 const TypeId = "Cloudflare.Ssl.CertificatePack" as const;
16 type TypeId = typeof TypeId;
17
18 /**
19 * Certificate Authorities available for Advanced Certificate Manager orders.
20 *
21 * - `google` — Google Trust Services
22 * - `lets_encrypt` — Let's Encrypt (no `cloudflareBranding`)
23 * - `ssl_com` — SSL.com (supports `email` validation)
24 */
25 export type CertificatePackCertificateAuthority = "google" | "lets_encrypt" | "ssl_com";
26
27 /**
28 * Domain Control Validation method used to prove ownership of the
29 * certificate's hostnames.
30 */
31 export type CertificatePackValidationMethod = "txt" | "http" | "email";
32
33 /**
34 * Number of days the issued certificates are valid for.
35 */
36 export type CertificatePackValidityDays = 14 | 30 | 90 | 365;
37
38 /**
39 * Status of a certificate pack as reported by Cloudflare.
40 */
41 export type CertificatePackStatus =
42 | "initializing"
43 | "pending_validation"
44 | "deleted"
45 | "pending_issuance"
46 | "pending_deployment"
47 | "pending_deletion"
48 | "pending_expiration"
49 | "expired"
50 | "active"
51 | "initializing_timed_out"
52 | "validation_timed_out"
53 | "issuance_timed_out"
54 | "deployment_timed_out"
55 | "deletion_timed_out"
56 | "pending_cleanup"
57 | "staging_deployment"
58 | "staging_active"
59 | "deactivating"
60 | "inactive"
61 | "backup_issued"
62 | "holding_deployment";
63
64 /**
65 * A Domain Control Validation record for a certificate pack — create the
66 * indicated TXT/CNAME record (or serve the HTTP token) to complete
67 * validation when the pack is `pending_validation`.
68 */
69 export interface CertificatePackValidationRecord {
70 /** Name of the TXT record to create (for `txt` validation). */
71 txtName?: string;
72 /** Value of the TXT record (for `txt` validation). */
73 txtValue?: string;
74 /** URL that must serve `httpBody` (for `http` validation). */
75 httpUrl?: string;
76 /** Body the `httpUrl` must respond with (for `http` validation). */
77 httpBody?: string;
78 /** Name of the CNAME record to create (for delegated DCV). */
79 cname?: string;
80 /** Target of the CNAME record (for delegated DCV). */
81 cnameTarget?: string;
82 /** Approver email addresses (for `email` validation). */
83 emails?: string[];
84 /** Validation status of this record. */
85 status?: string;
86 }
87
88 export interface CertificatePackProps {
89 /**
90 * Zone the certificate pack belongs to. Stable — moving a pack to a
91 * different zone triggers a replacement.
92 */
93 zoneId: string;
94 /**
95 * Certificate Authority to order the certificates from.
96 *
97 * Immutable — the Cloudflare API has no way to change the CA of an
98 * existing pack, so changing it triggers a replacement.
99 */
100 certificateAuthority: CertificatePackCertificateAuthority;
101 /**
102 * Hostnames the certificates cover. Must contain the zone apex, may
103 * contain wildcards, and may not exceed 50 hosts.
104 *
105 * Immutable — hosts cannot be added to or removed from an existing
106 * pack, so changing them (order-insensitively) triggers a replacement.
107 */
108 hosts: string[];
109 /**
110 * Domain Control Validation method for the order.
111 *
112 * Mutable — changed in place on the existing pack via the SSL
113 * verification API (`PATCH /ssl/verification/{certificatePackId}`).
114 */
115 validationMethod: CertificatePackValidationMethod;
116 /**
117 * Validity period of the issued certificates, in days.
118 *
119 * Immutable — changing it triggers a replacement (re-order).
120 */
121 validityDays: CertificatePackValidityDays;
122 /**
123 * Whether to add Cloudflare branding to the order: a subdomain of
124 * `sni.cloudflaressl.com` is used as the certificate's Common Name.
125 *
126 * Mutable — patched in place.
127 *
128 * @default false
129 */
130 cloudflareBranding?: boolean;
131 }
132
133 export interface CertificatePackAttributes {
134 /** Cloudflare-assigned identifier of the certificate pack. */
135 certificatePackId: string;
136 /** Zone the pack belongs to. */
137 zoneId: string;
138 /**
139 * Current status of the pack. Issuance is asynchronous — a freshly
140 * ordered pack starts in `initializing`/`pending_validation` and only
141 * reaches `active` once Domain Control Validation completes.
142 */
143 status: CertificatePackStatus;
144 /** Hostnames the certificates cover. */
145 hosts: string[];
146 /** Certificate Authority the pack was ordered from. */
147 certificateAuthority: string;
148 /** Domain Control Validation method currently configured. */
149 validationMethod: string | undefined;
150 /** Validity period of the issued certificates, in days. */
151 validityDays: number | undefined;
152 /** Identifier of the primary certificate in the pack, once issued. */
153 primaryCertificate: string | undefined;
154 /**
155 * Outstanding Domain Control Validation records — create these
156 * TXT/CNAME records (or serve the HTTP tokens) to complete validation.
157 */
158 validationRecords: CertificatePackValidationRecord[] | undefined;
159 /** DCV Delegation records for delegated domain validation. */
160 dcvDelegationRecords: CertificatePackValidationRecord[] | undefined;
161 }
162
163 export type CertificatePack = Resource<
164 TypeId,
165 CertificatePackProps,
166 CertificatePackAttributes,
167 never,
168 Providers
169 >;
170
171 /**
172 * An Advanced Certificate Manager (ACM) certificate pack — an order for
173 * edge certificates covering a custom set of hostnames in a zone, with a
174 * choice of Certificate Authority, validation method, and validity period.
175 *
176 * Requires the **Advanced Certificate Manager** subscription on the zone;
177 * ordering without it fails with the typed `AdvancedCertificateManagerRequired`
178 * error (Cloudflare code 1450).
179 *
180 * Issuance is asynchronous: the resource returns as soon as the order is
181 * placed (status `initializing`/`pending_validation`) and does not wait for
182 * `active`, because validation may require you to create DNS records first —
183 * the outstanding records are exported as `validationRecords`.
184 *
185 * The pack's `certificateAuthority`, `hosts`, and `validityDays` are
186 * immutable — changing any of them replaces the pack (a new order).
187 * `validationMethod` and `cloudflareBranding` are updated in place.
188 * ### Ordering a certificate pack
189 * **Example:** Order an advanced certificate for the apex and a wildcard
190 * ```typescript
191 * const pack = yield* Cloudflare.Ssl.CertificatePack("ApexCert", {
192 * zoneId: zone.zoneId,
193 * certificateAuthority: "google",
194 * hosts: ["example.com", "*.example.com"],
195 * validationMethod: "txt",
196 * validityDays: 90,
197 * });
198 * ```
199 *
200 * **Example:** Order from Let's Encrypt with a short validity
201 * ```typescript
202 * yield* Cloudflare.Ssl.CertificatePack("ShortLivedCert", {
203 * zoneId: zone.zoneId,
204 * certificateAuthority: "lets_encrypt",
205 * hosts: ["example.com", "api.example.com"],
206 * validationMethod: "http",
207 * validityDays: 30,
208 * });
209 * ```
210 *
211 * ### Completing validation
212 * **Example:** Create the DCV TXT records the order asks for
213 * ```typescript
214 * const pack = yield* Cloudflare.Ssl.CertificatePack("ApexCert", {
215 * zoneId: zone.zoneId,
216 * certificateAuthority: "google",
217 * hosts: ["example.com"],
218 * validationMethod: "txt",
219 * validityDays: 90,
220 * });
221 * // pack.validationRecords contains the txtName/txtValue pairs to create
222 * // as DNS records so the CA can validate domain control.
223 * ```
224 *
225 * @see https://developers.cloudflare.com/ssl/edge-certificates/advanced-certificate-manager/
226 *
227 * @resource
228 * @product SSL/TLS
229 * @category SSL/TLS & Certificates
230 */
231 export const CertificatePack = Resource<CertificatePack>(TypeId);
232
233 /**
234 * Returns true if the given value is a CertificatePack resource.
235 */
236 export const isCertificatePack = (value: unknown): value is CertificatePack =>
237 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
238
239 export const CertificatePackProvider = () =>
240 Provider.succeed(CertificatePack, {
241 stables: ["certificatePackId", "zoneId"],
242
243 diff: Effect.fn(function* ({ olds, news, output }) {
244 // news is Input<Props> during plan — only compare once resolved.
245 if (!isResolved(news)) return undefined;
246 // No prior props to compare against — let the engine decide.
247 if (olds?.hosts === undefined) return undefined;
248 // zoneId is the pack's scope; it is Input<string>, so compare only
249 // once both sides are concrete.
250 const oldZoneId =
251 output?.zoneId ?? (typeof olds.zoneId === "string" ? olds.zoneId : undefined);
252 if (oldZoneId !== undefined && typeof news.zoneId === "string" && oldZoneId !== news.zoneId) {
253 return { action: "replace" } as const;
254 }
255 // The order is immutable in CA, hosts, and validity — any change is
256 // a re-order (replacement). hosts compare order-insensitively.
257 if (
258 olds.certificateAuthority !== news.certificateAuthority ||
259 olds.validityDays !== news.validityDays ||
260 !sameHosts(olds.hosts, news.hosts)
261 ) {
262 return { action: "replace" } as const;
263 }
264 // validationMethod / cloudflareBranding are in-place updates.
265 return undefined;
266 }),
267
268 read: Effect.fn(function* ({ output, olds }) {
269 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
270 if (!zoneId) return undefined;
271
272 // Owned path: refresh by our persisted pack id.
273 if (output?.certificatePackId) {
274 const observed = yield* getPack(zoneId, output.certificatePackId);
275 if (observed) return toAttributes(zoneId, observed);
276 return undefined;
277 }
278
279 // Cold lookup (state persistence failed before we saved the id): an
280 // advanced pack with this exact host set may already exist. Packs
281 // carry no ownership markers, so report it as `Unowned` and let the
282 // engine gate takeover behind the adopt policy.
283 if (olds?.hosts) {
284 const observed = yield* findByHosts(zoneId, olds.hosts);
285 if (observed) return Unowned(toAttributes(zoneId, observed));
286 }
287 return undefined;
288 }),
289
290 reconcile: Effect.fn(function* ({ news, output }) {
291 // Inputs have been resolved to concrete strings by Plan.
292 const zoneId = news.zoneId as string;
293
294 // 1. Observe — the pack id cached on `output` is a hint, not a
295 // guarantee: a missing pack falls through to the host-set scan
296 // and then to a fresh order.
297 let observed = output?.certificatePackId
298 ? yield* getPack(zoneId, output.certificatePackId)
299 : undefined;
300
301 // 2. Fall back to scanning the zone for an advanced pack with the
302 // same host set (recovers from a crash after order-before-save).
303 if (!observed) {
304 observed = yield* findByHosts(zoneId, news.hosts);
305 }
306
307 // 3. Ensure — order the pack when missing. Ordering is gated on the
308 // Advanced Certificate Manager subscription; the typed
309 // `AdvancedCertificateManagerRequired` error propagates to the
310 // caller untouched.
311 if (!observed) {
312 observed = yield* ssl.createCertificatePack({
313 zoneId,
314 type: "advanced",
315 certificateAuthority: news.certificateAuthority,
316 hosts: news.hosts,
317 validationMethod: news.validationMethod,
318 validityDays: news.validityDays,
319 cloudflareBranding: news.cloudflareBranding,
320 });
321 }
322
323 // 4. Sync — diff each mutable aspect of the observed pack against
324 // the desired props; skip the API entirely on a no-op. A freshly
325 // ordered pack already matches, so both checks fall through.
326 if (
327 news.cloudflareBranding !== undefined &&
328 (observed.cloudflareBranding ?? false) !== news.cloudflareBranding
329 ) {
330 observed = yield* ssl.patchCertificatePack({
331 zoneId,
332 certificatePackId: observed.id,
333 cloudflareBranding: news.cloudflareBranding,
334 });
335 }
336
337 let validationMethod = observed.validationMethod ?? undefined;
338 if (validationMethod !== news.validationMethod) {
339 const verification = yield* ssl.patchVerification({
340 zoneId,
341 certificatePackId: observed.id,
342 validationMethod: news.validationMethod,
343 });
344 validationMethod = verification.validationMethod ?? validationMethod;
345 }
346
347 return toAttributes(zoneId, observed, validationMethod);
348 }),
349
350 list: Effect.fn(function* () {
351 const { accountId } = yield* yield* CloudflareEnvironment;
352 // Certificate packs are zone-scoped; there is no account-wide
353 // enumeration API. Fan out over every zone in the account and list
354 // its packs, restricting to `advanced` packs (the only kind this
355 // resource manages — universal/total_tls packs are not orderable).
356 const zones = yield* listAllZones(accountId);
357 // Cloudflare auto-orders an `advanced` pack for every Worker custom
358 // domain (hosts `[apex, host, *.host]`) and owns its lifecycle — the
359 // domain's `certId` is that pack's id. Those packs are not ours to
360 // enumerate (deleting one strips TLS from a live custom domain), so
361 // exclude them. Only zones that have candidate packs look up their
362 // custom domains, filtered to that zone.
363 const workerManagedIn = (zoneId: string) =>
364 workers.listDomains.items({ accountId, zoneId }).pipe(
365 Stream.runCollect,
366 Effect.map((domains) => new Set(Array.from(domains, (d) => d.certId))),
367 );
368 const rows = yield* Effect.forEach(
369 zones,
370 (zone) =>
371 ssl.listCertificatePacks.pages({ zoneId: zone.id, status: "all" }).pipe(
372 Stream.runCollect,
373 Effect.map((chunk) =>
374 Array.from(chunk).flatMap((page) =>
375 (page.result ?? []).filter(
376 (pack) => pack.type === "advanced" && !isTombstone(pack),
377 ),
378 ),
379 ),
380 Effect.flatMap((packs) =>
381 packs.length === 0
382 ? Effect.succeed([] as CertificatePackAttributes[])
383 : workerManagedIn(zone.id).pipe(
384 Effect.map((workerManaged) =>
385 packs
386 .filter((pack) => !workerManaged.has(pack.id))
387 .map((pack) => toAttributes(zone.id, pack)),
388 ),
389 ),
390 ),
391 // A plan-gated zone (no ACM) rejects the route, and a freshly
392 // minted token may briefly answer Forbidden — skip either.
393 Effect.catchTag(["InvalidRoute", "Forbidden"], () =>
394 Effect.succeed([] as CertificatePackAttributes[]),
395 ),
396 ),
397 { concurrency: 10 },
398 );
399 return rows.flat();
400 }),
401
402 delete: Effect.fn(function* ({ output }) {
403 const { zoneId, certificatePackId } = output;
404 yield* Effect.gen(function* () {
405 // Observe first — a missing pack (404, code 1408), a `deleted`
406 // tombstone, or a pack Cloudflare is already deleting are all done.
407 const observed = yield* getPack(zoneId, certificatePackId);
408 if (!observed || observed.status === "pending_deletion") return;
409 yield* ssl
410 .deleteCertificatePack({ zoneId, certificatePackId })
411 .pipe(Effect.catchTag("CertificatePackNotFound", () => Effect.void));
412 }).pipe(
413 // Cloudflare's certificate service answers a code-less 400 "Bad
414 // response certificate service" while it is mid-transition on the
415 // pack (observed on a just-deleted tombstone). Re-observe on a short
416 // bounded schedule — the next pass usually sees the tombstone and
417 // returns. If the pack is still live after ~50s, fail honestly
418 // rather than report a delete that did not happen.
419 Effect.retry({
420 while: (e) => e._tag === "CertificatePackNotDeletable",
421 schedule: Schedule.spaced("5 seconds"),
422 times: 10,
423 }),
424 );
425 }),
426 });
427
428 // ---------------------------------------------------------------------------
429 // API helpers
430 // ---------------------------------------------------------------------------
431
432 type ObservedPack =
433 | ssl.GetCertificatePackResponse
434 | ssl.CreateCertificatePackResponse
435 | ssl.PatchCertificatePackResponse
436 | ssl.ListCertificatePacksResponse["result"][number];
437
438 /**
439 * A deleted pack lingers for a minute or two as a `status: "deleted"`
440 * tombstone (still returned by get and by list with `status=all`). It is
441 * gone for every purpose: it cannot be patched, and deleting it again fails
442 * with `CertificatePackNotDeletable`.
443 */
444 const isTombstone = (pack: { status: string }) => pack.status === "deleted";
445
446 /**
447 * Read a pack by id, mapping "gone" (`CertificatePackNotFound`, Cloudflare
448 * error code 1408 / HTTP 404, or a `deleted` tombstone) and a deleted zone
449 * (`InvalidRoute`, code 7003) to `undefined`.
450 */
451 const getPack = (zoneId: string, certificatePackId: string) =>
452 ssl.getCertificatePack({ zoneId, certificatePackId }).pipe(
453 Effect.map((pack): ssl.GetCertificatePackResponse | undefined =>
454 isTombstone(pack) ? undefined : pack,
455 ),
456 Effect.catchTag(["CertificatePackNotFound", "InvalidRoute"], () => Effect.undefined),
457 );
458
459 /**
460 * Find an advanced pack by exact host set within the zone. Cloudflare
461 * rejects a second advanced order for an identical host set, so at most
462 * one pack can match. Includes non-active (pending) packs.
463 */
464 const findByHosts = (zoneId: string, hosts: string[]) =>
465 ssl.listCertificatePacks.items({ zoneId, status: "all" }).pipe(
466 Stream.runCollect,
467 Effect.map((chunk) =>
468 Array.from(chunk).find(
469 (pack) => pack.type === "advanced" && !isTombstone(pack) && sameHosts(pack.hosts, hosts),
470 ),
471 ),
472 Effect.catchTag("InvalidRoute", () => Effect.undefined),
473 );
474
475 /** Order-insensitive host set comparison. */
476 const sameHosts = (a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean => {
477 if (a.length !== b.length) return false;
478 const set = new Set(a);
479 return b.every((host) => set.has(host));
480 };
481
482 const toRecord = (record: {
483 cname?: string | null;
484 cnameTarget?: string | null;
485 emails?: string[] | null;
486 httpBody?: string | null;
487 httpUrl?: string | null;
488 status?: string | null;
489 txtName?: string | null;
490 txtValue?: string | null;
491 }): CertificatePackValidationRecord => ({
492 txtName: record.txtName ?? undefined,
493 txtValue: record.txtValue ?? undefined,
494 httpUrl: record.httpUrl ?? undefined,
495 httpBody: record.httpBody ?? undefined,
496 cname: record.cname ?? undefined,
497 cnameTarget: record.cnameTarget ?? undefined,
498 emails: record.emails ?? undefined,
499 status: record.status ?? undefined,
500 });
501
502 const toAttributes = (
503 zoneId: string,
504 pack: ObservedPack,
505 validationMethod?: string,
506 ): CertificatePackAttributes => ({
507 certificatePackId: pack.id,
508 zoneId,
509 status: pack.status as CertificatePackStatus,
510 hosts: [...pack.hosts],
511 certificateAuthority: pack.certificateAuthority ?? "",
512 validationMethod: validationMethod ?? pack.validationMethod ?? undefined,
513 validityDays: pack.validityDays ?? undefined,
514 primaryCertificate: pack.primaryCertificate ?? undefined,
515 validationRecords: pack.validationRecords?.map(toRecord) ?? undefined,
516 dcvDelegationRecords: pack.dcvDelegationRecords?.map(toRecord) ?? undefined,
517 });