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

main
ts 311 lines 11.8 KB
Raw
1 import * as hostnames from "@distilled.cloud/cloudflare/hostnames";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11
12 const TypeId = "Cloudflare.HostnameTlsSetting.HostnameTlsSetting" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Which per-hostname TLS setting to override:
17 *
18 * - `ciphers` — allowed cipher suites (BoringSSL names) for the hostname
19 * - `min_tls_version` — minimum TLS protocol version for the hostname
20 * - `http2` — whether HTTP/2 is offered to clients connecting to the hostname
21 */
22 export type Id = "ciphers" | "min_tls_version" | "http2";
23
24 /**
25 * The value of a per-hostname TLS setting. The shape depends on
26 * {@link Id}:
27 *
28 * - `ciphers` → `string[]` of BoringSSL cipher suite names
29 * - `min_tls_version` → `"1.0" | "1.1" | "1.2" | "1.3"`
30 * - `http2` → `"on" | "off"`
31 */
32 export type Value = "1.0" | "1.1" | "1.2" | "1.3" | "on" | "off" | string[];
33
34 export interface Props {
35 /**
36 * Zone the hostname belongs to. Stable — moving the override to another
37 * zone triggers a replacement.
38 */
39 zoneId: string;
40 /**
41 * Which TLS setting to override (`ciphers`, `min_tls_version`, or
42 * `http2`). Part of the override's identity — changing it triggers a
43 * replacement.
44 */
45 settingId: Id;
46 /**
47 * The hostname the override applies to. Part of the override's identity —
48 * changing it triggers a replacement.
49 *
50 * Per-hostname TLS settings require the hostname to be covered by
51 * Cloudflare for SaaS custom hostnames or an Advanced Certificate
52 * Manager certificate on the zone; without that entitlement the API
53 * rejects writes with `AdvancedCertificateManagerRequired`.
54 */
55 hostname: string;
56 /**
57 * Desired value of the setting. The shape depends on `settingId`:
58 * `ciphers` takes a `string[]` of BoringSSL cipher names,
59 * `min_tls_version` takes `"1.0" | "1.1" | "1.2" | "1.3"`, and `http2`
60 * takes `"on" | "off"`.
61 *
62 * Mutable — upserted in place via PUT.
63 */
64 value: Value;
65 }
66
67 export interface Attributes {
68 /** Zone the hostname belongs to. */
69 zoneId: string;
70 /** The overridden TLS setting's identifier. */
71 settingId: string;
72 /** The hostname the override applies to. */
73 hostname: string;
74 /** Current value of the override. */
75 value: Value;
76 /**
77 * Deployment status of the override (e.g. `pending_deployment`,
78 * `active`). Propagation to the edge is asynchronous.
79 */
80 status: string | undefined;
81 /** When the override was first created, if Cloudflare reports it. */
82 createdAt: string | undefined;
83 /** When the override was last updated, if Cloudflare reports it. */
84 updatedAt: string | undefined;
85 }
86
87 export type HostnameTlsSetting = Resource<TypeId, Props, Attributes, never, Providers>;
88
89 /**
90 * A per-hostname TLS setting override
91 * (`/zones/{zone_id}/hostnames/settings/{settingId}/{hostname}`) — pins
92 * `ciphers`, `min_tls_version`, or `http2` for a single hostname instead of
93 * the whole zone.
94 *
95 * Each `(settingId, hostname)` pair is an independent override with PUT
96 * (upsert) / DELETE semantics; deleting the override reverts the hostname to
97 * the zone-wide default. Overrides are mostly useful with Cloudflare for
98 * SaaS custom hostnames or Advanced Certificate Manager — on zones without
99 * that entitlement, writes fail with the typed
100 * `AdvancedCertificateManagerRequired` error (Cloudflare code 1450).
101 *
102 * Safety: overrides carry no ownership markers. When there is no prior
103 * state, `read` scans the setting's hostname list and reports an existing
104 * override as `Unowned`, so the engine refuses to take it over unless
105 * `--adopt` (or `adopt(true)`) is set.
106 * ### Minimum TLS version
107 * **Example:** Require TLS 1.2 for a single hostname
108 * ```typescript
109 * yield* Cloudflare.HostnameTlsSetting.HostnameTlsSetting("ApiMinTls", {
110 * zoneId: zone.zoneId,
111 * settingId: "min_tls_version",
112 * hostname: "api.example.com",
113 * value: "1.2",
114 * });
115 * ```
116 *
117 * ### HTTP/2
118 * **Example:** Disable HTTP/2 for a legacy hostname
119 * ```typescript
120 * yield* Cloudflare.HostnameTlsSetting.HostnameTlsSetting("LegacyHttp2", {
121 * zoneId: zone.zoneId,
122 * settingId: "http2",
123 * hostname: "legacy.example.com",
124 * value: "off",
125 * });
126 * ```
127 *
128 * ### Cipher suites
129 * **Example:** Restrict a hostname to modern ciphers
130 * ```typescript
131 * yield* Cloudflare.HostnameTlsSetting.HostnameTlsSetting("StrictCiphers", {
132 * zoneId: zone.zoneId,
133 * settingId: "ciphers",
134 * hostname: "secure.example.com",
135 * value: ["ECDHE-RSA-AES128-GCM-SHA256", "AES128-GCM-SHA256"],
136 * });
137 * ```
138 *
139 * @see https://developers.cloudflare.com/ssl/edge-certificates/additional-options/custom-metadata/
140 * @see https://developers.cloudflare.com/api/resources/hostnames/subresources/settings/subresources/tls/
141 *
142 * @resource
143 * @product Hostname TLS Settings
144 * @category SSL/TLS & Certificates
145 */
146 export const HostnameTlsSetting = Resource<HostnameTlsSetting>(TypeId, {
147 aliases: ["Cloudflare.HostnameTlsSetting"],
148 });
149
150 /**
151 * Returns true if the given value is a HostnameTlsSetting resource.
152 */
153 export const isHostnameTlsSetting = (value: unknown): value is HostnameTlsSetting =>
154 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
155
156 export const HostnameTlsSettingProvider = () =>
157 Provider.succeed(HostnameTlsSetting, {
158 stables: ["zoneId", "settingId", "hostname", "createdAt"],
159
160 list: Effect.fn(function* () {
161 // Enumerate every override, including subdomains, through the zone's
162 // collection endpoint. The per-hostname GET returns 405 on live zones.
163 const { accountId } = yield* yield* CloudflareEnvironment;
164 const zones = yield* listAllZones(accountId);
165 const settingIds: Id[] = ["ciphers", "min_tls_version", "http2"];
166 const rows = yield* Effect.forEach(
167 zones,
168 (zone) =>
169 Effect.forEach(
170 settingIds,
171 (settingId) =>
172 hostnames
173 .listSettingsTls({ zoneId: zone.id, settingId })
174 .pipe(
175 Effect.map((settings) =>
176 settings.flatMap((setting) =>
177 setting.hostname == null
178 ? []
179 : [toAttributes(zone.id, settingId, setting.hostname, setting)],
180 ),
181 ),
182 ),
183 { concurrency: "unbounded" },
184 ).pipe(Effect.map((perSetting) => perSetting.flat())),
185 { concurrency: 10 },
186 );
187 return rows.flat();
188 }),
189
190 diff: Effect.fn(function* ({ olds, news, output }) {
191 // `news` may still carry unresolved plan-time expressions — defer to
192 // the engine's default update logic until everything is concrete.
193 if (!isResolved(news)) return undefined;
194 // (settingId, hostname) is the override's identity.
195 const oldSettingId = output?.settingId ?? olds?.settingId;
196 if (oldSettingId !== undefined && oldSettingId !== news.settingId) {
197 return { action: "replace" } as const;
198 }
199 const oldHostname = output?.hostname ?? olds?.hostname;
200 if (oldHostname !== undefined && oldHostname !== news.hostname) {
201 return { action: "replace" } as const;
202 }
203 // zoneId is Input<string>; compare only once both sides are concrete.
204 const oldZoneId =
205 output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
206 if (oldZoneId !== undefined && typeof news.zoneId === "string" && oldZoneId !== news.zoneId) {
207 return { action: "replace" } as const;
208 }
209 return undefined;
210 }),
211
212 read: Effect.fn(function* ({ output, olds }) {
213 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
214 const settingId = output?.settingId ?? olds?.settingId;
215 const hostname = output?.hostname ?? olds?.hostname;
216 if (!zoneId || !settingId || !hostname) return undefined;
217
218 const observed = yield* findSetting(zoneId, settingId, hostname);
219 if (observed === undefined) return undefined;
220
221 const attrs = toAttributes(zoneId, settingId, hostname, observed);
222 // Overrides carry no ownership markers — on a cold read (no prior
223 // state) we cannot prove we created it, so brand it `Unowned` and
224 // let the engine gate takeover behind the adopt policy.
225 return output !== undefined ? attrs : Unowned(attrs);
226 }),
227
228 reconcile: Effect.fn(function* ({ news }) {
229 // Inputs have been resolved to concrete strings by Plan.
230 const zoneId = news.zoneId as string;
231 const { settingId, hostname } = news;
232
233 // 1. Observe — list the setting's overrides and match on hostname.
234 const observed = yield* findSetting(zoneId, settingId, hostname);
235
236 // 2. Sync — PUT is a true upsert, so a single call covers both the
237 // missing and the drifted case; skip it entirely on a no-op.
238 if (observed !== undefined && valueEquals(observed.value, news.value)) {
239 return toAttributes(zoneId, settingId, hostname, observed);
240 }
241 const updated = yield* hostnames.putSettingTls({
242 zoneId,
243 settingId,
244 hostname,
245 value: news.value,
246 });
247 // The list can briefly echo a stale value after the PUT (edge
248 // deployment is async) — trust the PUT response, not a re-read.
249 return toAttributes(zoneId, settingId, hostname, updated);
250 }),
251
252 delete: Effect.fn(function* ({ output }) {
253 const { zoneId, settingId, hostname } = output;
254 // Observe first — deleting an already-removed override is not an
255 // error (idempotent re-delete after a crashed run).
256 const observed = yield* findSetting(zoneId, settingId, hostname);
257 if (observed === undefined) return;
258 yield* hostnames.deleteSettingTls({ zoneId, settingId, hostname }).pipe(
259 // Lost a race with an out-of-band delete — already converged.
260 Effect.catchTag("HostnameTlsSettingNotFound", () => Effect.void),
261 );
262 }),
263 });
264
265 // ---------------------------------------------------------------------------
266 // API helpers
267 // ---------------------------------------------------------------------------
268
269 type ObservedSetting = hostnames.ListSettingsTlsResponse[number];
270
271 const findSetting = (zoneId: string, settingId: string, hostname: string) =>
272 hostnames
273 .listSettingsTls({ zoneId, settingId })
274 .pipe(Effect.map((settings) => settings.find((setting) => setting.hostname === hostname)));
275
276 /**
277 * Structural equality for setting values — scalar versions/toggles compare
278 * by identity, cipher lists element-wise (order matters: the list is the
279 * client-facing preference order).
280 */
281 const valueEquals = (a: ObservedSetting["value"], b: Value): boolean => {
282 if (Array.isArray(a) || Array.isArray(b)) {
283 if (!Array.isArray(a) || !Array.isArray(b)) return false;
284 return a.length === b.length && a.every((v, i) => v === b[i]);
285 }
286 return a === b;
287 };
288
289 const toAttributes = (
290 zoneId: string,
291 settingId: string,
292 hostname: string,
293 setting: ObservedSetting | hostnames.PutSettingTlsResponse,
294 ): Attributes => ({
295 zoneId,
296 settingId,
297 hostname,
298 value: normalizeValue(setting.value),
299 status: setting.status ?? undefined,
300 createdAt: setting.createdAt ?? undefined,
301 updatedAt: setting.updatedAt ?? undefined,
302 });
303
304 /**
305 * Distilled types the echoed value as nullable and cipher arrays as
306 * `readonly string[]` — normalize to the props-facing shape. A persisted
307 * override always carries a value; fall back to `"off"` purely to satisfy
308 * the type.
309 */
310 const normalizeValue = (value: ObservedSetting["value"]): Value =>
311 value === null || value === undefined ? "off" : Array.isArray(value) ? [...value] : value;