The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Hetzner from "@distilled.cloud/hetzner"; |
| 2 | import type { GetCertificateResponseCertificate } from "@distilled.cloud/hetzner/certificates"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import { tagRecord } from "alchemy/Tags"; |
| 9 | import { arrayEqualsUnordered } from "alchemy/Util/equal"; |
| 10 | import * as Data from "effect/Data"; |
| 11 | import * as Duration from "effect/Duration"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import * as Schedule from "effect/Schedule"; |
| 14 | import * as Stream from "effect/Stream"; |
| 15 | import { waitForAction } from "./actions.ts"; |
| 16 | import { |
| 17 | alchemyStackSelector, |
| 18 | createInternalLabels, |
| 19 | diffLabels, |
| 20 | hasAlchemyLabels, |
| 21 | labelSelector, |
| 22 | stripInternalLabels, |
| 23 | toLabels, |
| 24 | } from "./Labels.ts"; |
| 25 | import type { Providers } from "./Providers.ts"; |
| 26 | |
| 27 | export type CertificateType = "uploaded" | "managed"; |
| 28 | |
| 29 | export type CertificateStatus = { |
| 30 | /** Let's Encrypt issuance state. `undefined` for uploaded Certificates. */ |
| 31 | issuance?: "pending" | "completed" | "failed" | (string & {}); |
| 32 | /** Let's Encrypt renewal state. `undefined` for uploaded Certificates. */ |
| 33 | renewal?: "scheduled" | "pending" | "failed" | "unavailable" | (string & {}); |
| 34 | /** Present when issuance or renewal is `failed`. */ |
| 35 | error?: { code?: string; message?: string }; |
| 36 | }; |
| 37 | |
| 38 | export type UploadedCertificateProps = { |
| 39 | /** |
| 40 | * Upload an existing PEM certificate and private key. You monitor |
| 41 | * expiry and handle renewal yourself. |
| 42 | * @default "uploaded" |
| 43 | */ |
| 44 | type?: "uploaded"; |
| 45 | /** |
| 46 | * Name of the Certificate. Must be unique per Hetzner project. If |
| 47 | * omitted, a unique name is generated from the stack, stage, and |
| 48 | * logical id. |
| 49 | */ |
| 50 | name?: string; |
| 51 | /** |
| 52 | * Certificate and chain in PEM format, in order so that each record |
| 53 | * directly certifies the one preceding. Changing it replaces the |
| 54 | * Certificate. |
| 55 | */ |
| 56 | certificate: string; |
| 57 | /** |
| 58 | * Certificate private key in PEM format. Never returned by the API |
| 59 | * and not stored in resource attributes. Changing it replaces the |
| 60 | * Certificate. |
| 61 | */ |
| 62 | privateKey: string; |
| 63 | /** |
| 64 | * User-defined labels (`key/value` pairs). Alchemy ownership labels |
| 65 | * are merged in automatically. |
| 66 | */ |
| 67 | labels?: Record<string, string>; |
| 68 | }; |
| 69 | |
| 70 | export type ManagedCertificateProps = { |
| 71 | /** |
| 72 | * Request a Let's Encrypt Certificate for `domainNames`. Only domains |
| 73 | * managed by Hetzner DNS are supported. Hetzner handles renewal. |
| 74 | */ |
| 75 | type: "managed"; |
| 76 | /** |
| 77 | * Name of the Certificate. Must be unique per Hetzner project. If |
| 78 | * omitted, a unique name is generated from the stack, stage, and |
| 79 | * logical id. |
| 80 | */ |
| 81 | name?: string; |
| 82 | /** |
| 83 | * Domains and subdomains that should be contained in the Certificate. |
| 84 | * Changing them replaces the Certificate. |
| 85 | */ |
| 86 | domainNames: string[]; |
| 87 | /** |
| 88 | * User-defined labels (`key/value` pairs). Alchemy ownership labels |
| 89 | * are merged in automatically. |
| 90 | */ |
| 91 | labels?: Record<string, string>; |
| 92 | }; |
| 93 | |
| 94 | export type CertificateProps = UploadedCertificateProps | ManagedCertificateProps; |
| 95 | |
| 96 | export type Certificate = Resource< |
| 97 | "Hetzner.Certificate", |
| 98 | CertificateProps, |
| 99 | { |
| 100 | /** Numeric Hetzner Certificate id. */ |
| 101 | id: number; |
| 102 | /** Name of the Certificate (unique per project). */ |
| 103 | name: string; |
| 104 | /** `uploaded` or `managed`. */ |
| 105 | type: CertificateType; |
| 106 | /** |
| 107 | * Certificate and chain in PEM format. `undefined` while a managed |
| 108 | * Certificate is still being issued. |
| 109 | */ |
| 110 | certificate: string | undefined; |
| 111 | /** SHA256 fingerprint of the Certificate. */ |
| 112 | fingerprint: string | undefined; |
| 113 | /** Domains and subdomains covered by the Certificate. */ |
| 114 | domainNames: string[]; |
| 115 | /** RFC3339 instant when the Certificate becomes valid. */ |
| 116 | notValidBefore: string | undefined; |
| 117 | /** RFC3339 instant when the Certificate stops being valid. */ |
| 118 | notValidAfter: string | undefined; |
| 119 | /** RFC3339 creation timestamp. */ |
| 120 | created: string; |
| 121 | /** User-defined labels (Alchemy ownership labels stripped). */ |
| 122 | labels: Record<string, string>; |
| 123 | /** Managed issuance/renewal status. `undefined` for uploaded Certificates. */ |
| 124 | status: CertificateStatus | undefined; |
| 125 | /** Resources currently using the Certificate. */ |
| 126 | usedBy: { id: number; type: string }[]; |
| 127 | }, |
| 128 | never, |
| 129 | Providers |
| 130 | >; |
| 131 | |
| 132 | /** |
| 133 | * A Hetzner Cloud TLS Certificate. Upload a PEM (`type: "uploaded"`, the |
| 134 | * default) or request a Let's Encrypt Certificate for domains in Hetzner |
| 135 | * DNS (`type: "managed"`). |
| 136 | * |
| 137 | * `name` and `labels` update in place. Changing the type, the uploaded |
| 138 | * PEM/key, or the managed domain list replaces the Certificate. |
| 139 | * |
| 140 | * @see https://docs.hetzner.cloud/reference/cloud#certificates |
| 141 | * |
| 142 | * ### Uploading a Certificate |
| 143 | * **Example:** Generated name |
| 144 | * ```typescript |
| 145 | * const cert = yield* Hetzner.Certificate("web", { |
| 146 | * certificate: pem, |
| 147 | * privateKey: key, |
| 148 | * }); |
| 149 | * ``` |
| 150 | * |
| 151 | * **Example:** Explicit name and labels |
| 152 | * ```typescript |
| 153 | * const cert = yield* Hetzner.Certificate("web", { |
| 154 | * name: "my-website-cert", |
| 155 | * certificate: pem, |
| 156 | * privateKey: key, |
| 157 | * labels: { env: "prod" }, |
| 158 | * }); |
| 159 | * ``` |
| 160 | * |
| 161 | * ### Managed Let's Encrypt |
| 162 | * **Example:** Issue for Hetzner DNS domains |
| 163 | * ```typescript |
| 164 | * const cert = yield* Hetzner.Certificate("le", { |
| 165 | * type: "managed", |
| 166 | * domainNames: ["example.com", "www.example.com"], |
| 167 | * }); |
| 168 | * ``` |
| 169 | * |
| 170 | * @resource |
| 171 | * @product Certificate |
| 172 | */ |
| 173 | export const Certificate = Resource<Certificate>("Hetzner.Certificate"); |
| 174 | |
| 175 | export class CertificateNotResolved extends Data.TaggedError("Hetzner.CertificateNotResolved")<{ |
| 176 | resourceName: string; |
| 177 | }> {} |
| 178 | |
| 179 | export class CertificateIssuancePending extends Data.TaggedError( |
| 180 | "Hetzner.CertificateIssuancePending", |
| 181 | )<{ |
| 182 | certificateId: number; |
| 183 | issuance: string; |
| 184 | }> {} |
| 185 | |
| 186 | export class CertificateIssuanceFailed extends Data.TaggedError( |
| 187 | "Hetzner.CertificateIssuanceFailed", |
| 188 | )<{ |
| 189 | certificateId: number; |
| 190 | code?: string; |
| 191 | message: string; |
| 192 | }> {} |
| 193 | |
| 194 | type CloudCertificate = GetCertificateResponseCertificate; |
| 195 | |
| 196 | const asType = (type: string | undefined): CertificateType => |
| 197 | type === "managed" ? "managed" : "uploaded"; |
| 198 | |
| 199 | const userLabels = ( |
| 200 | labels: Record<string, string | undefined> | null | undefined, |
| 201 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 202 | |
| 203 | const toStatus = (status: CloudCertificate["status"]): CertificateStatus | undefined => { |
| 204 | if (status == null) return undefined; |
| 205 | return { |
| 206 | issuance: status.issuance, |
| 207 | renewal: status.renewal, |
| 208 | error: |
| 209 | status.error == null ? undefined : { code: status.error.code, message: status.error.message }, |
| 210 | }; |
| 211 | }; |
| 212 | |
| 213 | const toAttrs = (cert: CloudCertificate): Certificate["Attributes"] => ({ |
| 214 | id: cert.id, |
| 215 | name: cert.name, |
| 216 | type: asType(cert.type), |
| 217 | certificate: cert.certificate ?? undefined, |
| 218 | fingerprint: cert.fingerprint ?? undefined, |
| 219 | domainNames: cert.domain_names, |
| 220 | notValidBefore: cert.not_valid_before ?? undefined, |
| 221 | notValidAfter: cert.not_valid_after ?? undefined, |
| 222 | created: cert.created, |
| 223 | labels: userLabels(cert.labels), |
| 224 | status: toStatus(cert.status), |
| 225 | usedBy: cert.used_by.map((item) => ({ id: item.id, type: item.type })), |
| 226 | }); |
| 227 | |
| 228 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 229 | Effect.succeed(name ?? existing ?? undefined).pipe( |
| 230 | Effect.flatMap((resolved) => |
| 231 | resolved !== undefined ? Effect.succeed(resolved) : createPhysicalName({ id, maxLength: 64 }), |
| 232 | ), |
| 233 | ); |
| 234 | |
| 235 | const normalizePem = (pem: string | undefined): string => (pem ?? "").replace(/\r\n/g, "\n").trim(); |
| 236 | |
| 237 | const getById = (id: number) => |
| 238 | Hetzner.certificates.getCertificate({ id }).pipe( |
| 239 | Effect.map(({ certificate }) => certificate), |
| 240 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 241 | ); |
| 242 | |
| 243 | const findByName = (name: string) => |
| 244 | Hetzner.certificates |
| 245 | .listCertificates({ name, per_page: 50 }) |
| 246 | .pipe(Effect.map(({ certificates }) => certificates.find((cert) => cert.name === name))); |
| 247 | |
| 248 | const findByLabels = (labels: Record<string, string>) => |
| 249 | Hetzner.certificates |
| 250 | .listCertificates({ |
| 251 | label_selector: labelSelector(labels), |
| 252 | per_page: 50, |
| 253 | }) |
| 254 | .pipe(Effect.map(({ certificates }) => certificates[0])); |
| 255 | |
| 256 | const observe = Effect.fn(function* (input: { id?: number; name?: string; logicalId: string }) { |
| 257 | if (input.id !== undefined) { |
| 258 | const byId = yield* getById(input.id); |
| 259 | if (byId !== undefined) return byId; |
| 260 | } |
| 261 | if (input.name !== undefined) { |
| 262 | const byName = yield* findByName(input.name); |
| 263 | if (byName !== undefined) return byName; |
| 264 | } |
| 265 | const internal = yield* createInternalLabels(input.logicalId); |
| 266 | return yield* findByLabels(internal); |
| 267 | }); |
| 268 | |
| 269 | const deleteById = (id: number) => |
| 270 | Hetzner.certificates |
| 271 | .deleteCertificate({ id }) |
| 272 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 273 | |
| 274 | const waitForManagedIssuance = (id: number) => |
| 275 | Hetzner.certificates.getCertificate({ id }).pipe( |
| 276 | Effect.flatMap(({ certificate }) => |
| 277 | Effect.gen(function* () { |
| 278 | const issuance = certificate.status?.issuance; |
| 279 | if (issuance === "failed") { |
| 280 | return yield* new CertificateIssuanceFailed({ |
| 281 | certificateId: id, |
| 282 | code: certificate.status?.error?.code, |
| 283 | message: certificate.status?.error?.message ?? "Certificate issuance failed", |
| 284 | }); |
| 285 | } |
| 286 | if (issuance !== undefined && issuance !== "completed") { |
| 287 | return yield* new CertificateIssuancePending({ |
| 288 | certificateId: id, |
| 289 | issuance, |
| 290 | }); |
| 291 | } |
| 292 | return certificate; |
| 293 | }), |
| 294 | ), |
| 295 | Effect.retry({ |
| 296 | while: (e) => |
| 297 | e._tag === "Hetzner.CertificateIssuancePending" || |
| 298 | e._tag === "NotFound" || |
| 299 | e._tag === "TooManyRequests" || |
| 300 | e._tag === "ServiceUnavailable" || |
| 301 | e._tag === "InternalServerError" || |
| 302 | e._tag === "BadGateway" || |
| 303 | e._tag === "GatewayTimeout", |
| 304 | times: 10, |
| 305 | schedule: Schedule.min([ |
| 306 | Schedule.exponential(Duration.millis(500), 1.5), |
| 307 | Schedule.spaced(Duration.seconds(5)), |
| 308 | ]), |
| 309 | }), |
| 310 | ); |
| 311 | |
| 312 | const ensureCreated = Effect.fn(function* ({ |
| 313 | name, |
| 314 | news, |
| 315 | desiredLabels, |
| 316 | }: { |
| 317 | name: string; |
| 318 | news: CertificateProps; |
| 319 | desiredLabels: Record<string, string>; |
| 320 | }) { |
| 321 | const created = |
| 322 | news.type === "managed" |
| 323 | ? yield* Hetzner.certificates |
| 324 | .createCertificate({ |
| 325 | name, |
| 326 | type: "managed", |
| 327 | domain_names: news.domainNames, |
| 328 | labels: desiredLabels, |
| 329 | }) |
| 330 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)) |
| 331 | : yield* Hetzner.certificates |
| 332 | .createCertificate({ |
| 333 | name, |
| 334 | type: "uploaded", |
| 335 | certificate: news.certificate, |
| 336 | private_key: news.privateKey, |
| 337 | labels: desiredLabels, |
| 338 | }) |
| 339 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 340 | |
| 341 | if (created === undefined) { |
| 342 | return undefined; |
| 343 | } |
| 344 | |
| 345 | const cleanup = deleteById(created.certificate.id); |
| 346 | if (created.action) { |
| 347 | yield* waitForAction(created.action).pipe(Effect.tapError(() => cleanup)); |
| 348 | } |
| 349 | if (asType(created.certificate.type) === "managed") { |
| 350 | return yield* waitForManagedIssuance(created.certificate.id).pipe( |
| 351 | Effect.tapError(() => cleanup), |
| 352 | ); |
| 353 | } |
| 354 | return created.certificate; |
| 355 | }); |
| 356 | |
| 357 | export const CertificateProvider = () => |
| 358 | Provider.succeed(Certificate, { |
| 359 | stables: [ |
| 360 | "id", |
| 361 | "type", |
| 362 | "fingerprint", |
| 363 | "certificate", |
| 364 | "domainNames", |
| 365 | "notValidBefore", |
| 366 | "notValidAfter", |
| 367 | "created", |
| 368 | ], |
| 369 | |
| 370 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 371 | if (!isResolved(news)) return undefined; |
| 372 | if (output === undefined) return undefined; |
| 373 | |
| 374 | const nextType = news.type ?? "uploaded"; |
| 375 | const previousName = olds?.name ?? output.name; |
| 376 | const nextName = news.name ?? previousName; |
| 377 | const deleteFirst = nextName === previousName; |
| 378 | |
| 379 | if (nextType !== output.type) { |
| 380 | return { action: "replace" as const, deleteFirst }; |
| 381 | } |
| 382 | |
| 383 | if (news.type === "managed") { |
| 384 | if (!arrayEqualsUnordered(news.domainNames, output.domainNames)) { |
| 385 | return { action: "replace" as const, deleteFirst }; |
| 386 | } |
| 387 | return undefined; |
| 388 | } |
| 389 | |
| 390 | const prevCert = olds !== undefined && olds.type !== "managed" ? olds.certificate : undefined; |
| 391 | const prevKey = olds !== undefined && olds.type !== "managed" ? olds.privateKey : undefined; |
| 392 | if ( |
| 393 | (prevCert !== undefined && normalizePem(news.certificate) !== normalizePem(prevCert)) || |
| 394 | (prevKey !== undefined && normalizePem(news.privateKey) !== normalizePem(prevKey)) |
| 395 | ) { |
| 396 | return { action: "replace" as const, deleteFirst }; |
| 397 | } |
| 398 | return undefined; |
| 399 | }), |
| 400 | |
| 401 | read: Effect.fn(function* ({ id, olds, output }) { |
| 402 | const name = yield* toName(id, olds?.name, output?.name); |
| 403 | const existing = yield* observe({ |
| 404 | id: output?.id, |
| 405 | name, |
| 406 | logicalId: id, |
| 407 | }); |
| 408 | if (existing === undefined) return undefined; |
| 409 | const attrs = toAttrs(existing); |
| 410 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 411 | }), |
| 412 | |
| 413 | list: () => |
| 414 | Hetzner.certificates.listCertificates |
| 415 | .items({ label_selector: alchemyStackSelector, per_page: 50 }) |
| 416 | .pipe( |
| 417 | Stream.runCollect, |
| 418 | Effect.map((chunk) => Array.from(chunk, toAttrs)), |
| 419 | ), |
| 420 | |
| 421 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 422 | const name = yield* toName(id, news.name, output?.name); |
| 423 | const desiredLabels = { |
| 424 | ...toLabels(news.labels), |
| 425 | ...(yield* createInternalLabels(id)), |
| 426 | }; |
| 427 | |
| 428 | let current = yield* observe({ |
| 429 | id: output?.id, |
| 430 | name, |
| 431 | logicalId: id, |
| 432 | }); |
| 433 | |
| 434 | if (current === undefined) { |
| 435 | const created = yield* ensureCreated({ |
| 436 | name, |
| 437 | news, |
| 438 | desiredLabels, |
| 439 | }); |
| 440 | current = |
| 441 | created ?? |
| 442 | (yield* observe({ |
| 443 | id: output?.id, |
| 444 | name, |
| 445 | logicalId: id, |
| 446 | })); |
| 447 | } |
| 448 | |
| 449 | if (current === undefined) { |
| 450 | return yield* new CertificateNotResolved({ resourceName: name }); |
| 451 | } |
| 452 | |
| 453 | if (asType(current.type) === "managed") { |
| 454 | const issuance = current.status?.issuance; |
| 455 | if (issuance === "pending") { |
| 456 | current = yield* waitForManagedIssuance(current.id); |
| 457 | } else if (issuance === "failed") { |
| 458 | return yield* new CertificateIssuanceFailed({ |
| 459 | certificateId: current.id, |
| 460 | code: current.status?.error?.code, |
| 461 | message: current.status?.error?.message ?? "Certificate issuance failed", |
| 462 | }); |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | const observedLabels = tagRecord(current.labels); |
| 467 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 468 | const nameChanged = current.name !== name; |
| 469 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 470 | if (nameChanged || labelsChanged) { |
| 471 | const updated = yield* Hetzner.certificates.updateCertificate({ |
| 472 | id: current.id, |
| 473 | name: nameChanged ? name : undefined, |
| 474 | labels: labelsChanged ? desiredLabels : undefined, |
| 475 | }); |
| 476 | current = updated.certificate; |
| 477 | } |
| 478 | |
| 479 | return toAttrs(current); |
| 480 | }), |
| 481 | |
| 482 | delete: Effect.fn(function* ({ output }) { |
| 483 | yield* deleteById(output.id); |
| 484 | }), |
| 485 | }); |