@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 391 lines 14.2 KB
Raw
1 import * as mtls from "@distilled.cloud/cloudflare/mtls-certificates";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
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 Redacted from "effect/Redacted";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const TypeId = "Cloudflare.MtlsCertificate.MtlsCertificate" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * How the certificate was created and who manages it. Certificates uploaded
19 * through this resource are always `"custom"`.
20 */
21 export type Type =
22 | "custom"
23 | "gateway_managed"
24 | "access_managed"
25 // Keep the union open so new Cloudflare types aren't blocked by stale types.
26 | (string & {});
27
28 export type Props = {
29 /**
30 * Optional human-readable name for the certificate. If omitted, a unique
31 * name will be generated. There is no update API, so changing the name
32 * triggers a replacement. Names are unique per account, so replacing a
33 * certificate that keeps an explicit name deletes the old certificate
34 * before uploading the new one. Omit `name` to rotate create-first.
35 * @default ${app}-${stage}-${id}
36 */
37 name?: string;
38 /**
39 * Indicates whether the certificate is a CA certificate (`true`) used to
40 * validate client certificates, or a leaf certificate (`false`) presented
41 * by Cloudflare to your origin. Cannot be changed after upload — updating
42 * this property triggers a replacement.
43 */
44 ca: boolean;
45 /**
46 * The certificate in PEM format. A root CA certificate when `ca: true`,
47 * or a leaf certificate (chain) when `ca: false`. Cannot be changed after
48 * upload — updating this property triggers a replacement.
49 */
50 certificates: string;
51 /**
52 * The private key for the certificate in PEM format. Required when
53 * uploading a leaf certificate (`ca: false`) that Cloudflare must present
54 * to your origin. Cannot be changed after upload — updating this property
55 * triggers a replacement.
56 */
57 privateKey?: Redacted.Redacted<string>;
58 };
59
60 export type Attributes = {
61 /**
62 * Unique identifier of the uploaded certificate.
63 */
64 mtlsCertificateId: string;
65 /**
66 * The Cloudflare account the certificate was uploaded to.
67 */
68 accountId: string;
69 /**
70 * Human-readable name of the certificate.
71 */
72 name: string | undefined;
73 /**
74 * Whether the certificate is a CA (`true`) or leaf (`false`) certificate.
75 */
76 ca: boolean;
77 /**
78 * The certificate authority that issued the certificate.
79 */
80 issuer: string | undefined;
81 /**
82 * The certificate serial number.
83 */
84 serialNumber: string | undefined;
85 /**
86 * The type of hash used for the certificate signature.
87 */
88 signature: string | undefined;
89 /**
90 * When the certificate expires.
91 */
92 expiresOn: string | undefined;
93 /**
94 * When the certificate was uploaded to Cloudflare.
95 */
96 uploadedOn: string | undefined;
97 /**
98 * How the certificate was created and who manages it.
99 */
100 type: Type | undefined;
101 };
102
103 export type MtlsCertificate = Resource<TypeId, Props, Attributes, never, Providers>;
104
105 /**
106 * An account-level Cloudflare mTLS certificate.
107 *
108 * Uploads a certificate to the account-level mTLS certificate store. Upload a
109 * CA certificate (`ca: true`) to validate client certificates (referenced by
110 * certificate-authority hostname associations and Hyperdrive
111 * `caCertificateId`), or a leaf certificate plus private key (`ca: false`)
112 * that Cloudflare presents to your origin (referenced by Worker
113 * `mtls_certificate` bindings and Hyperdrive `mtlsCertificateId`).
114 *
115 * Certificates are immutable: there is no update API, so changing any
116 * property triggers a replacement.
117 * ### Uploading Certificates
118 * **Example:** CA certificate
119 * ```typescript
120 * const ca = yield* Cloudflare.MtlsCertificate.MtlsCertificate("client-ca", {
121 * ca: true,
122 * certificates: caPem,
123 * });
124 * ```
125 *
126 * **Example:** Leaf certificate with private key
127 * ```typescript
128 * const cert = yield* Cloudflare.MtlsCertificate.MtlsCertificate("origin-client-cert", {
129 * ca: false,
130 * certificates: leafPem,
131 * privateKey: yield* Config.Redacted("ORIGIN_CLIENT_KEY"),
132 * });
133 * ```
134 *
135 * **Example:** Named certificate
136 * ```typescript
137 * const ca = yield* Cloudflare.MtlsCertificate.MtlsCertificate("client-ca", {
138 * name: "my-client-ca",
139 * ca: true,
140 * certificates: caPem,
141 * });
142 * ```
143 *
144 * ### Referencing from Hyperdrive
145 * **Example:** Verify the origin with an uploaded CA
146 * ```typescript
147 * const ca = yield* Cloudflare.MtlsCertificate.MtlsCertificate("db-ca", {
148 * ca: true,
149 * certificates: caPem,
150 * });
151 *
152 * const hd = yield* Cloudflare.Hyperdrive.Connection("my-db", {
153 * origin: { ... },
154 * mtls: {
155 * caCertificateId: ca.mtlsCertificateId,
156 * sslmode: "verify-full",
157 * },
158 * });
159 * ```
160 *
161 * ### Binding to a Worker
162 * **Example:** Present a leaf certificate on subrequests
163 * ```typescript
164 * const cert = yield* Cloudflare.MtlsCertificate.MtlsCertificate("origin-client-cert", {
165 * ca: false,
166 * certificates: leafPem,
167 * privateKey: yield* Config.Redacted("ORIGIN_CLIENT_KEY"),
168 * });
169 *
170 * // `env.ORIGIN_CERT` is a `Fetcher`: `env.ORIGIN_CERT.fetch(url)` presents
171 * // the certificate to the origin.
172 * const worker = yield* Cloudflare.Worker("Worker", {
173 * main: "./src/worker.ts",
174 * env: { ORIGIN_CERT: cert },
175 * });
176 * ```
177 *
178 * **Example:** Present a leaf certificate from an Effect Worker
179 * ```typescript
180 * // Inside the Worker's Effect; provide `Cloudflare.MtlsCertificate.FetchBinding`.
181 * const fetchOrigin = yield* Cloudflare.MtlsCertificate.Fetch(cert);
182 * const response = yield* fetchOrigin(
183 * HttpClientRequest.get("https://origin.example.com/"),
184 * );
185 * ```
186 *
187 * @see https://developers.cloudflare.com/ssl/client-certificates/
188 *
189 * @resource
190 * @product mTLS Certificates
191 * @category SSL/TLS & Certificates
192 */
193 export const MtlsCertificate = Resource<MtlsCertificate>(TypeId, {
194 aliases: ["Cloudflare.MtlsCertificate"],
195 });
196
197 /**
198 * Returns true if the given value is a MtlsCertificate resource.
199 */
200 export const isMtlsCertificate = (value: unknown): value is MtlsCertificate =>
201 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
202
203 export const MtlsCertificateProvider = () =>
204 Provider.succeed(MtlsCertificate, {
205 stables: ["mtlsCertificateId", "accountId"],
206 diff: Effect.fn(function* ({ id, olds, news, output }) {
207 const { accountId } = yield* yield* CloudflareEnvironment;
208 if (!isResolved(news)) return undefined;
209 if ((output?.accountId ?? accountId) !== accountId) {
210 return { action: "replace" } as const;
211 }
212 const oldName = output?.name ?? (yield* createCertificateName(id, olds.name));
213 // Auto-generated names are engine-owned: the deployed name stays
214 // authoritative even if the generator would name this id differently
215 // today. Only an explicit user-provided name can force a replace.
216 const name = news.name ?? oldName;
217 if (
218 oldName !== name ||
219 (news.ca ?? undefined) !== (olds.ca ?? undefined) ||
220 (news.certificates ?? undefined) !== (olds.certificates ?? undefined) ||
221 unwrap(news.privateKey) !== unwrap(olds.privateKey)
222 ) {
223 // There is no update API for mTLS certificates — every change is a
224 // replacement. Cloudflare rejects a duplicate name, so a replacement
225 // that keeps an explicit name must delete the old certificate first.
226 // Generated names include the instance id and replace create-first.
227 return {
228 action: "replace",
229 deleteFirst: news.name !== undefined && news.name === oldName,
230 } as const;
231 }
232 return undefined;
233 }),
234 read: Effect.fn(function* ({ id, output, olds }) {
235 const { accountId } = yield* yield* CloudflareEnvironment;
236 const acct = output?.accountId ?? accountId;
237 if (output?.mtlsCertificateId) {
238 return yield* mtls
239 .getMtlsCertificate({
240 accountId: acct,
241 mtlsCertificateId: output.mtlsCertificateId,
242 })
243 .pipe(
244 Effect.map((cert) => toAttributes(cert, acct)),
245 Effect.catchTag("CertificateNotFound", () => Effect.undefined),
246 );
247 }
248 // Cold read — recover by listing and matching on the deterministic
249 // physical name (the only brand available; certificates have no tags).
250 const name = yield* createCertificateName(id, olds?.name);
251 const match = yield* findByName(acct, name);
252 return match ? toAttributes(match, acct) : undefined;
253 }),
254 list: Effect.fn(function* () {
255 const { accountId } = yield* yield* CloudflareEnvironment;
256 // Account-scoped collection — exhaustively paginate the mTLS
257 // certificate store and hydrate each item into the read Attributes
258 // shape (the private key is write-only and never returned).
259 return yield* mtls.listMtlsCertificates.pages({ accountId }).pipe(
260 Stream.runCollect,
261 Effect.map((chunk) =>
262 Array.from(chunk).flatMap((page) =>
263 (page.result ?? [])
264 // Cloudflare-managed certificates (e.g. the gateway/access
265 // managed CAs) reject deletion with `Unauthorized`; only
266 // enumerate user-uploaded `custom` certificates for teardown.
267 .filter((cert) => cert.type !== "gateway_managed" && cert.type !== "access_managed")
268 .map((cert) => toAttributes(cert, accountId)),
269 ),
270 ),
271 );
272 }),
273 reconcile: Effect.fn(function* ({ id, news, output }) {
274 const { accountId } = yield* yield* CloudflareEnvironment;
275 const name = output?.name ?? (yield* createCertificateName(id, news.name));
276
277 // Observe — the certificate id is the stable identifier; fall through
278 // a CertificateNotFound to the list+name match so we recover from
279 // out-of-band deletes and partial state persistence. Without an id,
280 // only adopt a certificate that has the same name AND the desired PEM:
281 // a replacement under an explicit name must upload the new PEM, not
282 // adopt the old certificate it is replacing (names are not unique).
283 let observed = output?.mtlsCertificateId
284 ? yield* mtls
285 .getMtlsCertificate({
286 accountId,
287 mtlsCertificateId: output.mtlsCertificateId,
288 })
289 .pipe(Effect.catchTag("CertificateNotFound", () => Effect.undefined))
290 : yield* findByName(accountId, name, news.certificates);
291
292 // Ensure — upload if missing. Cloudflare rejects uploading a
293 // certificate with identical content twice (code 1471); tolerate the
294 // race (or an orphaned prior upload) by re-listing and adopting the
295 // certificate with identical PEM content.
296 if (!observed) {
297 observed = yield* mtls
298 .createMtlsCertificate({
299 accountId,
300 ca: news.ca,
301 certificates: news.certificates,
302 name,
303 privateKey: unwrap(news.privateKey),
304 })
305 .pipe(
306 Effect.catchTag("CertificateAlreadyExists", (originalError) =>
307 Effect.gen(function* () {
308 const match = yield* findByContent(accountId, news.certificates);
309 if (!match) return yield* originalError;
310 return match;
311 }),
312 ),
313 );
314 }
315
316 return toAttributes(observed, accountId, news);
317 }),
318 delete: Effect.fn(function* ({ output }) {
319 yield* mtls
320 .deleteMtlsCertificate({
321 accountId: output.accountId,
322 mtlsCertificateId: output.mtlsCertificateId,
323 })
324 .pipe(
325 Effect.catchTag(["CertificateNotFound", "CertificateAlreadyDeleted"], () => Effect.void),
326 // Cloudflare releases a Worker's `mtls_certificate` binding
327 // eventually: for a short while after the Worker is deleted the
328 // delete still fails with `CertificateInUse`, even though the
329 // certificate's association list is already empty. Treat it as a
330 // dependency violation and retry, bounded to about 45 seconds.
331 Effect.retry({
332 while: (e) => e._tag === "CertificateInUse",
333 schedule: Schedule.max([
334 Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("5 seconds")]),
335 Schedule.recurs(10),
336 ]),
337 }),
338 );
339 }),
340 });
341
342 const createCertificateName = (id: string, name: string | undefined) =>
343 Effect.gen(function* () {
344 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
345 });
346
347 const findByName = (accountId: string, name: string, certificates?: string) =>
348 Effect.gen(function* () {
349 const list = yield* mtls.listMtlsCertificates({ accountId });
350 return list.result.find(
351 (c) =>
352 c.name === name && (certificates === undefined || samePem(c.certificates, certificates)),
353 );
354 });
355
356 const findByContent = (accountId: string, certificates: string) =>
357 Effect.gen(function* () {
358 const list = yield* mtls.listMtlsCertificates({ accountId });
359 return list.result.find((c) => samePem(c.certificates, certificates));
360 });
361
362 const samePem = (observed: string | null | undefined, desired: string) =>
363 observed?.trim() === desired.trim();
364
365 const unwrap = (value: Redacted.Redacted<string> | undefined): string | undefined =>
366 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
367
368 type CertificateShape = {
369 id?: string | null;
370 ca?: boolean | null;
371 name?: string | null;
372 issuer?: string | null;
373 serialNumber?: string | null;
374 signature?: string | null;
375 expiresOn?: string | null;
376 uploadedOn?: string | null;
377 type?: Type | null;
378 };
379
380 const toAttributes = (cert: CertificateShape, accountId: string, news?: Props): Attributes => ({
381 mtlsCertificateId: cert.id!,
382 accountId,
383 name: cert.name ?? undefined,
384 ca: cert.ca ?? news?.ca ?? false,
385 issuer: cert.issuer ?? undefined,
386 serialNumber: cert.serialNumber ?? undefined,
387 signature: cert.signature ?? undefined,
388 expiresOn: cert.expiresOn ?? undefined,
389 uploadedOn: cert.uploadedOn ?? undefined,
390 type: cert.type ?? undefined,
391 });