@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 289 lines 10.7 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Predicate from "effect/Predicate";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 export class CertificateUnexpectedResponse extends Data.TaggedError(
15 "CertificateUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export type CertificateProps = {
22 /**
23 * Display name for the certificate. Used as a stable identifier so the
24 * provider can locate the certificate during adoption / state recovery.
25 * If omitted, a unique name is generated from the stack/stage/logical id.
26 *
27 * @default ${app}-${stage}-${id}
28 */
29 name?: string;
30 /**
31 * The CA certificate content (PEM). Client certificates presented to
32 * Access-protected applications must chain to this CA. The certificate
33 * body is immutable — changing it replaces the resource.
34 */
35 certificate: string;
36 /**
37 * The hostnames of the Access applications that will use this
38 * certificate for mTLS authentication.
39 *
40 * @default []
41 */
42 associatedHostnames?: string[];
43 };
44
45 export type Certificate = Resource<
46 "Cloudflare.Access.Certificate",
47 CertificateProps,
48 {
49 /** UUID of the certificate assigned by Cloudflare. */
50 certificateId: string;
51 /** Cloudflare account that owns the certificate. */
52 accountId: string;
53 /** Display name reported by Cloudflare. */
54 name: string;
55 /**
56 * The PEM content that was uploaded. Cloudflare never returns the
57 * certificate body, so the provider persists it to detect replacement.
58 */
59 certificate: string;
60 /** The MD5 fingerprint of the certificate, computed by Cloudflare. */
61 fingerprint: string | undefined;
62 /** Hostnames currently associated with the certificate. */
63 associatedHostnames: string[];
64 /** Expiration timestamp of the CA certificate. */
65 expiresOn: string | undefined;
66 },
67 never,
68 Providers
69 >;
70
71 /**
72 * A Cloudflare Zero Trust Access mTLS certificate. Uploads a CA certificate
73 * that Access uses to validate client certificates presented to protected
74 * applications on the associated hostnames.
75 *
76 * The certificate body is immutable — changing the PEM replaces the
77 * resource. The name and associated hostnames converge in place.
78 * ### Creating a Certificate
79 * **Example:** Upload a CA certificate
80 * ```typescript
81 * const ca = yield* Cloudflare.Access.Certificate("ClientCa", {
82 * certificate: CA_PEM, // -----BEGIN CERTIFICATE----- ...
83 * });
84 * ```
85 *
86 * **Example:** Certificate with associated hostnames
87 * ```typescript
88 * const ca = yield* Cloudflare.Access.Certificate("ClientCa", {
89 * name: "corp-client-ca",
90 * certificate: CA_PEM,
91 * associatedHostnames: ["app.example.com"],
92 * });
93 * ```
94 *
95 * ### Updating Hostnames
96 * **Example:** Associate more hostnames in place
97 * ```typescript
98 * const ca = yield* Cloudflare.Access.Certificate("ClientCa", {
99 * certificate: CA_PEM,
100 * associatedHostnames: ["app.example.com", "admin.example.com"],
101 * });
102 * ```
103 *
104 * @resource
105 * @product Access
106 * @category Cloudflare One (Zero Trust)
107 */
108 export const Certificate = Resource<Certificate>("Cloudflare.Access.Certificate");
109
110 export const isCertificate = (value: unknown): value is Certificate =>
111 Predicate.hasProperty(value, "Type") && value.Type === "Cloudflare.Access.Certificate";
112
113 export const CertificateProvider = () =>
114 Provider.succeed(Certificate, {
115 stables: ["certificateId", "accountId", "fingerprint"],
116 // Account-scoped collection (pattern b). Cloudflare never returns the
117 // certificate PEM body, so the persisted `certificate` field is empty for
118 // enumerated items — every other attribute matches the `read` shape.
119 list: Effect.fn(function* () {
120 const { accountId } = yield* yield* CloudflareEnvironment;
121 return yield* zeroTrust.listAccessCertificatesForAccount.pages({ accountId }).pipe(
122 Stream.runCollect,
123 Effect.map((chunk) =>
124 Array.from(chunk).flatMap((page) =>
125 (page.result ?? [])
126 .filter((c): c is ObservedCertificate & { id: string } => c.id != null)
127 .map((c) => toAttrs(c, accountId, "")),
128 ),
129 ),
130 );
131 }),
132 diff: Effect.fn(function* ({ news, output }) {
133 const { accountId } = yield* yield* CloudflareEnvironment;
134 if (!isResolved(news)) return undefined;
135 if ((output?.accountId ?? accountId) !== accountId) {
136 return { action: "replace" } as const;
137 }
138 // The certificate body is immutable on the Cloudflare API.
139 if (output && news.certificate !== output.certificate) {
140 return { action: "replace" } as const;
141 }
142 // name/associatedHostnames converge via PUT.
143 }),
144 read: Effect.fn(function* ({ id, output, olds }) {
145 const { accountId } = yield* yield* CloudflareEnvironment;
146 const acct = output?.accountId ?? accountId;
147 if (output?.certificateId) {
148 const direct = yield* zeroTrust
149 .getAccessCertificateForAccount({
150 accountId: acct,
151 certificateId: output.certificateId,
152 })
153 .pipe(Effect.catchTag("AccessCertificateNotFound", () => Effect.undefined));
154 if (direct && direct.id) {
155 return toAttrs(direct, acct, output.certificate);
156 }
157 }
158 // Cold lookup — the certificate body never comes back from the API,
159 // so recovery is only possible when we still know the uploaded PEM.
160 const pem = olds?.certificate ?? output?.certificate;
161 if (pem === undefined) return undefined;
162 const name = yield* createCertificateName(id, olds?.name ?? output?.name);
163 const existing = yield* findCertificateByName(acct, name);
164 if (!existing || !existing.id) return undefined;
165 return toAttrs(existing, acct, pem);
166 }),
167 reconcile: Effect.fn(function* ({ id, news, output }) {
168 const { accountId } = yield* yield* CloudflareEnvironment;
169 const acct = output?.accountId ?? accountId;
170 const name = yield* createCertificateName(id, news.name);
171 const desiredHostnames = news.associatedHostnames ?? [];
172
173 // Observe — prefer the cached id, fall back to a name lookup so we
174 // recover from out-of-band deletes and state-persistence failures.
175 let observed: ObservedCertificate | undefined;
176 if (output?.certificateId) {
177 observed = yield* zeroTrust
178 .getAccessCertificateForAccount({
179 accountId: acct,
180 certificateId: output.certificateId,
181 })
182 .pipe(Effect.catchTag("AccessCertificateNotFound", () => Effect.undefined));
183 }
184 if (!observed || !observed.id) {
185 observed = yield* findCertificateByName(acct, name);
186 }
187
188 // Ensure — upload the certificate when missing. Tolerate a same-named
189 // create race by re-observing.
190 if (!observed || !observed.id) {
191 const created = yield* zeroTrust
192 .createAccessCertificateForAccount({
193 accountId: acct,
194 name,
195 certificate: news.certificate,
196 associatedHostnames: desiredHostnames,
197 })
198 .pipe(
199 Effect.catch((err) =>
200 Effect.gen(function* () {
201 const existing = yield* findCertificateByName(acct, name);
202 if (existing && existing.id) return existing;
203 return yield* err;
204 }),
205 ),
206 );
207 if (!created.id) {
208 return yield* new CertificateUnexpectedResponse({
209 message: "Certificate: created certificate missing id",
210 });
211 }
212 return toAttrs(created, acct, news.certificate);
213 }
214
215 // Sync — converge name and associated hostnames via PUT only when the
216 // observed state differs from the desired state.
217 const observedHostnames = [...(observed.associatedHostnames ?? [])];
218 if (observed.name !== name || !sameMembers(observedHostnames, desiredHostnames)) {
219 const updated = yield* zeroTrust.updateAccessCertificateForAccount({
220 accountId: acct,
221 certificateId: observed.id,
222 name,
223 associatedHostnames: desiredHostnames,
224 });
225 observed = {
226 id: updated.id ?? observed.id,
227 name: updated.name ?? name,
228 fingerprint: updated.fingerprint ?? observed.fingerprint,
229 associatedHostnames: updated.associatedHostnames ?? desiredHostnames,
230 expiresOn: updated.expiresOn ?? observed.expiresOn,
231 };
232 }
233
234 return toAttrs(observed, acct, news.certificate);
235 }),
236 delete: Effect.fn(function* ({ output }) {
237 // The API refuses to delete a certificate that still has associated
238 // hostnames — disassociate first, tolerating an already-gone cert.
239 yield* zeroTrust
240 .updateAccessCertificateForAccount({
241 accountId: output.accountId,
242 certificateId: output.certificateId,
243 name: output.name,
244 associatedHostnames: [],
245 })
246 .pipe(Effect.catchTag("AccessCertificateNotFound", () => Effect.void));
247 yield* zeroTrust
248 .deleteAccessCertificateForAccount({
249 accountId: output.accountId,
250 certificateId: output.certificateId,
251 })
252 .pipe(Effect.catchTag("AccessCertificateNotFound", () => Effect.void));
253 }),
254 });
255
256 const createCertificateName = (id: string, name: string | undefined) =>
257 Effect.gen(function* () {
258 if (name) return name;
259 return yield* createPhysicalName({ id });
260 });
261
262 const findCertificateByName = (acct: string, name: string) =>
263 zeroTrust.listAccessCertificatesForAccount.items({ accountId: acct }).pipe(
264 Stream.filter((c): c is ObservedCertificate => c.name === name),
265 Stream.runHead,
266 Effect.map(Option.getOrUndefined),
267 Effect.orElseSucceed(() => undefined),
268 );
269
270 const sameMembers = (a: readonly string[], b: readonly string[]) =>
271 a.length === b.length && [...a].sort().join("\n") === [...b].sort().join("\n");
272
273 const toAttrs = (observed: ObservedCertificate, accountId: string, certificate: string) => ({
274 certificateId: observed.id!,
275 accountId,
276 name: observed.name ?? "",
277 certificate,
278 fingerprint: observed.fingerprint ?? undefined,
279 associatedHostnames: [...(observed.associatedHostnames ?? [])],
280 expiresOn: observed.expiresOn ?? undefined,
281 });
282
283 type ObservedCertificate = {
284 id?: string | null;
285 name?: string | null;
286 fingerprint?: string | null;
287 associatedHostnames?: string[] | null;
288 expiresOn?: string | null;
289 };