@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 306 lines 11.2 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { isResolved } from "alchemy/Diff";
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
12 const TypeId = "Cloudflare.Gateway.Certificate" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Deployment status of the certificate on Cloudflare's edge. Gateway TLS
17 * interception can use certificates in the `available` state.
18 */
19 export type CertificateBindingStatus =
20 | "pending_deployment"
21 | "available"
22 | "pending_deletion"
23 | "inactive"
24 | (string & {});
25
26 export interface CertificateProps {
27 /**
28 * Certificate validity period in days (range: 1–10,950 days / ~30
29 * years). Only settable at creation time — changing it triggers a
30 * replacement (a new certificate is generated).
31 *
32 * @default 1825
33 */
34 validityPeriodDays?: number;
35 /**
36 * Whether the certificate should be activated (deployed to Cloudflare's
37 * edge so Gateway TLS interception can use it). Activation typically
38 * completes within seconds; the provider waits (bounded) for the
39 * `available` binding status. Set `false` to keep or return the
40 * certificate to the `inactive` state.
41 *
42 * @default true
43 */
44 activate?: boolean;
45 }
46
47 export interface CertificateAttributes {
48 /** UUID of the certificate, assigned by Cloudflare. */
49 certificateId: string;
50 /** Cloudflare account that owns the certificate. */
51 accountId: string;
52 /** Edge deployment status (`available` means usable for interception). */
53 bindingStatus: CertificateBindingStatus | undefined;
54 /** The CA certificate PEM (read-only, generated by Cloudflare). */
55 certificate: string | undefined;
56 /** SHA256 fingerprint of the certificate. */
57 fingerprint: string | undefined;
58 /**
59 * Whether Gateway TLS interception currently uses this certificate.
60 * Configured via the Gateway configuration `certificate` setting, not
61 * on the certificate itself.
62 */
63 inUse: boolean | undefined;
64 /** Organization that issued the certificate. */
65 issuerOrg: string | undefined;
66 /** Certificate kind — Cloudflare-generated (`gateway_managed`) or BYO-PKI (`custom`). */
67 certificateType: string | undefined;
68 /** ISO8601 expiry timestamp. */
69 expiresOn: string | undefined;
70 /** ISO8601 creation timestamp. */
71 createdAt: string | undefined;
72 }
73
74 export type Certificate = Resource<
75 TypeId,
76 CertificateProps,
77 CertificateAttributes,
78 never,
79 Providers
80 >;
81
82 /**
83 * A Cloudflare Zero Trust Gateway certificate — a Cloudflare-generated CA
84 * used by Gateway to inspect TLS traffic (HTTPS filtering, antivirus
85 * scanning, browser isolation). The certificate body is generated by
86 * Cloudflare; you only choose the validity period and whether it is
87 * activated (deployed to the edge).
88 *
89 * To make Gateway actually intercept with this certificate, reference its
90 * `certificateId` from the Gateway configuration's `certificate` setting
91 * (see `Cloudflare.Gateway.Configuration`).
92 * ### Creating a Certificate
93 * **Example:** Activated certificate (default)
94 * ```typescript
95 * const cert = yield* Cloudflare.Gateway.Certificate("InspectionCa", {});
96 * // cert.bindingStatus === "available" once deployed to the edge
97 * ```
98 *
99 * **Example:** Short-lived, kept inactive
100 * ```typescript
101 * const cert = yield* Cloudflare.Gateway.Certificate("StagedCa", {
102 * validityPeriodDays: 365,
103 * activate: false,
104 * });
105 * ```
106 *
107 * ### Using the certificate for TLS interception
108 * **Example:** Wire into the Gateway configuration
109 * ```typescript
110 * const cert = yield* Cloudflare.Gateway.Certificate("InspectionCa", {});
111 * yield* Cloudflare.Gateway.Configuration("Gateway", {
112 * settings: {
113 * tlsDecrypt: { enabled: true },
114 * certificate: { id: cert.certificateId },
115 * },
116 * });
117 * ```
118 *
119 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/user-side-certificates/
120 *
121 * @resource
122 * @product Gateway
123 * @category Cloudflare One (Zero Trust)
124 */
125 export const Certificate = Resource<Certificate>(TypeId);
126
127 /**
128 * Returns true if the given value is a Certificate resource.
129 */
130 export const isCertificate = (value: unknown): value is Certificate =>
131 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
132
133 export const CertificateProvider = () =>
134 Provider.succeed(Certificate, {
135 stables: [
136 "certificateId",
137 "accountId",
138 "certificate",
139 "fingerprint",
140 "issuerOrg",
141 "certificateType",
142 "expiresOn",
143 "createdAt",
144 ],
145
146 diff: Effect.fn(function* ({ olds = {}, news, output }) {
147 const { accountId } = yield* yield* CloudflareEnvironment;
148 if (!isResolved(news)) return undefined;
149 if ((output?.accountId ?? accountId) !== accountId) {
150 return { action: "replace" } as const;
151 }
152 // The validity period is only settable at creation time.
153 const o = olds as CertificateProps;
154 if (
155 output !== undefined &&
156 (o.validityPeriodDays ?? 1825) !== (news.validityPeriodDays ?? 1825)
157 ) {
158 return { action: "replace" } as const;
159 }
160 return undefined;
161 }),
162
163 read: Effect.fn(function* ({ output }) {
164 const { accountId } = yield* yield* CloudflareEnvironment;
165 const acct = output?.accountId ?? accountId;
166 // Certificates carry no name or tags, so there is no cold lookup —
167 // without a cached id the resource is simply unknown.
168 if (!output?.certificateId) return undefined;
169 const observed = yield* getCertificate(acct, output.certificateId);
170 if (!observed) return undefined;
171 return toAttributes(observed, acct);
172 }),
173
174 // Account-scoped collection (pattern b): enumerate every Gateway
175 // certificate in the ambient account. The list response already carries
176 // the full certificate shape, so each row maps straight to the `read`
177 // Attributes — no per-item hydration is required.
178 list: Effect.fn(function* () {
179 const { accountId } = yield* yield* CloudflareEnvironment;
180 return yield* zeroTrust.listGatewayCertificates.pages({ accountId }).pipe(
181 Stream.runCollect,
182 Effect.map((chunk) =>
183 Array.from(chunk).flatMap((page) =>
184 (page.result ?? [])
185 .map((cert) => toAttributes(cert, accountId))
186 // A certificate bound to the Gateway config (the active
187 // inspection CA) can't be deactivated/deleted while in use
188 // (`GatewayCertificateInUse`), and account-wide teardown does
189 // not remove the singleton Gateway config — skip in-use certs.
190 .filter((cert) => !cert.inUse),
191 ),
192 ),
193 );
194 }),
195
196 reconcile: Effect.fn(function* ({ news, output }) {
197 const { accountId } = yield* yield* CloudflareEnvironment;
198
199 // 1. Observe — the cached id is a hint; a vanished certificate
200 // falls through to create.
201 let observed = output?.certificateId
202 ? yield* getCertificate(accountId, output.certificateId)
203 : undefined;
204
205 // 2. Ensure — generate the CA when missing. New certificates start
206 // out `inactive`.
207 if (!observed) {
208 observed = yield* zeroTrust.createGatewayCertificate({
209 accountId,
210 ...(news.validityPeriodDays !== undefined
211 ? { validityPeriodDays: news.validityPeriodDays }
212 : {}),
213 });
214 }
215 const certificateId = observed.id ?? "";
216
217 // 3. Sync — converge the activation state. Activation/deactivation
218 // transit through pending_deployment / pending_deletion, so poll
219 // (bounded) for the terminal status; in practice this settles in
220 // a few seconds.
221 const wantActive = news.activate ?? true;
222 const status = observed.bindingStatus ?? undefined;
223 if (wantActive && (status === undefined || status === "inactive")) {
224 yield* zeroTrust.activateGatewayCertificate({
225 accountId,
226 certificateId,
227 });
228 } else if (!wantActive && (status === "available" || status === "pending_deployment")) {
229 yield* zeroTrust.deactivateGatewayCertificate({
230 accountId,
231 certificateId,
232 });
233 }
234 const desired = wantActive ? "available" : "inactive";
235 const final = yield* waitForStatus(accountId, certificateId, desired);
236
237 return toAttributes(final ?? observed, accountId);
238 }),
239
240 delete: Effect.fn(function* ({ output }) {
241 const { accountId, certificateId } = output;
242 // Observe — a missing certificate means we're done.
243 const observed = yield* getCertificate(accountId, certificateId);
244 if (!observed) return;
245 // Active certificates cannot be deleted (GatewayCertificateInUse,
246 // Cloudflare code 2118) — deactivate first and wait (bounded) for
247 // the `inactive` state.
248 const status = observed.bindingStatus ?? undefined;
249 if (status === "available" || status === "pending_deployment") {
250 yield* zeroTrust
251 .deactivateGatewayCertificate({ accountId, certificateId })
252 .pipe(Effect.catchTag("GatewayCertificateNotFound", () => Effect.void));
253 yield* waitForStatus(accountId, certificateId, "inactive");
254 }
255 yield* zeroTrust
256 .deleteGatewayCertificate({ accountId, certificateId })
257 .pipe(Effect.catchTag("GatewayCertificateNotFound", () => Effect.void));
258 }),
259 });
260
261 type ObservedCertificate =
262 | zeroTrust.GetGatewayCertificateResponse
263 | zeroTrust.CreateGatewayCertificateResponse
264 | zeroTrust.DeactivateGatewayCertificateResponse
265 | zeroTrust.ListGatewayCertificatesResponse["result"][number];
266
267 /**
268 * Read a certificate by id, mapping "gone" (`GatewayCertificateNotFound`,
269 * Cloudflare error code 2027) to `undefined`.
270 */
271 const getCertificate = (accountId: string, certificateId: string) =>
272 zeroTrust.getGatewayCertificate({ accountId, certificateId }).pipe(
273 Effect.map((c): zeroTrust.GetGatewayCertificateResponse | undefined => c),
274 Effect.catchTag("GatewayCertificateNotFound", () => Effect.undefined),
275 );
276
277 /**
278 * Poll the certificate until it reaches the desired binding status.
279 * Bounded — returns the last observation (which may still be pending)
280 * rather than failing, so eventual consistency never wedges a deploy.
281 */
282 const waitForStatus = (
283 accountId: string,
284 certificateId: string,
285 desired: "available" | "inactive",
286 ) =>
287 getCertificate(accountId, certificateId).pipe(
288 Effect.repeat({
289 schedule: Schedule.spaced("3 seconds"),
290 until: (c) => c === undefined || c.bindingStatus === desired,
291 times: 10,
292 }),
293 );
294
295 const toAttributes = (cert: ObservedCertificate, accountId: string): CertificateAttributes => ({
296 certificateId: cert.id ?? "",
297 accountId,
298 bindingStatus: cert.bindingStatus ?? undefined,
299 certificate: cert.certificate ?? undefined,
300 fingerprint: cert.fingerprint ?? undefined,
301 inUse: cert.inUse ?? undefined,
302 issuerOrg: cert.issuerOrg ?? undefined,
303 certificateType: cert.type ?? undefined,
304 expiresOn: cert.expiresOn ?? undefined,
305 createdAt: cert.createdAt ?? undefined,
306 });