@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 333 lines 12.9 KB
Raw
1 import * as originTls from "@distilled.cloud/cloudflare/origin-tls-client-auth";
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 Redacted from "effect/Redacted";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { listAllZones } from "../Zone/lookup.ts";
13
14 const TypeId = "Cloudflare.OriginTlsClientAuth.HostnameCertificate" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * Deployment status of the certificate. Deploying and deleting are
19 * asynchronous (`pending_deployment` → `active`, `pending_deletion` →
20 * `deleted`), typically settling within minutes.
21 */
22 export type HostnameCertificateStatus =
23 | "initializing"
24 | "pending_deployment"
25 | "pending_deletion"
26 | "active"
27 | "deleted"
28 | "deployment_timed_out"
29 | "deletion_timed_out"
30 // Keep the union open so new Cloudflare statuses aren't blocked by stale types.
31 | (string & {});
32
33 export type HostnameCertificateProps = {
34 /**
35 * Zone the certificate is uploaded to. Cannot be changed after upload —
36 * updating this property triggers a replacement.
37 */
38 zoneId: string;
39 /**
40 * The per-hostname client certificate in PEM format, presented by
41 * Cloudflare to your origin for hostnames associated with it via
42 * {@link HostnameAssociation}. Cannot be changed after
43 * upload — updating this property triggers a replacement.
44 */
45 certificate: string;
46 /**
47 * The certificate's private key in PEM format. Cannot be changed after
48 * upload — updating this property triggers a replacement.
49 */
50 privateKey: Redacted.Redacted<string>;
51 };
52
53 export type HostnameCertificateAttributes = {
54 /** Unique identifier of the uploaded certificate. */
55 certificateId: string;
56 /** Zone the certificate is uploaded to. */
57 zoneId: string;
58 /** Deployment status of the certificate. */
59 status: HostnameCertificateStatus | undefined;
60 /** When the certificate expires. */
61 expiresOn: string | undefined;
62 /** The certificate authority that issued the certificate. */
63 issuer: string | undefined;
64 /** The serial number on the uploaded certificate. */
65 serialNumber: string | undefined;
66 /** The type of hash used for the certificate signature. */
67 signature: string | undefined;
68 /** When the certificate was uploaded to Cloudflare. */
69 uploadedOn: string | undefined;
70 };
71
72 export type HostnameCertificate = Resource<
73 TypeId,
74 HostnameCertificateProps,
75 HostnameCertificateAttributes,
76 never,
77 Providers
78 >;
79
80 /**
81 * A per-hostname Authenticated Origin Pulls (AOP) client certificate
82 * (`/zones/{zone_id}/origin_tls_client_auth/hostnames/certificates`).
83 *
84 * Uploads a client certificate that Cloudflare presents to your origin for
85 * specific hostnames. Hostnames opt in by referencing the certificate from an
86 * {@link HostnameAssociation}, which pins the certificate
87 * and enables hostname-level AOP.
88 *
89 * Certificates are immutable: there is no update API, so changing any
90 * property triggers a replacement. Deployment is asynchronous — the
91 * certificate starts in `pending_deployment` and becomes `active` within a
92 * few minutes; deletion likewise passes through `pending_deletion`.
93 * ### Uploading a hostname certificate
94 * **Example:** Hostname client certificate
95 * ```typescript
96 * const cert = yield* Cloudflare.OriginTlsClientAuth.HostnameCertificate("AopHostCert", {
97 * zoneId: zone.zoneId,
98 * certificate: clientCertPem,
99 * privateKey: yield* Config.Redacted("AOP_CLIENT_KEY"),
100 * });
101 * ```
102 *
103 * ### Enabling AOP for a hostname
104 * **Example:** Upload the certificate and associate a hostname
105 * ```typescript
106 * const cert = yield* Cloudflare.OriginTlsClientAuth.HostnameCertificate("AopHostCert", {
107 * zoneId: zone.zoneId,
108 * certificate: clientCertPem,
109 * privateKey: yield* Config.Redacted("AOP_CLIENT_KEY"),
110 * });
111 *
112 * yield* Cloudflare.OriginTlsClientAuth.HostnameAssociation("AopHost", {
113 * zoneId: zone.zoneId,
114 * hostname: "api.example.com",
115 * certId: cert.certificateId,
116 * enabled: true,
117 * });
118 * ```
119 *
120 * @see https://developers.cloudflare.com/ssl/origin-configuration/authenticated-origin-pull/set-up/per-hostname/
121 *
122 * @resource
123 * @product Origin TLS Client Auth
124 * @category SSL/TLS & Certificates
125 */
126 export const HostnameCertificate = Resource<HostnameCertificate>(TypeId);
127
128 /**
129 * Returns true if the given value is an HostnameCertificate
130 * resource.
131 */
132 export const isHostnameCertificate = (value: unknown): value is HostnameCertificate =>
133 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
134
135 export const HostnameCertificateProvider = () =>
136 Provider.succeed(HostnameCertificate, {
137 stables: ["certificateId", "zoneId"],
138
139 list: Effect.fn(function* () {
140 const { accountId } = yield* yield* CloudflareEnvironment;
141 // Per-hostname client certificates live inside a zone and are only
142 // enumerable per-zone — fan out over every zone in the account.
143 const zones = yield* listAllZones(accountId);
144 const rows = yield* Effect.forEach(
145 zones,
146 (zone) =>
147 originTls.listHostnameCertificates.pages({ zoneId: zone.id }).pipe(
148 Stream.runCollect,
149 Effect.map((chunk) =>
150 Array.from(chunk).flatMap((page) =>
151 (page.result ?? [])
152 // Match `read`: tombstoned (deleted / pending_deletion)
153 // certificates no longer satisfy the desired state.
154 .filter((c) => isLive(c.status))
155 .map((c) => toAttributes(c, zone.id)),
156 ),
157 ),
158 // Plan-gated / partial zones reject the route; skip them.
159 Effect.catchTag("Forbidden", () => Effect.succeed([])),
160 ),
161 { concurrency: 10 },
162 );
163 return rows.flat();
164 }),
165
166 diff: Effect.fn(function* ({ olds, news }) {
167 if (!isResolved(news)) return undefined;
168 // zoneId is Input<string>; compare only once both sides are concrete.
169 if (
170 typeof olds.zoneId === "string" &&
171 typeof news.zoneId === "string" &&
172 olds.zoneId !== news.zoneId
173 ) {
174 return { action: "replace" } as const;
175 }
176 // Compare the certificate only when the old value is known — an
177 // Output-valued `certificate` doesn't survive a `creating`-state
178 // round-trip (it deserializes as `undefined`).
179 if (
180 (olds.certificate !== undefined &&
181 normalizePem(olds.certificate) !== normalizePem(news.certificate)) ||
182 unwrap(olds.privateKey) !== unwrap(news.privateKey)
183 ) {
184 // There is no update API for hostname client certificates — every
185 // change is a replacement.
186 return { action: "replace" } as const;
187 }
188 return undefined;
189 }),
190
191 read: Effect.fn(function* ({ output, olds }) {
192 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
193 if (!zoneId) return undefined;
194 if (output?.certificateId) {
195 const observed = yield* observeById(zoneId, output.certificateId);
196 if (observed) return toAttributes(observed, zoneId);
197 }
198 // Cold read — recover by listing and matching on the certificate PEM
199 // content (the only identity available; hostname client certificates
200 // have no name or tags). A content match IS the desired state, so
201 // adoption is safe without an `Unowned` gate.
202 if (typeof olds?.certificate === "string") {
203 const match = yield* findByContent(zoneId, olds.certificate);
204 if (match) return toAttributes(match, zoneId);
205 }
206 return undefined;
207 }),
208
209 reconcile: Effect.fn(function* ({ news, output }) {
210 // Inputs have been resolved to concrete strings by Plan.
211 const zoneId = news.zoneId as string;
212
213 // 1. Observe — the certificate id is the stable identifier; fall
214 // through a HostnameCertificateNotFound (or a pending/completed
215 // deletion) to the list+content match so we recover from
216 // out-of-band deletes and partial state persistence.
217 let observed = output?.certificateId
218 ? yield* observeById(zoneId, output.certificateId)
219 : yield* findByContent(zoneId, news.certificate);
220
221 // 2. Ensure — upload if missing. Cloudflare rejects uploading a PEM
222 // identical to an existing certificate (code 1406); tolerate the
223 // race (or an orphaned prior upload) by re-listing and adopting the
224 // certificate with identical PEM content. A destroy→deploy cycle
225 // also hits 1406 while the old certificate's tombstone is still
226 // `pending_deletion` (observed live: it settles to `deleted` within
227 // ~10 seconds, after which re-uploading the PEM resurrects it under
228 // the same id) — ride that window out with a bounded retry of the
229 // whole create-or-adopt step.
230 if (!observed) {
231 observed = yield* originTls
232 .createHostnameCertificate({
233 zoneId,
234 certificate: news.certificate,
235 privateKey: unwrap(news.privateKey),
236 })
237 .pipe(
238 Effect.catchTag("CertificateAlreadyExists", (originalError) =>
239 Effect.gen(function* () {
240 const match = yield* findByContent(zoneId, news.certificate);
241 if (!match) return yield* originalError;
242 return match;
243 }),
244 ),
245 Effect.retry({
246 while: (e) => e._tag === "CertificateAlreadyExists",
247 schedule: Schedule.spaced("5 seconds"),
248 times: 10,
249 }),
250 );
251 }
252
253 // 3. Return — deployment is asynchronous (`pending_deployment` →
254 // `active`); we do not block on activation.
255 return toAttributes(observed, zoneId);
256 }),
257
258 delete: Effect.fn(function* ({ output }) {
259 yield* originTls
260 .deleteHostnameCertificate({
261 zoneId: output.zoneId,
262 certificateId: output.certificateId,
263 })
264 .pipe(
265 // The certificate cannot be deleted while a hostname association
266 // still references it (code 1433) or while its initial deployment
267 // is still propagating (code 1434). Both clear within seconds once
268 // the association is voided / the deployment lands — ride them out
269 // with a bounded retry.
270 Effect.retry({
271 while: (e) =>
272 e._tag === "HostnameCertificateInUse" || e._tag === "CertificatePendingDeployment",
273 schedule: Schedule.spaced("5 seconds"),
274 times: 10,
275 }),
276 // Already gone (404 / code 1551) or already on its way out
277 // (code 1414 pending deletion) — delete is idempotent.
278 Effect.catchTag(
279 ["HostnameCertificateNotFound", "CertificatePendingDeletion"],
280 () => Effect.void,
281 ),
282 );
283 }),
284 });
285
286 /** A certificate that is being or has been deleted no longer satisfies the desired state. */
287 const isLive = (status: string | null | undefined): boolean =>
288 status !== "deleted" && status !== "pending_deletion";
289
290 // Observe a certificate by id, treating "not found" and "deleted /
291 // pending_deletion" (Cloudflare keeps tombstones readable by id) as missing.
292 const observeById = (zoneId: string, certificateId: string) =>
293 originTls.getHostnameCertificate({ zoneId, certificateId }).pipe(
294 Effect.map((cert) => (isLive(cert.status) ? cert : undefined)),
295 Effect.catchTag("HostnameCertificateNotFound", () => Effect.undefined),
296 );
297
298 // Locate a live certificate by exact PEM content. Tombstoned certificates
299 // are excluded so a destroy→deploy cycle re-creates (resurrects) instead of
300 // adopting a certificate that is on its way out.
301 const findByContent = (zoneId: string, certificate: string) =>
302 Effect.gen(function* () {
303 const list = yield* originTls.listHostnameCertificates({ zoneId });
304 return list.result.find(
305 (c) => isLive(c.status) && normalizePem(c.certificate ?? "") === normalizePem(certificate),
306 );
307 });
308
309 const normalizePem = (pem: string): string => pem.trim();
310
311 const unwrap = (value: Redacted.Redacted<string> | string): string =>
312 Redacted.isRedacted(value) ? Redacted.value(value) : value;
313
314 type CertificateShape = {
315 id?: string | null;
316 status?: string | null;
317 expiresOn?: string | null;
318 issuer?: string | null;
319 serialNumber?: string | null;
320 signature?: string | null;
321 uploadedOn?: string | null;
322 };
323
324 const toAttributes = (cert: CertificateShape, zoneId: string): HostnameCertificateAttributes => ({
325 certificateId: cert.id!,
326 zoneId,
327 status: cert.status ?? undefined,
328 expiresOn: cert.expiresOn ?? undefined,
329 issuer: cert.issuer ?? undefined,
330 serialNumber: cert.serialNumber ?? undefined,
331 signature: cert.signature ?? undefined,
332 uploadedOn: cert.uploadedOn ?? undefined,
333 });