@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 386 lines 15 KB
Raw
1 import * as originCa from "@distilled.cloud/cloudflare/origin-ca-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 Predicate from "effect/Predicate";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { findZoneByName, listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.OriginCaCertificate.OriginCaCertificate" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Signature type requested on the certificate: `origin-rsa` (RSA),
18 * `origin-ecc` (ECDSA), or `keyless-certificate` (for Keyless SSL servers).
19 */
20 export type RequestType = "origin-rsa" | "origin-ecc" | "keyless-certificate";
21
22 /**
23 * Number of days the certificate should be valid for. Cloudflare only
24 * accepts this fixed set of validity periods.
25 */
26 export type Validity = 7 | 30 | 90 | 365 | 730 | 1095 | 5475;
27
28 export interface Props {
29 /**
30 * The Certificate Signing Request (CSR) in PEM format (newline-encoded).
31 * The CSR's key is yours; Cloudflare only signs it. Immutable — changing
32 * the CSR triggers a replacement (a new certificate is issued and the old
33 * one is revoked).
34 */
35 csr: string;
36 /**
37 * Hostnames or wildcard names (e.g. `*.example.com`) bound to the
38 * certificate. Hostnames must be fully qualified domain names belonging
39 * to zones on your account. Immutable — changing the hostnames triggers
40 * a replacement.
41 */
42 hostnames: string[];
43 /**
44 * Signature type desired on the certificate: `origin-rsa` (RSA),
45 * `origin-ecc` (ECDSA), or `keyless-certificate` (for Keyless SSL
46 * servers). Immutable — changing the request type triggers a replacement.
47 */
48 requestType: RequestType;
49 /**
50 * The number of days for which the certificate should be valid.
51 * Immutable — changing the validity triggers a replacement.
52 * @default 5475
53 */
54 requestedValidity?: Validity;
55 }
56
57 export interface Attributes {
58 /**
59 * Cloudflare-assigned identifier of the certificate (a long decimal
60 * serial string). Stable for the lifetime of the certificate.
61 */
62 certificateId: string;
63 /**
64 * The signed Origin CA certificate in PEM format (newline-encoded).
65 * Install this on your origin server alongside the private key that
66 * produced the CSR.
67 */
68 certificate: string;
69 /**
70 * The Certificate Signing Request the certificate was issued for.
71 */
72 csr: string;
73 /**
74 * Hostnames or wildcard names bound to the certificate.
75 */
76 hostnames: string[];
77 /**
78 * Signature type on the certificate.
79 */
80 requestType: RequestType;
81 /**
82 * The number of days the certificate was requested to be valid for.
83 */
84 requestedValidity: number;
85 /**
86 * When the certificate expires.
87 */
88 expiresOn: string | undefined;
89 }
90
91 export type OriginCaCertificate = Resource<TypeId, Props, Attributes, never, Providers>;
92
93 /**
94 * A Cloudflare Origin CA certificate — a free certificate signed by
95 * Cloudflare's Origin CA that encrypts traffic between Cloudflare's edge
96 * and your origin server. Origin CA certificates are only trusted by
97 * Cloudflare (not by browsers), so they are used together with proxied
98 * DNS records.
99 *
100 * You supply a CSR (keeping the private key to yourself); Cloudflare signs
101 * it synchronously and returns the certificate PEM. The endpoints are
102 * top-level (`/certificates`) — the zone is implied by the hostnames in the
103 * request, which must belong to zones on your account.
104 *
105 * Certificates are fully immutable: there is no update API, so changing any
106 * property triggers a replacement (a new certificate is issued, then the
107 * old one is revoked). Destroying the resource revokes the certificate.
108 * ### Issuing a certificate
109 * **Example:** RSA certificate for a single hostname
110 * ```typescript
111 * const cert = yield* Cloudflare.OriginCaCertificate.OriginCaCertificate("origin-cert", {
112 * csr: originCsrPem,
113 * hostnames: ["origin.example.com"],
114 * requestType: "origin-rsa",
115 * requestedValidity: 90,
116 * });
117 * ```
118 *
119 * **Example:** Wildcard ECDSA certificate with the default 15-year validity
120 * ```typescript
121 * const cert = yield* Cloudflare.OriginCaCertificate.OriginCaCertificate("wildcard-cert", {
122 * csr: wildcardCsrPem,
123 * hostnames: ["example.com", "*.example.com"],
124 * requestType: "origin-ecc",
125 * });
126 * ```
127 *
128 * ### Using the certificate
129 * **Example:** Install the signed PEM on your origin
130 * ```typescript
131 * // The signed certificate is returned synchronously on create:
132 * const pem = cert.certificate; // "-----BEGIN CERTIFICATE-----\n..."
133 * const expires = cert.expiresOn;
134 * ```
135 *
136 * @see https://developers.cloudflare.com/ssl/origin-configuration/origin-ca/
137 *
138 * @resource
139 * @product Origin CA Certificates
140 * @category SSL/TLS & Certificates
141 */
142 export const OriginCaCertificate = Resource<OriginCaCertificate>(TypeId, {
143 aliases: ["Cloudflare.OriginCaCertificate"],
144 });
145
146 /**
147 * Returns true if the given value is an OriginCaCertificate resource.
148 */
149 export const isOriginCaCertificate = (value: unknown): value is OriginCaCertificate =>
150 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
151
152 export const OriginCaCertificateProvider = () =>
153 Provider.succeed(OriginCaCertificate, {
154 // Every prop change is a replacement, so all attributes are stable
155 // across (non-existent) updates.
156 stables: [
157 "certificateId",
158 "certificate",
159 "csr",
160 "hostnames",
161 "requestType",
162 "requestedValidity",
163 "expiresOn",
164 ],
165
166 // Origin CA certificates are enumerated per zone (the list endpoint
167 // requires a `zone_id` query param). Fan out across every zone on the
168 // account and flatten. The list response omits the csr and requested
169 // validity, so `toAttributes` fills them with the defaults — matching the
170 // cold/unowned `read` shape. Origin CA endpoints may require the special
171 // Origin CA Key auth; a zone we can't enumerate rejects with `Forbidden`,
172 // which we skip rather than fail (the array stays as complete as the
173 // credentials allow).
174 list: Effect.fn(function* () {
175 const { accountId } = yield* yield* CloudflareEnvironment;
176 const zones = yield* listAllZones(accountId);
177 const rows = yield* Effect.forEach(
178 zones,
179 (zone) =>
180 originCa.listOriginCaCertificates.pages({ zoneId: zone.id }).pipe(
181 Stream.runCollect,
182 Effect.map((chunk) =>
183 Array.from(chunk).flatMap((page) =>
184 (page.result ?? [])
185 .filter((cert) => cert.id != null)
186 .map((cert): Attributes => toAttributes(cert)),
187 ),
188 ),
189 Effect.catchTag("Forbidden", () => Effect.succeed([] as Attributes[])),
190 ),
191 { concurrency: 10 },
192 );
193 return rows.flat();
194 }),
195
196 diff: Effect.fn(function* ({ olds, news }) {
197 const o = olds as Props | undefined;
198 const n = news as Props;
199 // No prior props to compare against — let the engine decide.
200 if (o?.csr === undefined) return undefined;
201 // There is no update API for Origin CA certificates — every change
202 // is a replacement.
203 if (
204 o.csr !== n.csr ||
205 o.requestType !== n.requestType ||
206 (o.requestedValidity ?? DEFAULT_VALIDITY) !== (n.requestedValidity ?? DEFAULT_VALIDITY) ||
207 !sameHostnames(o.hostnames, n.hostnames)
208 ) {
209 return { action: "replace" } as const;
210 }
211 return undefined;
212 }),
213
214 read: Effect.fn(function* ({ output, olds, previous }) {
215 // Owned path: refresh by our persisted certificate id. A revoked
216 // certificate is still returned by GET (with `revokedAt` set) but is
217 // gone for all practical purposes.
218 if (output?.certificateId) {
219 const observed = yield* getCertificate(output.certificateId);
220 return observed ? toAttributes(observed, { ...olds, ...output }) : undefined;
221 }
222
223 // Cold read — Origin CA certificates have no name or tags, so the
224 // only identity available is the exact hostname set within the zone
225 // implied by the hostnames. A match cannot be proven to be ours, so
226 // brand it `Unowned` and let the engine gate takeover behind the
227 // adopt policy. Ambiguity (several live certs with the same
228 // hostnames) means no identity at all — report missing and recreate
229 // (certificates are free and revocation is harmless).
230 // Output-valued hostname elements don't survive a `creating`-state
231 // round-trip (they deserialize as null/undefined) — without a concrete
232 // hostname there is no identity to search by.
233 if (typeof olds?.hostnames?.[0] !== "string") return undefined;
234 const matches = yield* findByHostnames(olds.hostnames);
235 if (matches.length !== 1) return undefined;
236 // A replacement issues a new certificate for the same hostnames: the
237 // one it is replacing is not the replacement.
238 if (matches[0].id === previous?.certificateId) return undefined;
239 const observed = yield* getCertificate(matches[0].id!);
240 return observed ? Unowned(toAttributes(observed, olds)) : undefined;
241 }),
242
243 reconcile: Effect.fn(function* ({ news, output }) {
244 // Observe — the certificate id cached on `output` is a hint, not a
245 // guarantee: a missing or revoked certificate falls through to
246 // "missing" and ensure re-issues.
247 const observed = output?.certificateId
248 ? yield* getCertificate(output.certificateId)
249 : undefined;
250
251 // Ensure — issue when missing. Issuance is synchronous: the signed
252 // PEM comes back in the create response. Ids are server-assigned, so
253 // there is no AlreadyExists race to tolerate.
254 if (!observed) {
255 const created = yield* originCa.createOriginCaCertificate({
256 csr: news.csr,
257 hostnames: news.hostnames,
258 requestType: news.requestType,
259 requestedValidity: news.requestedValidity ?? DEFAULT_VALIDITY,
260 });
261 return toAttributes(created, news);
262 }
263
264 // Sync — certificates are immutable; any prop change was already
265 // routed to replacement by diff, so there is nothing to converge.
266 // GET omits the csr and requested validity, so fill them from the
267 // desired props (they are guaranteed equal here).
268 return toAttributes(observed, news);
269 }),
270
271 delete: Effect.fn(function* ({ output }) {
272 // Delete = revoke. Idempotent: an unknown id (1101) or an
273 // already-revoked certificate (1014) both mean "gone".
274 //
275 // `CertificateRevocationFailed` (code 1000) is the dual-use generic
276 // "API errors encountered" Cloudflare returns when a revoke blips —
277 // most often during the replace-time GC delete, when the old
278 // certificate is revoked right after its replacement was issued.
279 // Left untyped it surfaced as `UnknownCloudflareError` and aborted the
280 // delete, orphaning the old certificate (it is no longer in state, so
281 // a later `stack.destroy()` cannot reclaim it). Bounded-retry the
282 // transient failure, then read back: a revoked/absent certificate
283 // counts as deleted; a still-live one re-raises so the leak is never
284 // silent.
285 yield* originCa.deleteOriginCaCertificate({ certificateId: output.certificateId }).pipe(
286 Effect.retry({
287 while: (e) => e._tag === "CertificateRevocationFailed",
288 schedule: Schedule.exponential("500 millis"),
289 times: 6,
290 }),
291 Effect.catchTags({
292 CertificateNotFound: () => Effect.void,
293 CertificateAlreadyRevoked: () => Effect.void,
294 CertificateRevocationFailed: (e) =>
295 getCertificate(output.certificateId).pipe(
296 Effect.flatMap((cert) => (cert ? Effect.fail(e) : Effect.void)),
297 ),
298 }),
299 );
300 }),
301 });
302
303 const DEFAULT_VALIDITY = 5475;
304
305 /**
306 * Read a certificate by id, mapping "gone" to `undefined`. Gone is either
307 * `CertificateNotFound` (Cloudflare error code 1101) or a successful GET of
308 * an already-revoked certificate (`revokedAt` set).
309 */
310 const getCertificate = (certificateId: string) =>
311 originCa.getOriginCaCertificate({ certificateId }).pipe(
312 Effect.map((cert) => (cert.revokedAt ? undefined : cert)),
313 Effect.catchTag("CertificateNotFound", () => Effect.undefined),
314 );
315
316 /**
317 * Find live certificates with exactly the given hostname set. The zone is
318 * implied by the hostnames: resolve the registered zone by walking the
319 * suffixes of the first hostname (wildcard labels stripped), then scan the
320 * zone's certificate list. Revoked certificates drop out of the list
321 * immediately, so every match is live.
322 */
323 const findByHostnames = (hostnames: string[]) =>
324 Effect.gen(function* () {
325 const { accountId } = yield* yield* CloudflareEnvironment;
326 const hostname = hostnames[0].replace(/^\*\./, "");
327 const zoneId = yield* resolveZoneIdForHostname(accountId, hostname);
328 if (!zoneId) return [];
329 const certs = yield* originCa.listOriginCaCertificates.items({ zoneId }).pipe(
330 Stream.filter((cert) => sameHostnames([...cert.hostnames], hostnames)),
331 Stream.runCollect,
332 );
333 return [...certs].sort((a, b) => (a.id ?? "").localeCompare(b.id ?? ""));
334 });
335
336 /**
337 * Resolve the zone id for a hostname by trying each suffix of the hostname
338 * as a zone name (e.g. `a.b.example.com` → `a.b.example.com`,
339 * `b.example.com`, `example.com`). Returns `undefined` when no zone on the
340 * account matches.
341 */
342 const resolveZoneIdForHostname = (accountId: string, hostname: string) =>
343 Effect.gen(function* () {
344 const parts = hostname.split(".");
345 for (let i = 0; i < parts.length - 1; i++) {
346 const name = parts.slice(i).join(".");
347 const zone = yield* findZoneByName({ accountId, name });
348 if (zone) return zone.id;
349 }
350 return undefined;
351 });
352
353 const sameHostnames = (observed: readonly string[], desired: readonly string[]) =>
354 observed.length === desired.length &&
355 [...observed].sort().join(",") === [...desired].sort().join(",");
356
357 type CertificateShape = {
358 id?: string | null;
359 certificate?: string | null;
360 csr?: string | null;
361 hostnames: readonly string[];
362 requestType?: string | null;
363 requestedValidity?: number | null;
364 expiresOn?: string | null;
365 };
366
367 /**
368 * GET/list responses omit the `csr` and `requested_validity` fields, so
369 * fill them from the desired props (reconcile) or prior state (read).
370 */
371 const toAttributes = (
372 cert: CertificateShape,
373 fallback?: {
374 csr?: string;
375 requestType?: RequestType;
376 requestedValidity?: number;
377 },
378 ): Attributes => ({
379 certificateId: cert.id!,
380 certificate: cert.certificate ?? "",
381 csr: cert.csr ?? fallback?.csr ?? "",
382 hostnames: [...cert.hostnames],
383 requestType: (cert.requestType ?? fallback?.requestType ?? "origin-rsa") as RequestType,
384 requestedValidity: cert.requestedValidity ?? fallback?.requestedValidity ?? DEFAULT_VALIDITY,
385 expiresOn: cert.expiresOn ?? undefined,
386 });