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

main
ts 409 lines 16 KB
Raw
1 import * as clientCertificates from "@distilled.cloud/cloudflare/client-certificates";
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 Option from "effect/Option";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
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.ClientCertificate.ClientCertificate" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Lifecycle status of a client certificate. `pending_reactivation` and
18 * `pending_revocation` are in-progress asynchronous transitions.
19 */
20 export type Status =
21 | "active"
22 | "pending_reactivation"
23 | "pending_revocation"
24 | "revoked"
25 // Keep the union open so new Cloudflare statuses aren't blocked by stale
26 // types.
27 | (string & {});
28
29 export interface Props {
30 /**
31 * Zone the client certificate is issued under. Client certificates are a
32 * zone-level API Shield feature.
33 *
34 * Immutable — moving a certificate between zones triggers a replacement.
35 */
36 zoneId: string;
37 /**
38 * The Certificate Signing Request (CSR) in PEM format. Must be
39 * newline-encoded. Cloudflare's Managed CA signs this CSR and returns the
40 * client certificate.
41 *
42 * Immutable — the API has no way to re-sign a certificate, so changing the
43 * CSR triggers a replacement. Plain `string` (not `string`) so it is
44 * statically comparable inside `diff`.
45 */
46 csr: string;
47 /**
48 * The number of days the client certificate will be valid after the
49 * `issuedOn` date.
50 *
51 * Immutable — changing the validity triggers a replacement.
52 */
53 validityDays: number;
54 }
55
56 export interface Attributes {
57 /** Cloudflare-assigned identifier of the client certificate. */
58 clientCertificateId: string;
59 /** Zone the certificate was issued under. */
60 zoneId: string;
61 /** The signed client certificate in PEM format. */
62 certificate: string;
63 /** The CSR the certificate was issued from, as echoed by Cloudflare. */
64 csr: string;
65 /** Common Name parsed from the CSR. */
66 commonName: string | undefined;
67 /** Country parsed from the CSR. */
68 country: string | undefined;
69 /** State parsed from the CSR. */
70 state: string | undefined;
71 /** Location parsed from the CSR. */
72 location: string | undefined;
73 /** Organization parsed from the CSR. */
74 organization: string | undefined;
75 /** Organizational Unit parsed from the CSR. */
76 organizationalUnit: string | undefined;
77 /** ISO8601 date the certificate expires. */
78 expiresOn: string | undefined;
79 /** ISO8601 date the certificate was issued by the Managed CA. */
80 issuedOn: string | undefined;
81 /** SHA-256 fingerprint of the certificate. */
82 fingerprintSha256: string | undefined;
83 /** The serial number on the issued certificate. */
84 serialNumber: string | undefined;
85 /** The type of hash used for the certificate signature. */
86 signature: string | undefined;
87 /** Subject Key Identifier. */
88 ski: string | undefined;
89 /** Current lifecycle status of the certificate. */
90 status: Status;
91 /** The number of days the certificate is valid after `issuedOn`. */
92 validityDays: number;
93 /** Identifier of the Certificate Authority that issued the certificate. */
94 certificateAuthorityId: string | undefined;
95 /** Name of the Certificate Authority that issued the certificate. */
96 certificateAuthorityName: string | undefined;
97 }
98
99 export type ClientCertificate = Resource<TypeId, Props, Attributes, never, Providers>;
100
101 /**
102 * A zone-level API Shield mTLS client certificate signed by the Cloudflare
103 * Managed CA.
104 *
105 * You submit a Certificate Signing Request (CSR) plus a validity period;
106 * Cloudflare signs it and returns the client certificate PEM, which clients
107 * then present when connecting to API Shield mTLS-protected hostnames.
108 *
109 * Client certificates are immutable: there is no API to change the CSR or
110 * validity, so any prop change triggers a replacement. Deleting the resource
111 * revokes the certificate — revoked certificates remain listed on the zone in
112 * `revoked` status but are treated as deleted by this resource.
113 *
114 * Safety: client certificates carry no ownership markers. When there is no
115 * prior state, `read` scans the zone for a non-revoked certificate issued
116 * from the same CSR and reports it as `Unowned`, so the engine refuses to
117 * take it over unless `--adopt` (or `adopt(true)`) is set.
118 * ### Issuing a client certificate
119 * **Example:** Sign a CSR with the Cloudflare Managed CA
120 * ```typescript
121 * const cert = yield* Cloudflare.ClientCertificate.ClientCertificate("ApiClient", {
122 * zoneId: zone.zoneId,
123 * csr: clientCsrPem,
124 * validityDays: 365,
125 * });
126 * // cert.certificate is the signed client certificate PEM
127 * ```
128 *
129 * **Example:** Read the CSR from disk
130 * ```typescript
131 * const fs = yield* FileSystem.FileSystem;
132 * const csr = yield* fs.readFileString("certs/client.csr");
133 *
134 * const cert = yield* Cloudflare.ClientCertificate.ClientCertificate("ApiClient", {
135 * zoneId: zone.zoneId,
136 * csr,
137 * validityDays: 90,
138 * });
139 * ```
140 *
141 * ### Rotation
142 * **Example:** Rotate by changing the CSR
143 * ```typescript
144 * // csr and validityDays are immutable — changing either replaces the
145 * // certificate: a new one is signed and the old one is revoked.
146 * const cert = yield* Cloudflare.ClientCertificate.ClientCertificate("ApiClient", {
147 * zoneId: zone.zoneId,
148 * csr: rotatedCsrPem,
149 * validityDays: 365,
150 * });
151 * ```
152 *
153 * @see https://developers.cloudflare.com/ssl/client-certificates/
154 *
155 * @resource
156 * @product Client Certificates
157 * @category SSL/TLS & Certificates
158 */
159 export const ClientCertificate = Resource<ClientCertificate>(TypeId, {
160 aliases: ["Cloudflare.ClientCertificate"],
161 });
162
163 /**
164 * Returns true if the given value is a ClientCertificate resource.
165 */
166 export const isClientCertificate = (value: unknown): value is ClientCertificate =>
167 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
168
169 export const ClientCertificateProvider = () =>
170 Provider.succeed(ClientCertificate, {
171 // Everything Cloudflare returns at issuance is fixed for the lifetime of
172 // the certificate — only `status` changes (revocation/reactivation).
173 stables: [
174 "clientCertificateId",
175 "zoneId",
176 "certificate",
177 "csr",
178 "commonName",
179 "country",
180 "state",
181 "location",
182 "organization",
183 "organizationalUnit",
184 "expiresOn",
185 "issuedOn",
186 "fingerprintSha256",
187 "serialNumber",
188 "signature",
189 "ski",
190 "validityDays",
191 "certificateAuthorityId",
192 "certificateAuthorityName",
193 ],
194
195 // Client certificates are a zone-scoped API Shield feature. Fan out over
196 // every zone in the account, exhaustively paginate each zone's
197 // certificates, and hydrate each into the same Attributes shape `read`
198 // produces. Revoked certificates stay listed forever but revocation is the
199 // delete semantic, so they are filtered out. Zones where API Shield is not
200 // entitled reject with the typed `Forbidden` error — skip them.
201 list: Effect.fn(function* () {
202 const { accountId } = yield* yield* CloudflareEnvironment;
203 const zones = yield* listAllZones(accountId);
204 const rows = yield* Effect.forEach(
205 zones,
206 (zone) =>
207 clientCertificates.listClientCertificates.pages({ zoneId: zone.id, status: "all" }).pipe(
208 Stream.runCollect,
209 Effect.map((chunk) =>
210 Array.from(chunk).flatMap((page) =>
211 (page.result ?? [])
212 .filter((cert) => !isGone(cert.status))
213 .map((cert): Attributes => toAttributes(cert, zone.id)),
214 ),
215 ),
216 Effect.catchTag("Forbidden", () => Effect.succeed([])),
217 ),
218 { concurrency: 10 },
219 );
220 return rows.flat();
221 }),
222
223 diff: Effect.fn(function* ({ olds = {}, news }) {
224 const o = olds as Props;
225 const n = news as Props;
226 // No prior props to compare against — let the engine decide.
227 if (o.csr === undefined) return undefined;
228 // The API has no update for csr/validityDays — every change replaces.
229 if (normalizePem(o.csr) !== normalizePem(n.csr)) {
230 return { action: "replace" } as const;
231 }
232 if (o.validityDays !== n.validityDays) {
233 return { action: "replace" } as const;
234 }
235 // zoneId is Input<string>; compare only once both are concrete.
236 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
237 return { action: "replace" } as const;
238 }
239 return undefined;
240 }),
241
242 read: Effect.fn(function* ({ output, olds }) {
243 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
244 if (zoneId === undefined) return undefined;
245
246 // Owned path: refresh by our persisted certificate id. A revoked (or
247 // asynchronously revoking) certificate stays listed on the zone forever
248 // — revocation is the delete semantic, so report it as gone.
249 if (output?.clientCertificateId) {
250 const observed = yield* getCertificate(zoneId, output.clientCertificateId);
251 if (observed && !isGone(observed.status)) {
252 return toAttributes(observed, zoneId);
253 }
254 return undefined;
255 }
256
257 // Adoption path: a non-revoked certificate issued from the same CSR
258 // (with the same validity) may already exist on the zone. Client
259 // certificates carry no ownership markers, so we cannot prove we
260 // created it — brand it `Unowned` so the engine refuses takeover
261 // unless `adopt` is set.
262 if (olds?.csr !== undefined && olds.validityDays !== undefined) {
263 const observed = yield* findByCsr(zoneId, olds.csr, olds.validityDays);
264 if (observed) return Unowned(toAttributes(observed, zoneId));
265 }
266 return undefined;
267 }),
268
269 reconcile: Effect.fn(function* ({ news, output }) {
270 // Inputs have been resolved to concrete strings by Plan.
271 const zoneId = news.zoneId as string;
272
273 // 1. Observe — the certificate id cached on `output` is a hint, not a
274 // guarantee. A missing or revoked certificate (revocation is the
275 // delete semantic; the certificate cannot serve mTLS) falls
276 // through to the CSR scan and then to create.
277 let observed = output?.clientCertificateId
278 ? yield* getCertificate(zoneId, output.clientCertificateId)
279 : undefined;
280 if (observed && isGone(observed.status)) observed = undefined;
281
282 // 2. Fall back to scanning the zone for a non-revoked certificate
283 // issued from the same CSR with the same validity. Matching on
284 // BOTH props matters: a replacement keeps one of them while
285 // changing the other, so the old certificate never matches the new
286 // desired state and cannot be mistaken for it. Ownership has
287 // already been verified upstream — `read` reports existing
288 // certificates as `Unowned` and the engine gates takeover behind
289 // the adopt policy before reconcile ever runs.
290 if (!observed) {
291 observed = yield* findByCsr(zoneId, news.csr, news.validityDays);
292 }
293
294 // 3. Ensure — sign the CSR when missing. Cloudflare happily signs the
295 // same CSR multiple times (each issuance is a distinct
296 // certificate), so there is no AlreadyExists race to tolerate.
297 if (!observed) {
298 observed = yield* clientCertificates.createClientCertificate({
299 zoneId,
300 csr: news.csr,
301 validityDays: news.validityDays,
302 });
303 }
304
305 // 4. There is no sync step: csr/validityDays are immutable and every
306 // other attribute is derived at issuance.
307 return toAttributes(observed, zoneId);
308 }),
309
310 delete: Effect.fn(function* ({ output }) {
311 // DELETE revokes the certificate. Revoked certificates remain listed
312 // on the zone — observe first and treat already-revoked (or already
313 // revoking) as done so delete is idempotent.
314 const observed = yield* getCertificate(output.zoneId, output.clientCertificateId);
315 if (!observed || isGone(observed.status)) {
316 return;
317 }
318 yield* clientCertificates
319 .deleteClientCertificate({
320 zoneId: output.zoneId,
321 clientCertificateId: output.clientCertificateId,
322 })
323 .pipe(
324 // Races with an out-of-band revoke/delete are convergence, not
325 // failure.
326 Effect.catchTags({
327 ClientCertificateNotFound: () => Effect.void,
328 ClientCertificateAlreadyRevoked: () => Effect.void,
329 }),
330 );
331 }),
332 });
333
334 // ---------------------------------------------------------------------------
335 // API helpers
336 // ---------------------------------------------------------------------------
337
338 type ObservedCertificate = clientCertificates.GetClientCertificateResponse;
339
340 /**
341 * Read a certificate by id, mapping "gone" (`ClientCertificateNotFound`,
342 * Cloudflare error code 1415 `Invalid Certificate ID in request`) to
343 * `undefined`.
344 */
345 const getCertificate = (zoneId: string, clientCertificateId: string) =>
346 clientCertificates.getClientCertificate({ zoneId, clientCertificateId }).pipe(
347 Effect.map((cert): ObservedCertificate | undefined => cert),
348 Effect.catchTag("ClientCertificateNotFound", () => Effect.undefined),
349 );
350
351 /**
352 * Find a non-revoked certificate issued from the given CSR with the given
353 * validity. Cloudflare echoes the CSR back on every certificate, so an exact
354 * (whitespace-normalized) CSR + validity match is the only identity available
355 * for cold reads — certificates have no names or tags. Both props are matched
356 * so a replacement (which changes at least one of them) can never mistake the
357 * outgoing certificate for the desired one.
358 */
359 const findByCsr = (zoneId: string, csr: string, validityDays: number) =>
360 clientCertificates.listClientCertificates.items({ zoneId, status: "all" }).pipe(
361 Stream.filter(
362 (cert) =>
363 !isGone(cert.status) &&
364 cert.validityDays === validityDays &&
365 typeof cert.csr === "string" &&
366 normalizePem(cert.csr) === normalizePem(csr),
367 ),
368 Stream.runHead,
369 Effect.map(Option.getOrUndefined),
370 Effect.map((cert): ObservedCertificate | undefined => cert),
371 );
372
373 /**
374 * A certificate is "gone" once it is `revoked` or asynchronously transitioning
375 * to it (`pending_revocation`). Revocation is the delete semantic, and a
376 * revoking certificate can no longer serve mTLS — so it must never be adopted,
377 * reused, listed, or treated as live. Without this, a prior run's async revoke
378 * leaves a `pending_revocation` certificate that a fresh deploy would otherwise
379 * mistake for an existing live certificate matching the CSR.
380 */
381 const isGone = (status: string | null | undefined): boolean =>
382 status === "revoked" || status === "pending_revocation";
383
384 /** Normalize PEM content for comparison (CRLF + trailing-newline noise). */
385 const normalizePem = (pem: string | undefined): string | undefined =>
386 pem?.replace(/\r\n/g, "\n").trim();
387
388 const toAttributes = (cert: ObservedCertificate, zoneId: string): Attributes => ({
389 clientCertificateId: cert.id!,
390 zoneId,
391 certificate: cert.certificate ?? "",
392 csr: cert.csr ?? "",
393 commonName: cert.commonName ?? undefined,
394 country: cert.country ?? undefined,
395 state: cert.state ?? undefined,
396 location: cert.location ?? undefined,
397 organization: cert.organization ?? undefined,
398 organizationalUnit: cert.organizationalUnit ?? undefined,
399 expiresOn: cert.expiresOn ?? undefined,
400 issuedOn: cert.issuedOn ?? undefined,
401 fingerprintSha256: cert.fingerprintSha256 ?? undefined,
402 serialNumber: cert.serialNumber ?? undefined,
403 signature: cert.signature ?? undefined,
404 ski: cert.ski ?? undefined,
405 status: (cert.status ?? "active") as Status,
406 validityDays: cert.validityDays ?? 0,
407 certificateAuthorityId: cert.certificateAuthority?.id ?? undefined,
408 certificateAuthorityName: cert.certificateAuthority?.name ?? undefined,
409 });