@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 548 lines 20.3 KB
Raw
1 import crypto from "node:crypto";
2 import * as customCertificates from "@distilled.cloud/cloudflare/custom-certificates";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Predicate from "effect/Predicate";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
13 import type { Providers } from "../Providers.ts";
14 import { listAllZones } from "../Zone/lookup.ts";
15
16 const TypeId = "Cloudflare.CustomCertificate.CustomCertificate" as const;
17 type TypeId = typeof TypeId;
18
19 /**
20 * How Cloudflare builds the certificate chain served to clients.
21 *
22 * A `ubiquitous` bundle has the highest probability of being verified
23 * everywhere, even by clients using outdated or unusual trust stores. An
24 * `optimal` bundle uses the shortest chain and newest intermediates. `force`
25 * serves exactly the certificate you uploaded.
26 */
27 export type BundleMethod = "ubiquitous" | "optimal" | "force";
28
29 /**
30 * SNI support of the uploaded certificate. `legacy_custom` enables support
31 * for legacy clients which do not include SNI in the TLS handshake (requires
32 * dedicated IPs); `sni_custom` is the recommended modern option.
33 */
34 export type Type = "legacy_custom" | "sni_custom";
35
36 /**
37 * Lifecycle status of a custom certificate. Uploads are asynchronous —
38 * a certificate transitions `initializing` → `active`.
39 */
40 export type Status =
41 | "active"
42 | "expired"
43 | "deleted"
44 | "pending"
45 | "initializing"
46 // Keep the union open so new Cloudflare statuses aren't blocked by stale
47 // types.
48 | (string & {});
49
50 /**
51 * Geo Key Manager region restriction: where the certificate's private key
52 * may be held locally for optimal TLS performance.
53 */
54 export interface GeoRestrictions {
55 /**
56 * Region label: `us`, `eu`, or `highest_security`.
57 */
58 label: "us" | "eu" | "highest_security";
59 }
60
61 export interface Props {
62 /**
63 * Zone the certificate is uploaded to. Custom certificates are a
64 * zone-level feature (Business and Enterprise plans only).
65 *
66 * Immutable — moving a certificate between zones triggers a replacement.
67 */
68 zoneId: string;
69 /**
70 * The zone's SSL certificate — the leaf certificate plus any
71 * intermediates, in PEM format. Plain `string` (not `string`) so
72 * its content hash is statically computable.
73 *
74 * Mutable — Cloudflare PATCHes a new certificate onto the same record,
75 * keeping the certificate id stable across rotations.
76 */
77 certificate: string;
78 /**
79 * The certificate's private key in PEM format. Not required when
80 * `customCsrId` is provided, in which case the private key is retrieved
81 * from the CSR record held by Cloudflare.
82 *
83 * Write-only — Cloudflare never echoes the key back; a content hash of
84 * the certificate/key pair is persisted in the attributes for diffing.
85 */
86 privateKey?: Redacted.Redacted<string>;
87 /**
88 * The identifier of a Custom CSR held by Cloudflare to source the private
89 * key from, as an alternative to uploading `privateKey`.
90 */
91 customCsrId?: string;
92 /**
93 * How Cloudflare builds the certificate chain served to clients.
94 * @default "ubiquitous"
95 */
96 bundleMethod?: BundleMethod;
97 /**
98 * SNI support: `sni_custom` (recommended) or `legacy_custom` (supports
99 * non-SNI clients; requires dedicated IPs).
100 *
101 * Immutable — the PATCH endpoint does not accept `type`, so changing it
102 * triggers a replacement.
103 * @default "legacy_custom"
104 */
105 type?: Type;
106 /**
107 * Geo Key Manager region restriction for the private key. Mutually
108 * exclusive with `policy`.
109 */
110 geoRestrictions?: GeoRestrictions;
111 /**
112 * Geo Key Manager policy expression (e.g.
113 * `(country: US) or (region: EU)`) that determines where the private key
114 * is held. Mutually exclusive with `geoRestrictions`. Cloudflare echoes
115 * this back as the `policyRestrictions` attribute.
116 */
117 policy?: string;
118 /**
119 * The environment to deploy the certificate to. Staging deploys are an
120 * Enterprise feature. Write-only — not echoed back by the API.
121 * @default "production"
122 */
123 deploy?: "staging" | "production";
124 /**
125 * The order/priority in which the certificate is used in a request. A
126 * higher priority breaks ties across overlapping `legacy_custom`
127 * certificates. Synced via the prioritize endpoint when it differs from
128 * the observed value.
129 * @default API-assigned
130 */
131 priority?: number;
132 }
133
134 export interface Attributes {
135 /** Cloudflare-assigned identifier of the custom certificate. Stable across in-place certificate rotations. */
136 certificateId: string;
137 /** Zone the certificate belongs to. */
138 zoneId: string;
139 /** Hostnames covered by the certificate. */
140 hosts: string[];
141 /** The certificate authority that issued the certificate. */
142 issuer: string | undefined;
143 /** The type of hash used for the certificate signature. */
144 signature: string | undefined;
145 /** ISO8601 date the certificate expires. */
146 expiresOn: string | undefined;
147 /** ISO8601 date the certificate was uploaded to Cloudflare. */
148 uploadedOn: string | undefined;
149 /** ISO8601 date the certificate was last modified. */
150 modifiedOn: string | undefined;
151 /** How Cloudflare builds the certificate chain served to clients. */
152 bundleMethod: BundleMethod | undefined;
153 /** SNI support the certificate was uploaded with. Not echoed by the API — persisted from the input props. */
154 type: Type;
155 /** The order/priority in which the certificate is used in a request. */
156 priority: number | undefined;
157 /** Lifecycle status of the certificate (`initializing` → `active`). */
158 status: Status | undefined;
159 /** Geo Key Manager policy expression, as echoed by the API for the `policy` prop. */
160 policyRestrictions: string | undefined;
161 /** Geo Key Manager region restriction, if set. */
162 geoRestrictions: GeoRestrictions | undefined;
163 /**
164 * SHA-256 hash of the uploaded certificate/private key pair. Cloudflare
165 * never echoes the PEM contents back, so this hash is the diff baseline
166 * for deciding whether to re-push the certificate (a documented exception
167 * to "observation > assumption").
168 */
169 contentHash: string;
170 }
171
172 export type CustomCertificate = Resource<TypeId, Props, Attributes, never, Providers>;
173
174 /**
175 * A Cloudflare custom (BYO) edge certificate — upload your own SSL
176 * certificate and private key to be served at Cloudflare's edge for a zone.
177 *
178 * Custom certificates are a **Business / Enterprise** feature; on lower
179 * plans every API call fails with the typed `PlanLevelNotAllowed` error
180 * (Cloudflare error code 1011).
181 *
182 * The certificate id is stable across in-place rotations: PATCHing a new
183 * `certificate`/`privateKey` pair keeps the same id. Cloudflare never echoes
184 * the PEM contents back, so a SHA-256 content hash of the pair is persisted
185 * in the attributes and used as the rotation diff baseline. Only `zoneId`
186 * and `type` force a replacement.
187 * ### Uploading a certificate
188 * **Example:** Basic SNI certificate
189 * ```typescript
190 * const cert = yield* Cloudflare.CustomCertificate.CustomCertificate("EdgeCert", {
191 * zoneId: zone.zoneId,
192 * certificate: certPem,
193 * privateKey: Redacted.make(keyPem),
194 * type: "sni_custom",
195 * });
196 * ```
197 *
198 * **Example:** Optimal bundle with a Geo Key Manager region
199 * ```typescript
200 * yield* Cloudflare.CustomCertificate.CustomCertificate("EuCert", {
201 * zoneId: zone.zoneId,
202 * certificate: certPem,
203 * privateKey: Redacted.make(keyPem),
204 * type: "sni_custom",
205 * bundleMethod: "optimal",
206 * geoRestrictions: { label: "eu" },
207 * });
208 * ```
209 *
210 * ### Rotating the certificate
211 * **Example:** Rotate in place
212 * ```typescript
213 * // Changing `certificate`/`privateKey` PATCHes the same certificate id —
214 * // no replacement, no coverage gap.
215 * yield* Cloudflare.CustomCertificate.CustomCertificate("EdgeCert", {
216 * zoneId: zone.zoneId,
217 * certificate: renewedCertPem,
218 * privateKey: Redacted.make(renewedKeyPem),
219 * type: "sni_custom",
220 * });
221 * ```
222 *
223 * ### Prioritizing overlapping certificates
224 * **Example:** Explicit priority
225 * ```typescript
226 * // Higher priority breaks ties across overlapping legacy_custom certs.
227 * yield* Cloudflare.CustomCertificate.CustomCertificate("PrimaryCert", {
228 * zoneId: zone.zoneId,
229 * certificate: certPem,
230 * privateKey: Redacted.make(keyPem),
231 * priority: 1,
232 * });
233 * ```
234 *
235 * @see https://developers.cloudflare.com/ssl/edge-certificates/custom-certificates/
236 *
237 * @resource
238 * @product Custom Certificates
239 * @category SSL/TLS & Certificates
240 */
241 export const CustomCertificate = Resource<CustomCertificate>(TypeId, {
242 aliases: ["Cloudflare.CustomCertificate"],
243 });
244
245 /**
246 * Returns true if the given value is a CustomCertificate resource.
247 */
248 export const isCustomCertificate = (value: unknown): value is CustomCertificate =>
249 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
250
251 export const CustomCertificateProvider = () =>
252 Provider.succeed(CustomCertificate, {
253 stables: ["certificateId", "zoneId", "type", "uploadedOn"],
254
255 // Zone-scoped collection: fan out over every zone and exhaustively
256 // paginate that zone's custom certificates. The PEM contents and the
257 // uploaded `type` are write-only (never echoed back), so — exactly like
258 // `read`'s cold adoption path — the unknowable `type`/`contentHash`
259 // default to `legacy_custom`/`""`. Plan-gated zones reject the route with
260 // the typed `PlanLevelNotAllowed` (custom certs are Business/Enterprise),
261 // zones that can't host custom certs (partial/pending/deleted between
262 // list and read) reject with `ZoneNotFound` ("Cannot find a valid zone"),
263 // and freshly-scoped tokens may blip `Forbidden`; all three skip the zone
264 // so enumeration still returns every zone it can read.
265 list: Effect.fn(function* () {
266 const { accountId } = yield* yield* CloudflareEnvironment;
267 const zones = yield* listAllZones(accountId);
268 const rows = yield* Effect.forEach(
269 zones,
270 (zone) =>
271 customCertificates.listCustomCertificates.pages({ zoneId: zone.id }).pipe(
272 Stream.runCollect,
273 Effect.map((chunk) =>
274 Array.from(chunk).flatMap((page) =>
275 (page.result ?? []).map((cert): Attributes =>
276 toAttributes(cert, {
277 type: "legacy_custom",
278 contentHash: "",
279 }),
280 ),
281 ),
282 ),
283 Effect.catchTag(["PlanLevelNotAllowed", "ZoneNotFound", "Forbidden"], () =>
284 Effect.succeed([] as Attributes[]),
285 ),
286 ),
287 { concurrency: 10 },
288 );
289 return rows.flat();
290 }),
291
292 diff: Effect.fn(function* ({ olds, news, output }) {
293 if (!isResolved(news)) return undefined;
294 // Zone move replaces. zoneId is Input<string>; compare only once
295 // both sides are concrete.
296 const oldZone =
297 output?.zoneId ??
298 (olds !== undefined && isResolved(olds) ? (olds.zoneId as string | undefined) : undefined);
299 if (
300 typeof oldZone === "string" &&
301 typeof news.zoneId === "string" &&
302 oldZone !== news.zoneId
303 ) {
304 return { action: "replace" } as const;
305 }
306 // `type` is create-only (the PATCH body does not accept it).
307 const oldType =
308 output?.type ??
309 (olds !== undefined && isResolved(olds) ? olds.type : undefined) ??
310 "legacy_custom";
311 if ((news.type ?? "legacy_custom") !== oldType) {
312 return { action: "replace" } as const;
313 }
314 return undefined;
315 }),
316
317 read: Effect.fn(function* ({ output, olds }) {
318 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
319 if (zoneId === undefined) return undefined;
320
321 // Owned path: refresh by our persisted certificate id.
322 if (output?.certificateId) {
323 const observed = yield* getCertificate(zoneId, output.certificateId);
324 return observed
325 ? toAttributes(observed, {
326 type: output.type,
327 contentHash: output.contentHash,
328 })
329 : undefined;
330 }
331
332 // Cold path: state was lost. Custom certificates carry no ownership
333 // markers and no name, so identify the desired certificate by its
334 // parsed expiry timestamp (an upload of the same PEM always yields
335 // the same `expires_on`) and report it as `Unowned` so the engine
336 // gates takeover behind the adopt policy.
337 if (olds?.certificate === undefined) return undefined;
338 const parsed = yield* parseCertificate(olds.certificate);
339 const observed = yield* findByExpiry(zoneId, parsed.expiresAtMs);
340 if (observed) {
341 return Unowned(
342 toAttributes(observed, {
343 type: olds.type ?? "legacy_custom",
344 // The live cert/key contents are unknowable — force one
345 // convergence PATCH after adoption.
346 contentHash: "",
347 }),
348 );
349 }
350 return undefined;
351 }),
352
353 reconcile: Effect.fn(function* ({ news, output }) {
354 // Inputs have been resolved to concrete strings by Plan.
355 const zoneId = news.zoneId as string;
356 const customCsrId = news.customCsrId as string | undefined;
357 const type = news.type ?? output?.type ?? "legacy_custom";
358 const desiredHash = yield* hashContent(news);
359
360 // 1. Observe — the certificate id cached on `output` is a hint, not
361 // a guarantee: a missing certificate falls through to create.
362 let observed = output?.certificateId
363 ? yield* getCertificate(zoneId, output.certificateId)
364 : undefined;
365
366 // 2. Ensure — upload when missing. Certificates have no uniqueness
367 // constraint on Cloudflare's side, so there is no AlreadyExists
368 // race to tolerate.
369 if (!observed) {
370 observed = yield* customCertificates.createCustomCertificate({
371 zoneId,
372 certificate: news.certificate,
373 privateKey: news.privateKey ? Redacted.value(news.privateKey) : undefined,
374 customCsrId,
375 bundleMethod: news.bundleMethod,
376 type: news.type,
377 geoRestrictions: news.geoRestrictions,
378 policy: news.policy,
379 deploy: news.deploy,
380 });
381 // The freshly uploaded contents are the desired contents.
382 observed = yield* syncPriority(zoneId, observed, news.priority);
383 return toAttributes(observed, { type, contentHash: desiredHash });
384 }
385
386 // 3. Sync — diff observed cloud state against desired. The PEM
387 // contents are write-only, so the persisted content hash is the
388 // baseline for the certificate/key pair; everything else diffs
389 // against the observed response.
390 const certDirty = output?.contentHash !== desiredHash;
391 const bundleDirty =
392 news.bundleMethod !== undefined && observed.bundleMethod !== news.bundleMethod;
393 const geoDirty =
394 news.geoRestrictions !== undefined &&
395 observed.geoRestrictions?.label !== news.geoRestrictions.label;
396 const policyDirty =
397 news.policy !== undefined && (observed.policyRestrictions ?? undefined) !== news.policy;
398
399 if (certDirty || bundleDirty || geoDirty || policyDirty) {
400 observed = yield* customCertificates.patchCustomCertificate({
401 zoneId,
402 customCertificateId: observed.id,
403 ...(certDirty
404 ? {
405 certificate: news.certificate,
406 privateKey: news.privateKey ? Redacted.value(news.privateKey) : undefined,
407 customCsrId,
408 deploy: news.deploy,
409 }
410 : {}),
411 ...(bundleDirty ? { bundleMethod: news.bundleMethod } : {}),
412 ...(geoDirty ? { geoRestrictions: news.geoRestrictions } : {}),
413 ...(policyDirty ? { policy: news.policy } : {}),
414 });
415 }
416
417 observed = yield* syncPriority(zoneId, observed, news.priority);
418 return toAttributes(observed, { type, contentHash: desiredHash });
419 }),
420
421 delete: Effect.fn(function* ({ output }) {
422 yield* customCertificates
423 .deleteCustomCertificate({
424 zoneId: output.zoneId,
425 customCertificateId: output.certificateId,
426 })
427 .pipe(Effect.catchTag("CustomCertificateNotFound", () => Effect.void));
428 }),
429 });
430
431 // ---------------------------------------------------------------------------
432 // Helpers
433 // ---------------------------------------------------------------------------
434
435 type ObservedCertificate = customCertificates.GetCustomCertificateResponse;
436
437 /**
438 * Read a certificate by id, mapping "gone" (`CustomCertificateNotFound`,
439 * HTTP 404) to `undefined`.
440 */
441 const getCertificate = (zoneId: string, customCertificateId: string) =>
442 customCertificates.getCustomCertificate({ zoneId, customCertificateId }).pipe(
443 Effect.map((cert): ObservedCertificate | undefined => cert),
444 Effect.catchTag("CustomCertificateNotFound", () => Effect.undefined),
445 );
446
447 /**
448 * Find a certificate in the zone whose `expires_on` matches the desired
449 * PEM's parsed expiry. Uploading the same certificate always produces the
450 * same expiry, making it the best identity available (the API neither
451 * echoes the PEM nor exposes the serial number). If several match, pick the
452 * oldest upload for determinism.
453 */
454 const findByExpiry = (zoneId: string, expiresAtMs: number) =>
455 customCertificates.listCustomCertificates.items({ zoneId }).pipe(
456 Stream.runCollect,
457 Effect.map((chunk) =>
458 Array.from(chunk)
459 .filter((cert) => cert.expiresOn != null && Date.parse(cert.expiresOn) === expiresAtMs)
460 .sort((a, b) => (a.uploadedOn ?? "").localeCompare(b.uploadedOn ?? ""))
461 .at(0),
462 ),
463 );
464
465 /**
466 * Parse the leaf certificate of a PEM bundle. Sync CPU-only Node API,
467 * wrapped in `Effect.try` so a malformed PEM surfaces as a typed failure
468 * instead of a thrown exception.
469 */
470 class CertificateParseError extends Data.TaggedError("CertificateParseError")<{
471 message: string;
472 cause?: unknown;
473 }> {}
474
475 const parseCertificate = (pem: string) =>
476 Effect.try({
477 try: () => {
478 const x509 = new crypto.X509Certificate(pem);
479 return { expiresAtMs: Date.parse(x509.validTo) };
480 },
481 catch: (cause) =>
482 new CertificateParseError({
483 message: `failed to parse certificate PEM: ${cause instanceof Error ? cause.message : String(cause)}`,
484 cause,
485 }),
486 });
487
488 /**
489 * SHA-256 over the write-only inputs (certificate, private key, CSR id).
490 * Persisted in the attributes as the rotation diff baseline because the API
491 * never returns the PEM contents.
492 */
493 const hashContent = (news: Props) =>
494 Effect.sync(() =>
495 crypto
496 .createHash("sha256")
497 .update(news.certificate)
498 .update("\n")
499 .update(news.privateKey ? Redacted.value(news.privateKey) : "")
500 .update("\n")
501 .update((news.customCsrId as string | undefined) ?? "")
502 .digest("hex"),
503 );
504
505 /**
506 * Converge the certificate's priority via the prioritize endpoint when an
507 * explicit `priority` is desired and differs from the observed value.
508 */
509 const syncPriority = (
510 zoneId: string,
511 observed: ObservedCertificate,
512 priority: number | undefined,
513 ) =>
514 Effect.gen(function* () {
515 if (priority === undefined || observed.priority === priority) {
516 return observed;
517 }
518 yield* customCertificates.putPrioritize({
519 zoneId,
520 certificates: [{ id: observed.id, priority }],
521 });
522 // Re-observe so the returned attributes reflect the final state.
523 const fresh = yield* getCertificate(zoneId, observed.id);
524 return fresh ?? observed;
525 });
526
527 const toAttributes = (
528 cert: ObservedCertificate,
529 meta: { type: Type; contentHash: string },
530 ): Attributes => ({
531 certificateId: cert.id,
532 zoneId: cert.zoneId,
533 hosts: [...(cert.hosts ?? [])],
534 issuer: cert.issuer ?? undefined,
535 signature: cert.signature ?? undefined,
536 expiresOn: cert.expiresOn ?? undefined,
537 uploadedOn: cert.uploadedOn ?? undefined,
538 modifiedOn: cert.modifiedOn ?? undefined,
539 bundleMethod: (cert.bundleMethod as BundleMethod | null | undefined) ?? undefined,
540 type: meta.type,
541 priority: cert.priority ?? undefined,
542 status: cert.status ?? undefined,
543 policyRestrictions: cert.policyRestrictions ?? undefined,
544 geoRestrictions: cert.geoRestrictions?.label
545 ? { label: cert.geoRestrictions.label as "us" | "eu" | "highest_security" }
546 : undefined,
547 contentHash: meta.contentHash,
548 });