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

main
ts 316 lines 12.7 KB
Raw
1 import * as certificateAuthorities from "@distilled.cloud/cloudflare/certificate-authorities";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Schedule from "effect/Schedule";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.CertificateAuthorities.HostnameAssociation" as const;
14 type TypeId = typeof TypeId;
15
16 export type HostnameAssociationProps = {
17 /**
18 * Zone whose hostnames should enforce mTLS. Stable — the zone is part of
19 * the association's identity, so changing it triggers a replacement (the
20 * old zone's association is cleared).
21 */
22 zoneId: string;
23 /**
24 * UUID of an uploaded CA certificate from the account-level mTLS
25 * Certificate Management store (`Cloudflare.MtlsCertificate.MtlsCertificate` with
26 * `ca: true`). When omitted, the hostnames are associated with the zone's
27 * active Cloudflare Managed CA instead.
28 *
29 * Stable — the certificate keys the association, so changing it triggers
30 * a replacement (the old certificate's hostname list is cleared).
31 *
32 * @default the active Cloudflare Managed CA
33 */
34 mtlsCertificateId?: string;
35 /**
36 * Fully-qualified hostnames in the zone that enforce mTLS for the keyed
37 * certificate authority. Mutable — the desired list replaces the current
38 * one in full on update.
39 */
40 hostnames: Array<string>;
41 };
42
43 export type HostnameAssociationAttributes = {
44 /** Zone the association belongs to. */
45 zoneId: string;
46 /**
47 * The mTLS CA certificate the hostnames are associated with, or
48 * `undefined` when they are associated with the Cloudflare Managed CA.
49 */
50 mtlsCertificateId: string | undefined;
51 /** Hostnames currently enforcing mTLS for the keyed CA. */
52 hostnames: Array<string>;
53 };
54
55 export type HostnameAssociation = Resource<
56 TypeId,
57 HostnameAssociationProps,
58 HostnameAssociationAttributes,
59 never,
60 Providers
61 >;
62
63 /**
64 * The set of hostnames in a Cloudflare zone that enforce mTLS, optionally
65 * keyed by an uploaded mTLS CA certificate.
66 *
67 * Cloudflare models this as a settings singleton per
68 * `(zone, mtls_certificate_id)` pair — a pure GET/PUT API over
69 * `/zones/{zone_id}/certificate_authorities/hostname_associations`. With no
70 * `mtlsCertificateId`, the hostnames are associated with the zone's active
71 * Cloudflare Managed CA; with one, they are associated with that uploaded CA
72 * certificate. Destroying the resource clears the association (PUT of an
73 * empty hostname list).
74 *
75 * Safety: when there is no prior state but the keyed association already has
76 * hostnames, `read` reports the existing list as `Unowned` — the engine
77 * refuses to take it over (and would otherwise clobber a hand-managed list)
78 * unless `--adopt` or `adopt(true)` is set.
79 *
80 * Note: an mTLS CA certificate cannot be deleted while hostname associations
81 * still reference it. Pass the certificate id through
82 * `cert.mtlsCertificateId` so the engine destroys the association before the
83 * certificate.
84 * ### Cloudflare Managed CA
85 * **Example:** Enforce mTLS on a hostname with the Managed CA
86 * ```typescript
87 * yield* Cloudflare.CertificateAuthorities.HostnameAssociation("MtlsHosts", {
88 * zoneId: zone.zoneId,
89 * hostnames: ["api.example.com"],
90 * });
91 * ```
92 *
93 * ### Uploaded CA certificate
94 * **Example:** Associate hostnames with an uploaded CA
95 * ```typescript
96 * const ca = yield* Cloudflare.MtlsCertificate.MtlsCertificate("ClientCa", {
97 * ca: true,
98 * certificates: caPem,
99 * });
100 *
101 * yield* Cloudflare.CertificateAuthorities.HostnameAssociation("ClientCaHosts", {
102 * zoneId: zone.zoneId,
103 * mtlsCertificateId: ca.mtlsCertificateId,
104 * hostnames: ["api.example.com", "admin.example.com"],
105 * });
106 * ```
107 *
108 * @see https://developers.cloudflare.com/api/resources/certificate_authorities/subresources/hostname_associations/
109 *
110 * @resource
111 * @product Certificate Authorities
112 * @category SSL/TLS & Certificates
113 */
114 export const HostnameAssociation = Resource<HostnameAssociation>(TypeId);
115
116 /**
117 * Returns true if the given value is a HostnameAssociation resource.
118 */
119 export const isHostnameAssociation = (value: unknown): value is HostnameAssociation =>
120 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
121
122 /** The hostname list still reads back non-empty after repeated clears. */
123 export class HostnameAssociationNotCleared extends Data.TaggedError(
124 "HostnameAssociationNotCleared",
125 )<{
126 zoneId: string;
127 mtlsCertificateId: string | undefined;
128 hostnames: string[];
129 }> {
130 override get message() {
131 return `The ${this.mtlsCertificateId ?? "Managed CA"} hostname association in zone ${this.zoneId} still lists ${this.hostnames.join(", ")} after repeated clears`;
132 }
133 }
134
135 export const HostnameAssociationProvider = () =>
136 Provider.succeed(HostnameAssociation, {
137 stables: ["zoneId", "mtlsCertificateId"],
138
139 list: Effect.fn(function* () {
140 const { accountId } = yield* yield* CloudflareEnvironment;
141 // The association is a per-zone settings singleton with no
142 // account-wide enumeration API. The only enumerable key is the
143 // zone's active Cloudflare Managed CA (no `mtlsCertificateId`):
144 // associations keyed by an uploaded CA can't be enumerated because
145 // there is no API to list the certificate ids in play. Fan out over
146 // every zone and read its Managed-CA association.
147 const zones = yield* listAllZones(accountId);
148 const rows = yield* Effect.forEach(
149 zones,
150 (zone) =>
151 certificateAuthorities.getHostnameAssociation({ zoneId: zone.id }).pipe(
152 Effect.map((observed): HostnameAssociationAttributes | undefined => {
153 const hostnames = [...(observed.hostnames ?? [])];
154 // An empty list is the singleton's "unconfigured"
155 // state — nothing exists to enumerate (matches `read`).
156 if (hostnames.length === 0) return undefined;
157 return {
158 zoneId: zone.id,
159 mtlsCertificateId: undefined,
160 hostnames,
161 };
162 }),
163 // Zones without the mTLS entitlement reject the route
164 // (Forbidden) or aren't routable (InvalidRoute); skip them.
165 Effect.catchTag(["Forbidden", "InvalidRoute"], () => Effect.undefined),
166 ),
167 { concurrency: 10 },
168 );
169 return rows.filter((row): row is HostnameAssociationAttributes => row !== undefined);
170 }),
171
172 diff: Effect.fn(function* ({ olds = {}, news, output }) {
173 const o = olds as HostnameAssociationProps;
174 const n = news as HostnameAssociationProps;
175 // zoneId is Input<string>; compare only once both sides are concrete.
176 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
177 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
178 return { action: "replace" } as const;
179 }
180 // mtlsCertificateId keys the association — `undefined` (Managed CA)
181 // is itself an identity value.
182 const oldCertId =
183 output !== undefined
184 ? output.mtlsCertificateId
185 : typeof o.mtlsCertificateId === "string"
186 ? o.mtlsCertificateId
187 : undefined;
188 // A presence flip (Managed CA <-> uploaded CA) is decidable even when
189 // the new side is an unresolved Input reference — the reference itself
190 // proves a certificate now keys (or no longer keys) the association.
191 if ((oldCertId === undefined) !== (n.mtlsCertificateId === undefined)) {
192 return { action: "replace" } as const;
193 }
194 // Both sides keyed by a certificate: compare only once the new side is
195 // a concrete string (an unresolved Input may still resolve to the same
196 // id, so we leave that case to the engine's default update).
197 if (typeof n.mtlsCertificateId === "string" && oldCertId !== n.mtlsCertificateId) {
198 return { action: "replace" } as const;
199 }
200 return undefined;
201 }),
202
203 read: Effect.fn(function* ({ output, olds }) {
204 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
205 if (!zoneId) return undefined;
206 // A CA id that hasn't resolved yet (a certificate created in the same
207 // deploy) names no association we can observe. Reading with
208 // `undefined` would read the zone's managed-CA association instead, a
209 // different singleton, and report it as an unowned conflict.
210 if (
211 output === undefined &&
212 olds?.mtlsCertificateId !== undefined &&
213 typeof olds.mtlsCertificateId !== "string"
214 ) {
215 return undefined;
216 }
217 const mtlsCertificateId =
218 output !== undefined
219 ? output.mtlsCertificateId
220 : typeof olds?.mtlsCertificateId === "string"
221 ? olds.mtlsCertificateId
222 : undefined;
223 const observed = yield* certificateAuthorities.getHostnameAssociation({
224 zoneId,
225 mtlsCertificateId,
226 });
227 const hostnames = [...(observed.hostnames ?? [])];
228 // An empty list is the singleton's "unconfigured" state — nothing
229 // exists to refresh or adopt.
230 if (hostnames.length === 0) return undefined;
231 const attrs: HostnameAssociationAttributes = {
232 zoneId,
233 mtlsCertificateId,
234 hostnames,
235 };
236 // Cold read with a non-empty pre-existing list: the association
237 // carries no ownership markers, so we cannot prove we created it —
238 // gate the takeover behind the adopt policy.
239 return output !== undefined ? attrs : Unowned(attrs);
240 }),
241
242 reconcile: Effect.fn(function* ({ news }) {
243 // Inputs have been resolved to concrete strings by Plan.
244 const zoneId = news.zoneId as string;
245 const mtlsCertificateId = news.mtlsCertificateId as string | undefined;
246 const desired = (news.hostnames ?? []) as Array<string>;
247
248 // 1. Observe — the association always "exists" (possibly empty);
249 // read the live hostname list.
250 const observed = yield* certificateAuthorities.getHostnameAssociation({
251 zoneId,
252 mtlsCertificateId,
253 });
254 const current = [...(observed.hostnames ?? [])];
255
256 // 2. Sync — full PUT of the desired list; skip when the observed
257 // set already matches (order is not significant).
258 if (hostnameSetEquals(current, desired)) {
259 return { zoneId, mtlsCertificateId, hostnames: current };
260 }
261 const updated = yield* certificateAuthorities.putHostnameAssociation({
262 zoneId,
263 mtlsCertificateId,
264 hostnames: desired,
265 });
266 return {
267 zoneId,
268 mtlsCertificateId,
269 hostnames: [...(updated.hostnames ?? desired)],
270 };
271 }),
272
273 delete: Effect.fn(function* ({ output }) {
274 // The association is a settings singleton — "delete" means clearing
275 // the hostname list with a PUT of an empty list, re-sent until the
276 // clear is visible: Cloudflare sometimes keeps the old list after the
277 // PUT. An association that outlives its CA survives the CA's delete,
278 // and a re-upload of the same certificate gets the same id, so the
279 // stale hostnames would come back attached to the new upload. Failing
280 // here keeps the CA (deleted after this) in place instead.
281 const clear = Effect.gen(function* () {
282 yield* certificateAuthorities.putHostnameAssociation({
283 zoneId: output.zoneId,
284 mtlsCertificateId: output.mtlsCertificateId,
285 hostnames: [],
286 });
287 const observed = yield* certificateAuthorities.getHostnameAssociation({
288 zoneId: output.zoneId,
289 mtlsCertificateId: output.mtlsCertificateId,
290 });
291 const hostnames = [...(observed.hostnames ?? [])];
292 if (hostnames.length > 0) {
293 return yield* new HostnameAssociationNotCleared({
294 zoneId: output.zoneId,
295 mtlsCertificateId: output.mtlsCertificateId,
296 hostnames,
297 });
298 }
299 });
300 yield* clear.pipe(
301 Effect.retry({
302 while: (error) => error._tag === "HostnameAssociationNotCleared",
303 schedule: Schedule.spaced("2 seconds"),
304 times: 10,
305 }),
306 );
307 }),
308 });
309
310 /** Order-insensitive equality of two hostname lists (exact duplicates kept). */
311 const hostnameSetEquals = (a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean => {
312 if (a.length !== b.length) return false;
313 const sortedA = [...a].sort();
314 const sortedB = [...b].sort();
315 return sortedA.every((v, i) => v === sortedB[i]);
316 };