@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 308 lines 11 KB
Raw
1 import * as acm from "@distilled.cloud/cloudflare/acm";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
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.Acm.CustomTrustStore" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Lifecycle status of an uploaded custom trust store certificate.
18 * Upload is asynchronous: certificates start `initializing` and progress
19 * to `active`; deletes go through `pending_deletion` before `deleted`.
20 */
21 export type CustomTrustStoreStatus =
22 | "initializing"
23 | "pending_deployment"
24 | "active"
25 | "pending_deletion"
26 | "deleted"
27 | "expired"
28 | (string & {});
29
30 export interface CustomTrustStoreProps {
31 /**
32 * Zone the trust store certificate belongs to.
33 *
34 * Immutable — moving the certificate to another zone triggers a
35 * replacement.
36 */
37 zoneId: string;
38 /**
39 * The root CA certificate in PEM format. Only root CA certificates are
40 * accepted; intermediate and leaf certificates are rejected by
41 * Cloudflare.
42 *
43 * Immutable — the API has no update operation, so changing the
44 * certificate triggers a replacement.
45 */
46 certificate: string;
47 }
48
49 export interface CustomTrustStoreAttributes {
50 /** Cloudflare-assigned identifier of the trust store certificate. */
51 id: string;
52 /** Zone the certificate belongs to. */
53 zoneId: string;
54 /** The root CA certificate in PEM format, as echoed by Cloudflare. */
55 certificate: string;
56 /** When the certificate expires. */
57 expiresOn: string;
58 /** The certificate authority that issued the certificate. */
59 issuer: string;
60 /** The type of hash used for the certificate. */
61 signature: string;
62 /** Deployment status of the certificate. */
63 status: CustomTrustStoreStatus;
64 /** When the certificate was uploaded to Cloudflare. */
65 uploadedOn: string;
66 /** When the certificate was last modified. */
67 updatedAt: string;
68 }
69
70 export type CustomTrustStore = Resource<
71 TypeId,
72 CustomTrustStoreProps,
73 CustomTrustStoreAttributes,
74 never,
75 Providers
76 >;
77
78 /**
79 * A root CA certificate in a zone's custom origin trust store
80 * (`/zones/{zone_id}/acm/custom_trust_store`). Cloudflare uses the trust
81 * store to validate your origin server's certificate when connecting to
82 * the origin (e.g. with Full (strict) SSL and a private CA at the origin).
83 *
84 * Requires the Advanced Certificate Manager entitlement on the zone —
85 * without it every call fails with the typed
86 * `AdvancedCertificateManagerRequired` (code 1450) error.
87 *
88 * The certificate is immutable: there is no update API, so changing the
89 * PEM (or the zone) replaces the resource. Trust store certificates carry
90 * no ownership markers, so a cold `read` scans the zone for a certificate
91 * with the same PEM body and reports it as `Unowned` — the engine refuses
92 * to take it over unless `--adopt` (or `adopt(true)`) is set.
93 * ### Uploading a root CA
94 * **Example:** Trust a private root CA for origin pulls
95 * ```typescript
96 * const trustStore = yield* Cloudflare.Acm.CustomTrustStore("OriginRootCa", {
97 * zoneId: zone.zoneId,
98 * certificate: rootCaPem, // "-----BEGIN CERTIFICATE-----\n..."
99 * });
100 * ```
101 *
102 * **Example:** Load the PEM from a file
103 * ```typescript
104 * const fs = yield* FileSystem.FileSystem;
105 * const pem = yield* fs.readFileString("./certs/root-ca.pem");
106 * yield* Cloudflare.Acm.CustomTrustStore("OriginRootCa", {
107 * zoneId: zone.zoneId,
108 * certificate: pem,
109 * });
110 * ```
111 *
112 * @see https://developers.cloudflare.com/api/resources/acm/
113 *
114 * @resource
115 * @product ACM
116 * @category SSL/TLS & Certificates
117 */
118 export const CustomTrustStore = Resource<CustomTrustStore>(TypeId);
119
120 /**
121 * Returns true if the given value is a CustomTrustStore resource.
122 */
123 export const isCustomTrustStore = (value: unknown): value is CustomTrustStore =>
124 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
125
126 export const CustomTrustStoreProvider = () =>
127 Provider.succeed(CustomTrustStore, {
128 stables: ["id", "zoneId", "issuer", "signature", "uploadedOn"],
129
130 list: Effect.fn(function* () {
131 const { accountId } = yield* yield* CloudflareEnvironment;
132 // Trust stores live inside a zone (`/zones/{zone_id}/acm/...`) with
133 // no account-wide collection API — enumerate every zone and list
134 // within each, paginating exhaustively.
135 const zones = yield* listAllZones(accountId);
136 const rows = yield* Effect.forEach(
137 zones,
138 (zone) =>
139 acm.listCustomTrustStores.pages({ zoneId: zone.id }).pipe(
140 Stream.runCollect,
141 Effect.map((chunk) =>
142 Array.from(chunk).flatMap((page) =>
143 (page.result ?? [])
144 .filter((cert) => !isGoneStatus(cert.status))
145 .map((cert) => toAttributes(zone.id, cert)),
146 ),
147 ),
148 // Zones without the Advanced Certificate Manager add-on reject
149 // the route with the typed entitlement tag — skip them.
150 Effect.catchTag("AdvancedCertificateManagerRequired", () =>
151 Effect.succeed([] as CustomTrustStoreAttributes[]),
152 ),
153 ),
154 { concurrency: 10 },
155 );
156 return rows.flat();
157 }),
158
159 diff: Effect.fn(function* ({ olds, news, output }) {
160 if (!isResolved(news)) return undefined;
161 // The certificate is the resource's identity — no update API exists.
162 const oldCertificate = olds?.certificate ?? output?.certificate;
163 if (
164 oldCertificate !== undefined &&
165 normalizePem(oldCertificate) !== normalizePem(news.certificate)
166 ) {
167 return { action: "replace" } as const;
168 }
169 // zoneId is Input<string>; compare only once both sides are concrete.
170 const oldZoneId =
171 output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
172 if (oldZoneId !== undefined && typeof news.zoneId === "string" && oldZoneId !== news.zoneId) {
173 return { action: "replace" } as const;
174 }
175 return undefined;
176 }),
177
178 read: Effect.fn(function* ({ output, olds }) {
179 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
180 if (!zoneId) return undefined;
181
182 // Owned path: refresh by our persisted certificate id.
183 if (output?.id) {
184 const observed = yield* getTrustStore(zoneId, output.id);
185 if (observed && !isGoneStatus(observed.status)) {
186 return toAttributes(zoneId, observed);
187 }
188 }
189
190 // Adoption path: a certificate with the same PEM may already exist.
191 // Trust store entries carry no ownership markers, so report it as
192 // `Unowned` and let the engine gate takeover behind the adopt policy.
193 const certificate = output?.certificate ?? olds?.certificate;
194 if (certificate) {
195 const observed = yield* findByCertificate(zoneId, certificate);
196 if (observed) return Unowned(toAttributes(zoneId, observed));
197 }
198 return undefined;
199 }),
200
201 reconcile: Effect.fn(function* ({ news, output }) {
202 // Inputs have been resolved to concrete strings by Plan.
203 const zoneId = news.zoneId as string;
204
205 // 1. Observe — the id cached on `output` is a hint, not a guarantee:
206 // a missing (or async-deleted) certificate falls through to the
207 // PEM scan and then to create.
208 let observed = output?.id ? yield* getTrustStore(zoneId, output.id) : undefined;
209 if (observed && isGoneStatus(observed.status)) observed = undefined;
210
211 // 2. Fall back to scanning the zone for the same PEM body. Ownership
212 // has already been verified upstream — `read` reports foreign
213 // certificates as `Unowned` and the engine gates adoption.
214 if (!observed) {
215 observed = yield* findByCertificate(zoneId, news.certificate);
216 }
217
218 // 3. Ensure — upload when missing. There is no sync step: the
219 // certificate is immutable (diff replaces on any change).
220 if (!observed) {
221 observed = yield* acm.createCustomTrustStore({
222 zoneId,
223 certificate: news.certificate,
224 });
225 }
226
227 return toAttributes(zoneId, observed);
228 }),
229
230 delete: Effect.fn(function* ({ output }) {
231 // Observe first — re-deleting an already-gone certificate is a no-op
232 // (delete must stay idempotent across crashed runs).
233 const observed = yield* getTrustStore(output.zoneId, output.id);
234 if (!observed || isGoneStatus(observed.status)) return;
235 yield* acm
236 .deleteCustomTrustStore({
237 zoneId: output.zoneId,
238 customOriginTrustStoreId: output.id,
239 })
240 .pipe(
241 Effect.catchTag(
242 ["CustomTrustStoreNotFound", "InvalidObjectIdentifier"],
243 () => Effect.void,
244 ),
245 );
246 }),
247 });
248
249 // ---------------------------------------------------------------------------
250 // Helpers
251 // ---------------------------------------------------------------------------
252
253 type ObservedTrustStore =
254 | acm.GetCustomTrustStoreResponse
255 | acm.CreateCustomTrustStoreResponse
256 | acm.ListCustomTrustStoresResponse["result"][number];
257
258 /**
259 * Deletion is asynchronous — a certificate lingers in `pending_deletion`
260 * (then `deleted`) after a successful DELETE. Treat both as "gone" so
261 * observation does not resurrect a dying certificate.
262 */
263 const isGoneStatus = (status: CustomTrustStoreStatus): boolean =>
264 status === "pending_deletion" || status === "deleted";
265
266 /**
267 * Read a trust store certificate by id, mapping "gone"
268 * (`CustomTrustStoreNotFound` / `InvalidObjectIdentifier`) to `undefined`.
269 */
270 const getTrustStore = (zoneId: string, id: string) =>
271 acm.getCustomTrustStore({ zoneId, customOriginTrustStoreId: id }).pipe(
272 Effect.map((cert): ObservedTrustStore | undefined => cert),
273 Effect.catchTag(
274 ["CustomTrustStoreNotFound", "InvalidObjectIdentifier"],
275 () => Effect.undefined,
276 ),
277 );
278
279 /**
280 * Find a live certificate with the same PEM body in the zone's trust
281 * store. PEMs are compared after whitespace normalization so formatting
282 * differences (trailing newline, CRLF) don't defeat the match.
283 */
284 const findByCertificate = (zoneId: string, certificate: string) =>
285 acm.listCustomTrustStores.items({ zoneId }).pipe(
286 Stream.runCollect,
287 Effect.map((chunk) =>
288 Array.from(chunk).find(
289 (cert): cert is ObservedTrustStore =>
290 !isGoneStatus(cert.status) &&
291 normalizePem(cert.certificate) === normalizePem(certificate),
292 ),
293 ),
294 );
295
296 const normalizePem = (pem: string): string => pem.replace(/\r\n/g, "\n").trim();
297
298 const toAttributes = (zoneId: string, cert: ObservedTrustStore): CustomTrustStoreAttributes => ({
299 id: cert.id,
300 zoneId,
301 certificate: cert.certificate,
302 expiresOn: cert.expiresOn,
303 issuer: cert.issuer,
304 signature: cert.signature,
305 status: cert.status,
306 uploadedOn: cert.uploadedOn,
307 updatedAt: cert.updatedAt,
308 });