@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, 04:45 UTC

main
ts 340 lines 13.5 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.Certificate" 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 CertificateStatus =
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 CertificateProps = {
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 zone's leaf client certificate in PEM format, presented by
41 * Cloudflare to your origin when Authenticated Origin Pulls is enabled.
42 * Cannot be changed after upload — updating this property triggers a
43 * 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 CertificateAttributes = {
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: CertificateStatus | undefined;
60 /** When the certificate expires. */
61 expiresOn: string | undefined;
62 /** The certificate authority that issued the certificate. */
63 issuer: string | undefined;
64 /** The type of hash used for the certificate signature. */
65 signature: string | undefined;
66 /** When the certificate was uploaded to Cloudflare. */
67 uploadedOn: string | undefined;
68 };
69
70 export type Certificate = Resource<
71 TypeId,
72 CertificateProps,
73 CertificateAttributes,
74 never,
75 Providers
76 >;
77
78 /**
79 * A zone-level Authenticated Origin Pulls (AOP) client certificate
80 * (`/zones/{zone_id}/origin_tls_client_auth`).
81 *
82 * Uploads the client certificate Cloudflare presents to your origin when
83 * zone-level Authenticated Origin Pulls is enabled
84 * ({@link Setting}), letting the origin verify that
85 * requests really come from Cloudflare via mTLS.
86 *
87 * Certificates are immutable: there is no update API, so changing any
88 * property triggers a replacement. Deployment is asynchronous — the
89 * certificate starts in `pending_deployment` and becomes `active` within a
90 * few minutes; deletion likewise passes through `pending_deletion`.
91 * ### Uploading a certificate
92 * **Example:** Zone client certificate
93 * ```typescript
94 * const cert = yield* Cloudflare.OriginTlsClientAuth.Certificate("AopCert", {
95 * zoneId: zone.zoneId,
96 * certificate: clientCertPem,
97 * privateKey: yield* Config.Redacted("AOP_CLIENT_KEY"),
98 * });
99 * ```
100 *
101 * ### Enabling Authenticated Origin Pulls
102 * **Example:** Upload the certificate and turn AOP on
103 * ```typescript
104 * const cert = yield* Cloudflare.OriginTlsClientAuth.Certificate("AopCert", {
105 * zoneId: zone.zoneId,
106 * certificate: clientCertPem,
107 * privateKey: yield* Config.Redacted("AOP_CLIENT_KEY"),
108 * });
109 *
110 * yield* Cloudflare.OriginTlsClientAuth.Setting("Aop", {
111 * zoneId: zone.zoneId,
112 * enabled: true,
113 * });
114 * ```
115 *
116 * @see https://developers.cloudflare.com/ssl/origin-configuration/authenticated-origin-pull/
117 *
118 * @resource
119 * @product Origin TLS Client Auth
120 * @category SSL/TLS & Certificates
121 */
122 export const Certificate = Resource<Certificate>(TypeId);
123
124 /**
125 * Returns true if the given value is an Certificate
126 * resource.
127 */
128 export const isCertificate = (value: unknown): value is Certificate =>
129 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
130
131 export const CertificateProvider = () =>
132 Provider.succeed(Certificate, {
133 stables: ["certificateId", "zoneId"],
134
135 diff: Effect.fn(function* ({ olds = {}, news }) {
136 if (!isResolved(news)) return undefined;
137 const o = olds as CertificateProps;
138 const n = news as CertificateProps;
139 // zoneId is Input<string>; compare only once both sides are concrete.
140 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
141 return { action: "replace" } as const;
142 }
143 if (
144 (o.certificate !== undefined &&
145 normalizePem(o.certificate) !== normalizePem(n.certificate)) ||
146 (o.privateKey !== undefined && unwrap(o.privateKey) !== unwrap(n.privateKey))
147 ) {
148 // There is no update API for zone client certificates — every change
149 // is a replacement.
150 return { action: "replace" } as const;
151 }
152 return undefined;
153 }),
154
155 read: Effect.fn(function* ({ output, olds }) {
156 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
157 if (!zoneId) return undefined;
158 if (output?.certificateId) {
159 const observed = yield* observeById(zoneId, output.certificateId);
160 if (observed) return toAttributes(observed, zoneId);
161 }
162 // Cold read — recover by listing and matching on the certificate PEM
163 // content (the only identity available; zone client certificates have
164 // no name or tags). A content match IS the desired state, so adoption
165 // is safe without an `Unowned` gate.
166 if (typeof olds?.certificate === "string") {
167 const match = yield* findByContent(zoneId, olds.certificate);
168 if (match) return toAttributes(match, zoneId);
169 }
170 return undefined;
171 }),
172
173 reconcile: Effect.fn(function* ({ news, output }) {
174 // Inputs have been resolved to concrete strings by Plan.
175 const zoneId = news.zoneId as string;
176
177 // 1. Observe — the certificate id is the stable identifier; fall
178 // through a CertificateNotFound (or a pending/completed deletion)
179 // to the list+content match so we recover from out-of-band deletes
180 // and partial state persistence.
181 let observed = output?.certificateId
182 ? yield* observeById(zoneId, output.certificateId)
183 : yield* findByContent(zoneId, news.certificate);
184
185 // 2. Ensure — upload if missing. Cloudflare rejects uploading a PEM
186 // identical to a live certificate (code 1406); tolerate the race
187 // (or an orphaned prior upload) by re-listing and adopting the
188 // certificate with identical PEM content. Re-uploading the PEM of
189 // a certificate in `pending_deletion` resurrects it under the same
190 // id, so a destroy→deploy cycle converges naturally.
191 if (!observed) {
192 observed = yield* originTls
193 .createOriginTlsClientAuth({
194 zoneId,
195 certificate: news.certificate,
196 privateKey: unwrap(news.privateKey),
197 })
198 .pipe(
199 Effect.catchTag("CertificateAlreadyExists", (originalError) =>
200 Effect.gen(function* () {
201 const match = yield* findByContent(zoneId, news.certificate);
202 if (!match) return yield* originalError;
203 return match;
204 }),
205 ),
206 // A destroy→deploy cycle re-uploading the same PEM hits 1406 while
207 // the prior certificate's tombstone is still `pending_deletion`
208 // (it settles to `deleted` within ~10s, after which the same PEM
209 // either resurrects under its old id or uploads fresh). Ride that
210 // window out with a bounded retry of the whole create-or-adopt
211 // step.
212 //
213 // Cloudflare serializes zone client-cert mutations per zone; when a
214 // sibling upload/delete on the SAME zone is in flight, a concurrent
215 // upload is rejected with HTTP 409 (`ZoneClientCertConflict`).
216 // Retry it on the same bounded (~50s) schedule so concurrent
217 // per-zone mutations serialize gracefully instead of failing the
218 // deploy.
219 Effect.retry({
220 while: (e) =>
221 e._tag === "CertificateAlreadyExists" || e._tag === "ZoneClientCertConflict",
222 schedule: Schedule.spaced("5 seconds"),
223 times: 10,
224 }),
225 );
226 }
227
228 // 3. Return — deployment is asynchronous (`pending_deployment` →
229 // `active`); we do not block on activation.
230 return toAttributes(observed, zoneId);
231 }),
232
233 list: Effect.fn(function* () {
234 const { accountId } = yield* yield* CloudflareEnvironment;
235 const zones = yield* listAllZones(accountId);
236 const rows = yield* Effect.forEach(
237 zones,
238 (zone) =>
239 originTls.listOriginTlsClientAuths.pages({ zoneId: zone.id }).pipe(
240 Stream.runCollect,
241 Effect.map((chunk) =>
242 Array.from(chunk).flatMap((page) =>
243 (page.result ?? [])
244 // Match `read`: tombstoned (deleted / pending_deletion)
245 // certificates no longer satisfy the desired state.
246 .filter((cert) => isLive(cert.status))
247 .map((cert) => toAttributes(cert, zone.id)),
248 ),
249 ),
250 // A zone the scoped token can't access rejects with the typed
251 // Forbidden tag; skip it rather than failing the whole enumeration.
252 Effect.catchTag("Forbidden", () => Effect.succeed([])),
253 ),
254 { concurrency: 10 },
255 );
256 return rows.flat();
257 }),
258
259 delete: Effect.fn(function* ({ output }) {
260 // Deletion is idempotent: a certificate that is already gone surfaces
261 // as `CertificateNotFound`, and one already in (or past) deletion
262 // answers HTTP 400 "Certificate is already deleted."
263 // (`CertificateAlreadyDeleted`). Both mean the desired end state — the
264 // certificate is not live — is reached.
265 yield* originTls
266 .deleteOriginTlsClientAuth({
267 zoneId: output.zoneId,
268 certificateId: output.certificateId,
269 })
270 .pipe(
271 // A certificate still propagating its initial deployment answers
272 // code 1434 "Cannot delete resource while in pending deployment
273 // state." — this is why a destroy immediately after a deploy could
274 // leak the certificate. Deployment settles within seconds, so ride
275 // it out with a bounded (~60s) retry.
276 //
277 // Cloudflare serializes zone client-cert mutations per zone; a delete
278 // racing a sibling upload/delete on the SAME zone is rejected with
279 // HTTP 409 (`ZoneClientCertConflict`). Retry it on the same bounded
280 // schedule so the delete (and thus teardown) converges instead of
281 // leaking the certificate.
282 Effect.retry({
283 while: (e) =>
284 e._tag === "CertificatePendingDeployment" || e._tag === "ZoneClientCertConflict",
285 schedule: Schedule.spaced("5 seconds"),
286 times: 12,
287 }),
288 Effect.catchTag(["CertificateNotFound", "CertificateAlreadyDeleted"], () => Effect.void),
289 );
290 }),
291 });
292
293 /** A certificate that is being or has been deleted no longer satisfies the desired state. */
294 const isLive = (status: string | null | undefined): boolean =>
295 status !== "deleted" && status !== "pending_deletion";
296
297 // Observe a certificate by id, treating "not found" and "deleted /
298 // pending_deletion" (Cloudflare keeps tombstones readable by id) as missing.
299 const observeById = (zoneId: string, certificateId: string) =>
300 originTls.getOriginTlsClientAuth({ zoneId, certificateId }).pipe(
301 Effect.map((cert) => (isLive(cert.status) ? cert : undefined)),
302 Effect.catchTag("CertificateNotFound", () => Effect.undefined),
303 );
304
305 // Locate a live certificate by exact PEM content. Tombstoned certificates
306 // are excluded so a destroy→deploy cycle re-creates (resurrects) instead of
307 // adopting a certificate that is on its way out.
308 const findByContent = (zoneId: string, certificate: string) =>
309 Effect.gen(function* () {
310 const list = yield* originTls.listOriginTlsClientAuths({ zoneId });
311 // Cloudflare returns `result: null` (not `[]`) for a zone whose cert store
312 // is empty — treat it as no matches.
313 return (list.result ?? []).find(
314 (c) => isLive(c.status) && normalizePem(c.certificate ?? "") === normalizePem(certificate),
315 );
316 });
317
318 const normalizePem = (pem: string): string => pem.trim();
319
320 const unwrap = (value: Redacted.Redacted<string> | string): string =>
321 Redacted.isRedacted(value) ? Redacted.value(value) : value;
322
323 type CertificateShape = {
324 id?: string | null;
325 status?: string | null;
326 expiresOn?: string | null;
327 issuer?: string | null;
328 signature?: string | null;
329 uploadedOn?: string | null;
330 };
331
332 const toAttributes = (cert: CertificateShape, zoneId: string): CertificateAttributes => ({
333 certificateId: cert.id!,
334 zoneId,
335 status: cert.status ?? undefined,
336 expiresOn: cert.expiresOn ?? undefined,
337 issuer: cert.issuer ?? undefined,
338 signature: cert.signature ?? undefined,
339 uploadedOn: cert.uploadedOn ?? undefined,
340 });