The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as keylessCertificates from "@distilled.cloud/cloudflare/keyless-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 Stream from "effect/Stream"; |
| 9 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { listAllZones } from "../Zone/lookup.ts"; |
| 12 | |
| 13 | const TypeId = "Cloudflare.KeylessCertificate.KeylessCertificate" as const; |
| 14 | type TypeId = typeof TypeId; |
| 15 | |
| 16 | /** |
| 17 | * How the certificate chain is bundled when the certificate is served. |
| 18 | * Create-only — Cloudflare has no API to change the bundle method after |
| 19 | * upload, so changing it triggers a replacement. |
| 20 | */ |
| 21 | export type BundleMethod = "ubiquitous" | "optimal" | "force"; |
| 22 | |
| 23 | /** |
| 24 | * Lifecycle status of a Keyless SSL configuration. |
| 25 | */ |
| 26 | export type Status = |
| 27 | | "active" |
| 28 | | "deleted" |
| 29 | // Keep the union open so new Cloudflare statuses aren't blocked by stale |
| 30 | // types. |
| 31 | | (string & {}); |
| 32 | |
| 33 | /** |
| 34 | * Configuration for reaching the key server through a Cloudflare Tunnel |
| 35 | * instead of over the public internet. |
| 36 | */ |
| 37 | export interface Tunnel { |
| 38 | /** |
| 39 | * Private IP of the key server inside the tunnel's virtual network. |
| 40 | */ |
| 41 | privateIp: string; |
| 42 | /** |
| 43 | * Identifier of the Cloudflare Tunnel virtual network the key server is |
| 44 | * reachable through (e.g. `VirtualNetwork.vnetId`). |
| 45 | */ |
| 46 | vnetId: string; |
| 47 | } |
| 48 | |
| 49 | export interface Props { |
| 50 | /** |
| 51 | * Zone the Keyless SSL certificate is uploaded to. Keyless SSL is a |
| 52 | * zone-level Enterprise feature. |
| 53 | * |
| 54 | * Immutable — moving a Keyless SSL configuration between zones triggers a |
| 55 | * replacement. |
| 56 | */ |
| 57 | zoneId: string; |
| 58 | /** |
| 59 | * The zone's SSL certificate (or certificate and intermediates) in PEM |
| 60 | * format. The private key never leaves your key server. |
| 61 | * |
| 62 | * Immutable — the PATCH API has no certificate field, so changing the |
| 63 | * certificate triggers a replacement. Plain `string` (not `string`) |
| 64 | * so it is statically comparable inside `diff`. |
| 65 | */ |
| 66 | certificate: string; |
| 67 | /** |
| 68 | * Hostname of the externally running gokeyless key server that holds the |
| 69 | * private key. Mutable — patched in place. |
| 70 | */ |
| 71 | host: string; |
| 72 | /** |
| 73 | * Port Cloudflare uses to communicate with the key server. Mutable — |
| 74 | * patched in place. |
| 75 | * @default 24008 |
| 76 | */ |
| 77 | port?: number; |
| 78 | /** |
| 79 | * Human readable name for the Keyless SSL configuration. If omitted, a |
| 80 | * deterministic name is generated from the app, stage, and logical ID. |
| 81 | * Mutable — patched in place. |
| 82 | * @default ${app}-${stage}-${id} |
| 83 | */ |
| 84 | name?: string; |
| 85 | /** |
| 86 | * How the certificate chain is bundled: `ubiquitous` (highest probability |
| 87 | * of broad trust), `optimal` (shortest chain, newest intermediates), or |
| 88 | * `force` (use the chain exactly as uploaded). |
| 89 | * |
| 90 | * Create-only — changing the bundle method triggers a replacement. |
| 91 | * @default "ubiquitous" |
| 92 | */ |
| 93 | bundleMethod?: BundleMethod; |
| 94 | /** |
| 95 | * Whether the Keyless SSL configuration is on or off. Mutable — patched in |
| 96 | * place. |
| 97 | * @default true |
| 98 | */ |
| 99 | enabled?: boolean; |
| 100 | /** |
| 101 | * Reach the key server through a Cloudflare Tunnel virtual network instead |
| 102 | * of the public internet. |
| 103 | * |
| 104 | * Adding or changing the tunnel is patched in place; removing a previously |
| 105 | * configured tunnel triggers a replacement (the PATCH API cannot clear it). |
| 106 | */ |
| 107 | tunnel?: Tunnel; |
| 108 | } |
| 109 | |
| 110 | export interface Attributes { |
| 111 | /** Cloudflare-assigned identifier of the Keyless SSL configuration. */ |
| 112 | keylessCertificateId: string; |
| 113 | /** Zone the Keyless SSL configuration belongs to. */ |
| 114 | zoneId: string; |
| 115 | /** Human readable name of the Keyless SSL configuration. */ |
| 116 | name: string; |
| 117 | /** Hostname of the key server holding the private key. */ |
| 118 | host: string; |
| 119 | /** Port Cloudflare uses to communicate with the key server. */ |
| 120 | port: number; |
| 121 | /** Whether the Keyless SSL configuration is on or off. */ |
| 122 | enabled: boolean; |
| 123 | /** Current lifecycle status of the Keyless SSL configuration. */ |
| 124 | status: Status; |
| 125 | /** Permissions the requesting token has on this Keyless SSL. */ |
| 126 | permissions: string[]; |
| 127 | /** ISO8601 timestamp the Keyless SSL configuration was created. */ |
| 128 | createdOn: string; |
| 129 | /** ISO8601 timestamp the Keyless SSL configuration was last modified. */ |
| 130 | modifiedOn: string; |
| 131 | /** Tunnel configuration, when the key server is reached through a Cloudflare Tunnel. */ |
| 132 | tunnel: { privateIp: string; vnetId: string } | undefined; |
| 133 | } |
| 134 | |
| 135 | export type KeylessCertificate = Resource<TypeId, Props, Attributes, never, Providers>; |
| 136 | |
| 137 | /** |
| 138 | * A zone-level Keyless SSL configuration — serve TLS for a certificate whose |
| 139 | * private key stays on your own key server instead of being uploaded to |
| 140 | * Cloudflare. |
| 141 | * |
| 142 | * You upload only the certificate (and intermediates); Cloudflare reaches out |
| 143 | * to an externally running [gokeyless](https://github.com/cloudflare/gokeyless) |
| 144 | * key server at `host:port` (optionally through a Cloudflare Tunnel) for every |
| 145 | * private-key operation. |
| 146 | * |
| 147 | * Keyless SSL is an **Enterprise-only** feature: on zones without the |
| 148 | * entitlement, creation fails with the typed `KeylessSslNotAvailable` error |
| 149 | * (Cloudflare code 1067). |
| 150 | * |
| 151 | * `host`, `port`, `name`, `enabled`, and `tunnel` are mutable in place; |
| 152 | * `certificate` and `bundleMethod` are create-only and trigger a replacement. |
| 153 | * ### Creating a Keyless SSL configuration |
| 154 | * **Example:** Basic key server over the public internet |
| 155 | * ```typescript |
| 156 | * const keyless = yield* Cloudflare.KeylessCertificate.KeylessCertificate("SiteKeyless", { |
| 157 | * zoneId: zone.zoneId, |
| 158 | * certificate: certPem, // PEM, private key stays on your key server |
| 159 | * host: "keyless.example.com", |
| 160 | * port: 24008, |
| 161 | * }); |
| 162 | * ``` |
| 163 | * |
| 164 | * **Example:** Read the certificate from disk |
| 165 | * ```typescript |
| 166 | * const fs = yield* FileSystem.FileSystem; |
| 167 | * const certificate = yield* fs.readFileString("certs/site.pem"); |
| 168 | * |
| 169 | * const keyless = yield* Cloudflare.KeylessCertificate.KeylessCertificate("SiteKeyless", { |
| 170 | * zoneId: zone.zoneId, |
| 171 | * certificate, |
| 172 | * host: "keyless.example.com", |
| 173 | * }); |
| 174 | * ``` |
| 175 | * |
| 176 | * ### Reaching the key server through a Cloudflare Tunnel |
| 177 | * **Example:** Private key server on a tunnel virtual network |
| 178 | * ```typescript |
| 179 | * const vnet = yield* Cloudflare.Tunnel.VirtualNetwork("KeylessVnet", {}); |
| 180 | * |
| 181 | * const keyless = yield* Cloudflare.KeylessCertificate.KeylessCertificate("SiteKeyless", { |
| 182 | * zoneId: zone.zoneId, |
| 183 | * certificate: certPem, |
| 184 | * host: "keyless.internal", |
| 185 | * port: 24008, |
| 186 | * tunnel: { |
| 187 | * privateIp: "10.0.0.10", |
| 188 | * vnetId: vnet.vnetId, |
| 189 | * }, |
| 190 | * }); |
| 191 | * ``` |
| 192 | * |
| 193 | * ### Rotation |
| 194 | * **Example:** Rotate by changing the certificate |
| 195 | * ```typescript |
| 196 | * // `certificate` is create-only — changing it replaces the configuration: |
| 197 | * // the new one is created and the old one is deleted. |
| 198 | * const keyless = yield* Cloudflare.KeylessCertificate.KeylessCertificate("SiteKeyless", { |
| 199 | * zoneId: zone.zoneId, |
| 200 | * certificate: rotatedCertPem, |
| 201 | * host: "keyless.example.com", |
| 202 | * }); |
| 203 | * ``` |
| 204 | * |
| 205 | * @see https://developers.cloudflare.com/ssl/keyless-ssl/ |
| 206 | * |
| 207 | * @resource |
| 208 | * @product Keyless Certificates |
| 209 | * @category SSL/TLS & Certificates |
| 210 | */ |
| 211 | export const KeylessCertificate = Resource<KeylessCertificate>(TypeId, { |
| 212 | aliases: ["Cloudflare.KeylessCertificate"], |
| 213 | }); |
| 214 | |
| 215 | /** |
| 216 | * Returns true if the given value is a KeylessCertificate resource. |
| 217 | */ |
| 218 | export const isKeylessCertificate = (value: unknown): value is KeylessCertificate => |
| 219 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 220 | |
| 221 | export const KeylessCertificateProvider = () => |
| 222 | Provider.succeed(KeylessCertificate, { |
| 223 | stables: ["keylessCertificateId", "zoneId", "createdOn"], |
| 224 | |
| 225 | // Keyless SSL is zone-scoped (`/zones/{id}/keyless_certificates`) with no |
| 226 | // account-wide enumeration API. Fan out over every zone in the account, |
| 227 | // list its Keyless SSL configurations, and hydrate each into the exact |
| 228 | // `read` Attributes shape. Zones without the Enterprise entitlement reject |
| 229 | // the route with the typed `Forbidden` error — skip them. |
| 230 | list: Effect.fn(function* () { |
| 231 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 232 | const zones = yield* listAllZones(accountId); |
| 233 | const rows = yield* Effect.forEach( |
| 234 | zones, |
| 235 | (zone) => |
| 236 | keylessCertificates.listKeylessCertificates.pages({ zoneId: zone.id }).pipe( |
| 237 | Stream.runCollect, |
| 238 | Effect.map((chunk) => |
| 239 | Array.from(chunk).flatMap((page) => |
| 240 | (page.result ?? []) |
| 241 | .filter((keyless) => keyless.status !== "deleted") |
| 242 | .map((keyless) => |
| 243 | toAttributes({ ...keyless, permissions: [...keyless.permissions] }, zone.id), |
| 244 | ), |
| 245 | ), |
| 246 | ), |
| 247 | // Non-entitled / plan-gated zones reject Keyless SSL listing. |
| 248 | Effect.catchTag("Forbidden", () => Effect.succeed([])), |
| 249 | ), |
| 250 | { concurrency: 10 }, |
| 251 | ); |
| 252 | return rows.flat(); |
| 253 | }), |
| 254 | |
| 255 | diff: Effect.fn(function* ({ olds, news }) { |
| 256 | // diff runs during plan — `news` may still contain unresolved Outputs. |
| 257 | if (!isResolved(news)) return undefined; |
| 258 | // No prior props to compare against — let the engine decide. |
| 259 | if (olds?.certificate === undefined) return undefined; |
| 260 | // The PATCH API has no certificate field — rotation replaces. |
| 261 | if (normalizePem(olds.certificate) !== normalizePem(news.certificate)) { |
| 262 | return { action: "replace" } as const; |
| 263 | } |
| 264 | // bundleMethod is create-only. |
| 265 | if ((olds.bundleMethod ?? "ubiquitous") !== (news.bundleMethod ?? "ubiquitous")) { |
| 266 | return { action: "replace" } as const; |
| 267 | } |
| 268 | // The PATCH API can set a tunnel but cannot clear one — removing it |
| 269 | // requires a replacement. (Adding/changing is an in-place update.) |
| 270 | if (olds.tunnel !== undefined && news.tunnel === undefined) { |
| 271 | return { action: "replace" } as const; |
| 272 | } |
| 273 | // zoneId is Input<string>; compare only once both are concrete. |
| 274 | if ( |
| 275 | typeof olds.zoneId === "string" && |
| 276 | typeof news.zoneId === "string" && |
| 277 | olds.zoneId !== news.zoneId |
| 278 | ) { |
| 279 | return { action: "replace" } as const; |
| 280 | } |
| 281 | return undefined; |
| 282 | }), |
| 283 | |
| 284 | read: Effect.fn(function* ({ id, output, olds }) { |
| 285 | const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined); |
| 286 | if (zoneId === undefined) return undefined; |
| 287 | |
| 288 | // Owned path: refresh by our persisted identifier. Cloudflare keeps a |
| 289 | // tombstone with status "deleted" for a while — report it as gone. |
| 290 | if (output?.keylessCertificateId) { |
| 291 | const observed = yield* getKeylessCertificate(zoneId, output.keylessCertificateId); |
| 292 | return observed ? toAttributes(observed, zoneId) : undefined; |
| 293 | } |
| 294 | |
| 295 | // Cold read — recover from lost state by matching the deterministic |
| 296 | // physical name. Names are not unique on Cloudflare's side; an exact |
| 297 | // match on our generated/explicit name is the best identity we have. |
| 298 | const name = yield* createKeylessName(id, olds?.name); |
| 299 | const match = yield* findByName(zoneId, name); |
| 300 | return match ? toAttributes(match, zoneId) : undefined; |
| 301 | }), |
| 302 | |
| 303 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 304 | // Inputs have been resolved to concrete strings by Plan. |
| 305 | const zoneId = news.zoneId as string; |
| 306 | const name = yield* createKeylessName(id, news.name); |
| 307 | const desiredTunnel = resolveTunnel(news.tunnel); |
| 308 | |
| 309 | // 1. Observe — the identifier cached on `output` is a hint, not a |
| 310 | // guarantee: a missing (or tombstoned "deleted") configuration |
| 311 | // falls through to the name scan and then to create. |
| 312 | let observed = output?.keylessCertificateId |
| 313 | ? yield* getKeylessCertificate(zoneId, output.keylessCertificateId) |
| 314 | : undefined; |
| 315 | |
| 316 | // 2. Fall back to scanning the zone for a configuration carrying our |
| 317 | // deterministic physical name (recovers from lost state). |
| 318 | if (!observed) { |
| 319 | observed = yield* findByName(zoneId, name); |
| 320 | } |
| 321 | |
| 322 | // 3. Ensure — create when missing. Names are not unique on |
| 323 | // Cloudflare's side, so there is no AlreadyExists race to |
| 324 | // tolerate. On zones without the Enterprise entitlement this |
| 325 | // fails with the typed `KeylessSslNotAvailable` error. |
| 326 | if (!observed) { |
| 327 | observed = yield* keylessCertificates.createKeylessCertificate({ |
| 328 | zoneId, |
| 329 | certificate: news.certificate, |
| 330 | host: news.host, |
| 331 | port: news.port ?? 24008, |
| 332 | name, |
| 333 | bundleMethod: news.bundleMethod, |
| 334 | tunnel: desiredTunnel, |
| 335 | }); |
| 336 | } |
| 337 | |
| 338 | // 4. Sync — diff observed cloud state against desired and patch only |
| 339 | // when something actually differs; skip the call on a no-op. |
| 340 | // `enabled` is create-time defaulted by Cloudflare, so it is only |
| 341 | // compared when explicitly configured. |
| 342 | const desired = { |
| 343 | name, |
| 344 | host: news.host, |
| 345 | port: news.port ?? 24008, |
| 346 | }; |
| 347 | const dirty = |
| 348 | observed.name !== desired.name || |
| 349 | observed.host !== desired.host || |
| 350 | observed.port !== desired.port || |
| 351 | (news.enabled !== undefined && observed.enabled !== news.enabled) || |
| 352 | (desiredTunnel !== undefined && !sameTunnel(observed.tunnel ?? undefined, desiredTunnel)); |
| 353 | |
| 354 | if (dirty) { |
| 355 | observed = yield* keylessCertificates.patchKeylessCertificate({ |
| 356 | zoneId, |
| 357 | keylessCertificateId: observed.id, |
| 358 | ...desired, |
| 359 | enabled: news.enabled, |
| 360 | tunnel: desiredTunnel, |
| 361 | }); |
| 362 | } |
| 363 | |
| 364 | return toAttributes(observed, zoneId); |
| 365 | }), |
| 366 | |
| 367 | delete: Effect.fn(function* ({ output }) { |
| 368 | // Deleting an already-gone configuration answers with Cloudflare code |
| 369 | // 1005 ("Invalid or missing Keyless SSL") — convergence, not failure. |
| 370 | yield* keylessCertificates |
| 371 | .deleteKeylessCertificate({ |
| 372 | zoneId: output.zoneId, |
| 373 | keylessCertificateId: output.keylessCertificateId, |
| 374 | }) |
| 375 | .pipe(Effect.catchTag("KeylessCertificateNotFound", () => Effect.void)); |
| 376 | }), |
| 377 | }); |
| 378 | |
| 379 | // --------------------------------------------------------------------------- |
| 380 | // API helpers |
| 381 | // --------------------------------------------------------------------------- |
| 382 | |
| 383 | type ObservedKeyless = keylessCertificates.GetKeylessCertificateResponse; |
| 384 | |
| 385 | /** |
| 386 | * Read a Keyless SSL configuration by id, mapping "gone" |
| 387 | * (`KeylessCertificateNotFound`, Cloudflare error code 1005 "Invalid or |
| 388 | * missing Keyless SSL") and the "deleted" tombstone status to `undefined`. |
| 389 | */ |
| 390 | const getKeylessCertificate = (zoneId: string, keylessCertificateId: string) => |
| 391 | keylessCertificates.getKeylessCertificate({ zoneId, keylessCertificateId }).pipe( |
| 392 | Effect.map((observed): ObservedKeyless | undefined => |
| 393 | observed.status === "deleted" ? undefined : observed, |
| 394 | ), |
| 395 | Effect.catchTag("KeylessCertificateNotFound", () => Effect.undefined), |
| 396 | ); |
| 397 | |
| 398 | /** |
| 399 | * Find a non-deleted Keyless SSL configuration by exact name. Names are not |
| 400 | * unique on Cloudflare's side; if several carry the same name, pick the |
| 401 | * oldest for determinism. |
| 402 | */ |
| 403 | const findByName = (zoneId: string, name: string) => |
| 404 | keylessCertificates.listKeylessCertificates.items({ zoneId }).pipe( |
| 405 | Stream.filter((keyless) => keyless.name === name && keyless.status !== "deleted"), |
| 406 | Stream.runCollect, |
| 407 | Effect.map((chunk) => |
| 408 | Array.from(chunk) |
| 409 | .sort((a, b) => a.createdOn.localeCompare(b.createdOn)) |
| 410 | .at(0), |
| 411 | ), |
| 412 | Effect.map( |
| 413 | (keyless): ObservedKeyless | undefined => |
| 414 | keyless && { |
| 415 | ...keyless, |
| 416 | permissions: [...keyless.permissions], |
| 417 | }, |
| 418 | ), |
| 419 | ); |
| 420 | |
| 421 | const createKeylessName = (id: string, name: string | undefined) => |
| 422 | Effect.gen(function* () { |
| 423 | return name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 424 | }); |
| 425 | |
| 426 | /** Normalize PEM content for comparison (CRLF + trailing-newline noise). */ |
| 427 | const normalizePem = (pem: string): string => pem.replace(/\r\n/g, "\n").trim(); |
| 428 | |
| 429 | /** |
| 430 | * Resolve a tunnel prop to the concrete shape the API expects. Inputs have |
| 431 | * been resolved to concrete strings by Plan before reconcile runs. |
| 432 | */ |
| 433 | const resolveTunnel = ( |
| 434 | tunnel: Tunnel | undefined, |
| 435 | ): { privateIp: string; vnetId: string } | undefined => |
| 436 | tunnel === undefined |
| 437 | ? undefined |
| 438 | : { |
| 439 | privateIp: tunnel.privateIp as string, |
| 440 | vnetId: tunnel.vnetId as string, |
| 441 | }; |
| 442 | |
| 443 | const sameTunnel = ( |
| 444 | observed: { privateIp: string; vnetId: string } | undefined, |
| 445 | desired: { privateIp: string; vnetId: string }, |
| 446 | ): boolean => |
| 447 | observed !== undefined && |
| 448 | observed.privateIp === desired.privateIp && |
| 449 | observed.vnetId === desired.vnetId; |
| 450 | |
| 451 | const toAttributes = (keyless: ObservedKeyless, zoneId: string): Attributes => ({ |
| 452 | keylessCertificateId: keyless.id, |
| 453 | zoneId, |
| 454 | name: keyless.name, |
| 455 | host: keyless.host, |
| 456 | port: keyless.port, |
| 457 | enabled: keyless.enabled, |
| 458 | status: keyless.status as Status, |
| 459 | permissions: [...keyless.permissions], |
| 460 | createdOn: keyless.createdOn, |
| 461 | modifiedOn: keyless.modifiedOn, |
| 462 | tunnel: keyless.tunnel ?? undefined, |
| 463 | }); |