The best way to control Claude Code, Codex and more from any computer or phone

main
ts 262 lines 9.58 KB
Raw
1 import * as originTls from "@distilled.cloud/cloudflare/origin-tls-client-auth";
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 type { Providers } from "../Providers.ts";
9
10 const TypeId = "Cloudflare.OriginTlsClientAuth.HostnameAssociation" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * Deployment status of the association or its pinned certificate. Changes
15 * propagate asynchronously (`pending_deployment` → `active`), typically
16 * settling within seconds.
17 */
18 export type HostnameAssociationStatus =
19 | "initializing"
20 | "pending_deployment"
21 | "pending_deletion"
22 | "active"
23 | "deleted"
24 | "deployment_timed_out"
25 | "deletion_timed_out"
26 // Keep the union open so new Cloudflare statuses aren't blocked by stale types.
27 | (string & {});
28
29 export type HostnameAssociationProps = {
30 /**
31 * Zone the hostname belongs to. Cannot be changed — updating this property
32 * triggers a replacement.
33 */
34 zoneId: string;
35 /**
36 * The hostname on the origin for which the client certificate will be
37 * presented. Must be a hostname of the zone. This is the association's
38 * identity — updating it triggers a replacement (the old hostname's
39 * association is voided).
40 */
41 hostname: string;
42 /**
43 * Identifier of the hostname client certificate
44 * ({@link HostnameCertificate}) presented to the origin
45 * for this hostname. Required by Cloudflare for every hostname AOP
46 * configuration. Mutable — updated in place.
47 */
48 certId: string;
49 /**
50 * Whether hostname-level Authenticated Origin Pulls is enabled for this
51 * hostname. Mutable — updated in place. On destroy the association is
52 * voided (Cloudflare's `enabled: null`), restoring the hostname to
53 * zone-level behavior.
54 */
55 enabled: boolean;
56 };
57
58 export type HostnameAssociationAttributes = {
59 /** Zone the hostname belongs to. */
60 zoneId: string;
61 /** The hostname the association applies to. */
62 hostname: string;
63 /** Identifier of the pinned hostname client certificate. */
64 certId: string;
65 /** Whether hostname-level Authenticated Origin Pulls is enabled. */
66 enabled: boolean;
67 /** Deployment status of the association. */
68 status: HostnameAssociationStatus | undefined;
69 /** Deployment status of the pinned certificate. */
70 certStatus: HostnameAssociationStatus | undefined;
71 };
72
73 export type HostnameAssociation = Resource<
74 TypeId,
75 HostnameAssociationProps,
76 HostnameAssociationAttributes,
77 never,
78 Providers
79 >;
80
81 /**
82 * A per-hostname Authenticated Origin Pulls (AOP) association
83 * (`/zones/{zone_id}/origin_tls_client_auth/hostnames`).
84 *
85 * Pins a hostname client certificate
86 * ({@link HostnameCertificate}) to a hostname and toggles
87 * hostname-level AOP for it. Cloudflare's API is a bulk upsert keyed by
88 * hostname; this resource manages exactly one hostname per instance, so
89 * separate instances for different hostnames are safe to deploy
90 * concurrently. On destroy the association is voided (`enabled: null`),
91 * which restores the hostname to zone-level AOP behavior.
92 * ### Enabling AOP for a hostname
93 * **Example:** Associate a hostname with a client certificate
94 * ```typescript
95 * const cert = yield* Cloudflare.OriginTlsClientAuth.HostnameCertificate("AopHostCert", {
96 * zoneId: zone.zoneId,
97 * certificate: clientCertPem,
98 * privateKey: yield* Config.Redacted("AOP_CLIENT_KEY"),
99 * });
100 *
101 * yield* Cloudflare.OriginTlsClientAuth.HostnameAssociation("AopHost", {
102 * zoneId: zone.zoneId,
103 * hostname: "api.example.com",
104 * certId: cert.certificateId,
105 * enabled: true,
106 * });
107 * ```
108 *
109 * **Example:** Keep the certificate pinned but disable enforcement
110 * ```typescript
111 * yield* Cloudflare.OriginTlsClientAuth.HostnameAssociation("AopHost", {
112 * zoneId: zone.zoneId,
113 * hostname: "api.example.com",
114 * certId: cert.certificateId,
115 * enabled: false,
116 * });
117 * ```
118 *
119 * @see https://developers.cloudflare.com/ssl/origin-configuration/authenticated-origin-pull/set-up/per-hostname/
120 *
121 * @resource
122 * @product Origin TLS Client Auth
123 * @category SSL/TLS & Certificates
124 */
125 export const HostnameAssociation = Resource<HostnameAssociation>(TypeId);
126
127 /**
128 * Returns true if the given value is an HostnameAssociation
129 * resource.
130 */
131 export const isHostnameAssociation = (value: unknown): value is HostnameAssociation =>
132 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
133
134 export const HostnameAssociationProvider = () =>
135 Provider.succeed(HostnameAssociation, {
136 stables: ["zoneId", "hostname"],
137
138 // Non-listable: an association is keyed entirely by {zoneId, hostname}
139 // and the only read op is `getHostname({ zoneId, hostname })`. Cloudflare
140 // exposes no endpoint that enumerates which hostnames in a zone have an
141 // AOP association (`listHostnameCertificates` lists certificates, which
142 // carry no hostname), so there is provably no way to discover the
143 // hostnames to read. Return [] rather than throwing.
144 list: () => Effect.succeed<HostnameAssociationAttributes[]>([]),
145
146 diff: Effect.fn(function* ({ olds, news }) {
147 if (!isResolved(news)) return undefined;
148 // zoneId is Input<string>; compare only once both sides are concrete.
149 if (
150 typeof olds.zoneId === "string" &&
151 typeof news.zoneId === "string" &&
152 olds.zoneId !== news.zoneId
153 ) {
154 return { action: "replace" } as const;
155 }
156 // The hostname is the association's identity in Cloudflare's bulk
157 // upsert — changing it must void the old hostname's entry, so it is a
158 // replacement.
159 if (olds.hostname !== news.hostname) {
160 return { action: "replace" } as const;
161 }
162 return undefined;
163 }),
164
165 read: Effect.fn(function* ({ output, olds }) {
166 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
167 const hostname = output?.hostname ?? olds?.hostname;
168 if (!zoneId || !hostname) return undefined;
169 const observed = yield* observeAssociation(zoneId, hostname);
170 if (!observed) return undefined;
171 const attrs = toAttributes(observed, zoneId, hostname);
172 // Cold read (no prior output): an association for this hostname exists
173 // but carries no ownership markers, so we cannot prove we created it —
174 // brand it `Unowned` so the engine refuses to take it over unless
175 // `adopt` is set.
176 return output === undefined ? Unowned(attrs) : attrs;
177 }),
178
179 reconcile: Effect.fn(function* ({ news }) {
180 // Inputs have been resolved to concrete strings by Plan.
181 const zoneId = news.zoneId as string;
182 const certId = news.certId as string;
183 const hostname = news.hostname;
184
185 // 1. Observe — the hostname is the deterministic identity; a voided
186 // (`enabled: null`) or missing entry reads as absent.
187 const observed = yield* observeAssociation(zoneId, hostname);
188
189 // 2. Sync — the PUT is a true upsert; skip it when the observed entry
190 // already matches the desired certificate and enablement.
191 if (observed && observed.certId === certId && observed.enabled === news.enabled) {
192 return toAttributes(observed, zoneId, hostname);
193 }
194 const put = yield* originTls.putHostname({
195 zoneId,
196 config: [{ hostname, certId, enabled: news.enabled }],
197 });
198 const result = put.result.find((r) => r.hostname === hostname);
199
200 // 3. Return — propagation is asynchronous (`pending_deployment` →
201 // `active`); we do not block on activation.
202 return toAttributes(result ?? { certId, enabled: news.enabled }, zoneId, hostname);
203 }),
204
205 delete: Effect.fn(function* ({ output }) {
206 const { zoneId, hostname } = output;
207 // Observe first — voiding an already-voided / never-created hostname
208 // is a no-op, and the PUT needs the certificate id currently pinned to
209 // the association.
210 const observed = yield* observeAssociation(zoneId, hostname);
211 if (!observed) return;
212 yield* originTls
213 .putHostname({
214 zoneId,
215 // `enabled: null` voids the association; Cloudflare still requires
216 // the pinned certificate id in the payload.
217 config: [
218 {
219 hostname,
220 certId: observed.certId ?? output.certId,
221 enabled: null,
222 },
223 ],
224 })
225 .pipe(
226 // Code 1415: the pinned certificate was already deleted out from
227 // under the association, which Cloudflare rejects even for a void.
228 // The association is inert without its certificate — treat as done.
229 Effect.catchTag("InvalidHostnameConfig", () => Effect.void),
230 );
231 }),
232 });
233
234 // Observe a hostname's association, mapping "never configured" (HTTP 404 /
235 // code 1553) and "voided" (`enabled: null`) to `undefined`.
236 const observeAssociation = (zoneId: string, hostname: string) =>
237 originTls.getHostname({ zoneId, hostname }).pipe(
238 Effect.map((assoc) =>
239 assoc.enabled === null || assoc.enabled === undefined ? undefined : assoc,
240 ),
241 Effect.catchTag("HostnameAssociationNotFound", () => Effect.undefined),
242 );
243
244 type AssociationShape = {
245 certId?: string | null;
246 enabled?: boolean | null;
247 status?: string | null;
248 certStatus?: string | null;
249 };
250
251 const toAttributes = (
252 assoc: AssociationShape,
253 zoneId: string,
254 hostname: string,
255 ): HostnameAssociationAttributes => ({
256 zoneId,
257 hostname,
258 certId: assoc.certId!,
259 enabled: assoc.enabled ?? false,
260 status: assoc.status ?? undefined,
261 certStatus: assoc.certStatus ?? undefined,
262 });