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
| 1 | import * as acm from "@distilled.cloud/aws/acm"; |
| 2 | import { Region as AwsRegion } from "@distilled.cloud/aws/Region"; |
| 3 | import * as route53 from "@distilled.cloud/aws/route-53"; |
| 4 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 5 | import type { DnsRecord } from "alchemy/DNS/Adapter"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 8 | import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Option from "effect/Option"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | import { findPublicHostedZoneId } from "../Route53/HostedZoneLookup.ts"; |
| 16 | |
| 17 | export class CertificateNotReady extends Data.TaggedError("CertificateNotReady")<{ |
| 18 | readonly message: string; |
| 19 | readonly cause?: unknown; |
| 20 | }> {} |
| 21 | |
| 22 | export class CertificateUnexpectedResponse extends Data.TaggedError( |
| 23 | "CertificateUnexpectedResponse", |
| 24 | )<{ |
| 25 | readonly message: string; |
| 26 | readonly cause?: unknown; |
| 27 | }> {} |
| 28 | |
| 29 | export class CertificateOperationFailed extends Data.TaggedError("CertificateOperationFailed")<{ |
| 30 | readonly message: string; |
| 31 | readonly cause?: unknown; |
| 32 | }> {} |
| 33 | |
| 34 | export interface CertificateProps { |
| 35 | /** |
| 36 | * Primary domain name for the certificate. |
| 37 | */ |
| 38 | domainName: string; |
| 39 | /** |
| 40 | * Additional domain names to include on the certificate. |
| 41 | */ |
| 42 | subjectAlternativeNames?: string[]; |
| 43 | /** |
| 44 | * Validation method for the certificate request. |
| 45 | * @default "DNS" |
| 46 | */ |
| 47 | validationMethod?: acm.ValidationMethod; |
| 48 | /** |
| 49 | * Route 53 hosted zone used to auto-create DNS validation records. |
| 50 | * |
| 51 | * With `validationMethod: "DNS"` the certificate provider upserts the |
| 52 | * validation records into this zone and waits for issuance. When |
| 53 | * omitted, the most specific PUBLIC hosted zone in the account |
| 54 | * containing `domainName` is inferred; if none matches, validation is |
| 55 | * left to the caller (external DNS) and the certificate is returned |
| 56 | * pending. |
| 57 | */ |
| 58 | hostedZoneId?: string; |
| 59 | /** |
| 60 | * Who publishes the DNS validation records (with `validationMethod: |
| 61 | * "DNS"`). |
| 62 | * |
| 63 | * - `"route53"` — the provider upserts them into Route 53 |
| 64 | * ({@link hostedZoneId}, or the inferred public zone) and waits for |
| 65 | * issuance. |
| 66 | * - `"external"` — the provider only waits until ACM has computed the |
| 67 | * records and returns the certificate `PENDING_VALIDATION` with |
| 68 | * `domainValidationOptions` filled in. Publish them yourself — e.g. |
| 69 | * through a DNS adapter with {@link validationRecordsOf} — and wait for |
| 70 | * issuance with `AWS.ACM.CertificateValidation`. This is what AWS |
| 71 | * composites do for a `domain.dns` outside Route 53. |
| 72 | * |
| 73 | * @default "route53" |
| 74 | */ |
| 75 | dnsValidation?: "route53" | "external"; |
| 76 | /** |
| 77 | * Requested key algorithm. |
| 78 | */ |
| 79 | keyAlgorithm?: acm.KeyAlgorithm; |
| 80 | /** |
| 81 | * Certificate transparency logging preference. |
| 82 | * |
| 83 | * Updated in place via `UpdateCertificateOptions`. Note that AWS no longer |
| 84 | * allows opting new public certificates out of CT logging. |
| 85 | */ |
| 86 | certificateTransparencyLoggingPreference?: "ENABLED" | "DISABLED" | undefined; |
| 87 | /** |
| 88 | * Whether the certificate's private key can be exported with |
| 89 | * `acm:ExportCertificate` (see the `ExportCertificate` binding). |
| 90 | * Exportable public certificates carry an additional charge. |
| 91 | * |
| 92 | * Exportability can only be chosen when the certificate is requested — |
| 93 | * ACM rejects `UpdateCertificateOptions` for it ("Export option for |
| 94 | * certificates cannot be updated") — so changing this on an existing |
| 95 | * certificate forces a replacement. |
| 96 | */ |
| 97 | export?: "ENABLED" | "DISABLED" | undefined; |
| 98 | /** |
| 99 | * AWS region to request the certificate in. |
| 100 | * |
| 101 | * Defaults to `us-east-1` (the region CloudFront viewer certificates must |
| 102 | * live in). Set this to the region of a regional consumer — e.g. an ALB |
| 103 | * HTTPS listener requires the certificate in the load balancer's own |
| 104 | * region. Changing the region replaces the certificate. |
| 105 | * @default "us-east-1" |
| 106 | */ |
| 107 | region?: string; |
| 108 | /** |
| 109 | * User-defined tags to apply to the certificate. |
| 110 | */ |
| 111 | tags?: Record<string, string>; |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Binding contract of {@link Certificate}: composites contribute additional |
| 116 | * subject alternative names without a circular input prop (e.g. a site |
| 117 | * attached to an `AWS.Website.Router` binds its hostnames onto the Router's |
| 118 | * certificate). ACM certificates are immutable — a change in the bound SAN |
| 119 | * set plans a REPLACEMENT (new certificate requested and validated first, |
| 120 | * consumers re-pointed, old certificate deleted last). |
| 121 | */ |
| 122 | export type CertificateBinding = { |
| 123 | /** |
| 124 | * Additional subject alternative names merged into the certificate's SAN |
| 125 | * set at reconcile time. |
| 126 | */ |
| 127 | subjectAlternativeNames?: string[]; |
| 128 | }; |
| 129 | |
| 130 | export interface Certificate extends Resource< |
| 131 | "AWS.ACM.Certificate", |
| 132 | CertificateProps, |
| 133 | { |
| 134 | /** |
| 135 | * ARN of the certificate. |
| 136 | */ |
| 137 | certificateArn: string; |
| 138 | /** |
| 139 | * Primary domain name of the certificate. |
| 140 | */ |
| 141 | domainName: string; |
| 142 | /** |
| 143 | * Additional subject alternative names on the certificate. |
| 144 | */ |
| 145 | subjectAlternativeNames: string[]; |
| 146 | /** |
| 147 | * Current ACM certificate status. |
| 148 | */ |
| 149 | status: acm.CertificateStatus | undefined; |
| 150 | /** |
| 151 | * ACM-managed domain validation details, including DNS validation records. |
| 152 | */ |
| 153 | domainValidationOptions: acm.DomainValidation[]; |
| 154 | /** |
| 155 | * Requested validation method. |
| 156 | */ |
| 157 | validationMethod: acm.ValidationMethod | undefined; |
| 158 | /** |
| 159 | * Requested key algorithm. |
| 160 | */ |
| 161 | keyAlgorithm: acm.KeyAlgorithm | undefined; |
| 162 | /** |
| 163 | * Route 53 hosted zone used for automatic DNS validation, when configured. |
| 164 | */ |
| 165 | hostedZoneId: string | undefined; |
| 166 | /** |
| 167 | * Certificate transparency logging preference currently on the certificate. |
| 168 | */ |
| 169 | certificateTransparencyLoggingPreference: |
| 170 | | acm.CertificateTransparencyLoggingPreference |
| 171 | | undefined; |
| 172 | /** |
| 173 | * Whether the certificate's private key is exportable. |
| 174 | */ |
| 175 | export: acm.CertificateExport | undefined; |
| 176 | /** |
| 177 | * Current tags on the certificate. |
| 178 | */ |
| 179 | tags: Record<string, string>; |
| 180 | /** |
| 181 | * Certificate issue timestamp, when issued. |
| 182 | */ |
| 183 | issuedAt: Date | undefined; |
| 184 | /** |
| 185 | * Certificate expiration timestamp, when issued. |
| 186 | */ |
| 187 | notAfter: Date | undefined; |
| 188 | }, |
| 189 | CertificateBinding, |
| 190 | Providers |
| 191 | > {} |
| 192 | |
| 193 | /** |
| 194 | * Effective SAN set: declared props plus bound SANs (see |
| 195 | * {@link CertificateBinding}), deduped. Tolerates both `{ sid, data }` rows |
| 196 | * (provider lifecycle) and bare binding payloads. |
| 197 | * @internal |
| 198 | */ |
| 199 | const resolveEffectiveSans = ( |
| 200 | declared: string[] | undefined, |
| 201 | bindings: ReadonlyArray<CertificateBinding | ResourceBinding<CertificateBinding>> | undefined, |
| 202 | ): string[] | undefined => { |
| 203 | const bound = (bindings ?? []).flatMap((binding) => |
| 204 | "data" in binding && binding.data !== undefined |
| 205 | ? ((binding as ResourceBinding<CertificateBinding>).data.subjectAlternativeNames ?? []) |
| 206 | : ((binding as CertificateBinding).subjectAlternativeNames ?? []), |
| 207 | ); |
| 208 | if (bound.length === 0) { |
| 209 | return declared; |
| 210 | } |
| 211 | return [...new Set([...(declared ?? []), ...bound])]; |
| 212 | }; |
| 213 | |
| 214 | /** |
| 215 | * ACM refused to issue the certificate because a CAA record on the domain |
| 216 | * does not authorize Amazon. Alchemy never writes CAA records itself — add |
| 217 | * the records named in the message at the zone apex and redeploy. |
| 218 | */ |
| 219 | export class CertificateCaaError extends Data.TaggedError("CertificateCaaError")<{ |
| 220 | readonly certificateArn: string; |
| 221 | readonly domainName: string; |
| 222 | }> { |
| 223 | override get message() { |
| 224 | return ( |
| 225 | `ACM could not issue ${this.certificateArn} for ${this.domainName}: a CAA record on the domain does not authorize Amazon (CAA_ERROR). ` + |
| 226 | `Add CAA records at the zone apex — \`0 issue "amazon.com"\` and \`0 issue "amazonaws.com"\` (plus the same with \`issuewild\` for wildcard names) — then redeploy.` |
| 227 | ); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * An ACM certificate for CloudFront and other AWS endpoints. |
| 233 | * |
| 234 | * `Certificate` requests an ACM certificate in `us-east-1`, which is the |
| 235 | * region required for CloudFront viewer certificates. With DNS validation, |
| 236 | * the provider creates or updates the Route 53 validation records |
| 237 | * (`hostedZoneId`, or the inferred public zone) and waits for the |
| 238 | * certificate to be issued. With `dnsValidation: "external"` the records |
| 239 | * are published elsewhere — e.g. through a DNS adapter — and |
| 240 | * `AWS.ACM.CertificateValidation` waits for issuance. |
| 241 | * ### Requesting Certificates |
| 242 | * **Example:** DNS-Validated Certificate |
| 243 | * ```typescript |
| 244 | * const cert = yield* Certificate("WebsiteCertificate", { |
| 245 | * domainName: "www.example.com", |
| 246 | * hostedZoneId: "Z1234567890", |
| 247 | * }); |
| 248 | * ``` |
| 249 | * |
| 250 | * **Example:** Certificate With SANs |
| 251 | * ```typescript |
| 252 | * const cert = yield* Certificate("WebsiteCertificate", { |
| 253 | * domainName: "example.com", |
| 254 | * subjectAlternativeNames: ["www.example.com"], |
| 255 | * hostedZoneId: "Z1234567890", |
| 256 | * }); |
| 257 | * ``` |
| 258 | * |
| 259 | * **Example:** Exportable Certificate |
| 260 | * ```typescript |
| 261 | * // `export: "ENABLED"` lets the ExportCertificate binding retrieve the |
| 262 | * // certificate together with its (encrypted) private key at runtime. |
| 263 | * const cert = yield* Certificate("ExportableCertificate", { |
| 264 | * domainName: "www.example.com", |
| 265 | * hostedZoneId: "Z1234567890", |
| 266 | * export: "ENABLED", |
| 267 | * }); |
| 268 | * ``` |
| 269 | * |
| 270 | * **Example:** Certificate Validated Through Another DNS Host |
| 271 | * ```typescript |
| 272 | * // DNS lives in Cloudflare: publish ACM's validation CNAMEs through the |
| 273 | * // Cloudflare DNS adapter, then wait for issuance. AWS composites do this |
| 274 | * // for you when `domain.dns` is set. |
| 275 | * const cert = yield* Certificate("WebsiteCertificate", { |
| 276 | * domainName: "www.example.com", |
| 277 | * dnsValidation: "external", |
| 278 | * }); |
| 279 | * const dns = yield* DNS.resolve(Cloudflare.DNS.Adapter()); |
| 280 | * yield* dns.records("WebsiteCertificateValidation", { |
| 281 | * records: cert.domainValidationOptions.pipe( |
| 282 | * Output.map(validationRecordsOf), |
| 283 | * ), |
| 284 | * retain: true, |
| 285 | * }); |
| 286 | * const issued = yield* CertificateValidation("WebsiteCertificateIssued", { |
| 287 | * certificateArn: cert.certificateArn, |
| 288 | * }); |
| 289 | * ``` |
| 290 | * |
| 291 | * ### Certificate Expiry Events |
| 292 | * **Example:** React to Approaching Expiration |
| 293 | * ```typescript |
| 294 | * // ACM emits "ACM Certificate Approaching Expiration" events through |
| 295 | * // EventBridge — consume them with the ACM expiry event source, scoped |
| 296 | * // to this certificate. |
| 297 | * yield* AWS.ACM.consumeExpiryEvents( |
| 298 | * { certificateArns: [cert.certificateArn] }, |
| 299 | * (events) => |
| 300 | * Stream.runForEach(events, (event) => |
| 301 | * Effect.log( |
| 302 | * `${event.detail.CommonName} expires in ${event.detail.DaysToExpiry} days`, |
| 303 | * ), |
| 304 | * ), |
| 305 | * ); |
| 306 | * ``` |
| 307 | * |
| 308 | * @resource |
| 309 | */ |
| 310 | export const Certificate = Resource<Certificate>("AWS.ACM.Certificate"); |
| 311 | |
| 312 | export const CertificateProvider = () => |
| 313 | Provider.effect( |
| 314 | Certificate, |
| 315 | Effect.gen(function* () { |
| 316 | const describeCertificate = Effect.fn(function* (certificateArn: string) { |
| 317 | return yield* acm.describeCertificate({ CertificateArn: certificateArn }).pipe( |
| 318 | Effect.map((response) => response.Certificate), |
| 319 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 320 | withCertRegion(regionOfCertificateArn(certificateArn)), |
| 321 | ); |
| 322 | }); |
| 323 | |
| 324 | const listCertificateTags = Effect.fn(function* (certificateArn: string) { |
| 325 | return yield* acm.listTagsForCertificate({ CertificateArn: certificateArn }).pipe( |
| 326 | Effect.map((response) => toTagRecord(response.Tags)), |
| 327 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})), |
| 328 | withCertRegion(regionOfCertificateArn(certificateArn)), |
| 329 | ); |
| 330 | }); |
| 331 | |
| 332 | const findManagedCertificate = Effect.fn(function* (id: string, props: CertificateProps) { |
| 333 | // Describe candidates lazily as pages stream in and stop at the first |
| 334 | // match, so pagination terminates early instead of draining every page. |
| 335 | return yield* withCertRegion(props.region)( |
| 336 | acm.listCertificates |
| 337 | .items({ |
| 338 | Includes: { |
| 339 | keyTypes: props.keyAlgorithm ? [props.keyAlgorithm] : undefined, |
| 340 | }, |
| 341 | } as any) |
| 342 | .pipe( |
| 343 | Stream.filter((summary) => summary.DomainName === props.domainName), |
| 344 | Stream.mapEffect((summary) => |
| 345 | Effect.gen(function* () { |
| 346 | if (!summary.CertificateArn) { |
| 347 | return undefined; |
| 348 | } |
| 349 | const detail = yield* describeCertificate(summary.CertificateArn); |
| 350 | if (!detail?.CertificateArn) { |
| 351 | return undefined; |
| 352 | } |
| 353 | if ( |
| 354 | detail.DomainName !== props.domainName || |
| 355 | JSON.stringify(normalizeSanList(detail.SubjectAlternativeNames)) !== |
| 356 | JSON.stringify(normalizeSanList(props.subjectAlternativeNames)) |
| 357 | ) { |
| 358 | return undefined; |
| 359 | } |
| 360 | // Exportability is fixed at request time, so a certificate |
| 361 | // with a different export option can never converge to these |
| 362 | // props — it is the doomed half of a replacement, not a |
| 363 | // match. |
| 364 | if ((props.export ?? "DISABLED") !== (detail.Options?.Export ?? "DISABLED")) { |
| 365 | return undefined; |
| 366 | } |
| 367 | const tags = yield* listCertificateTags(detail.CertificateArn); |
| 368 | return (yield* hasAlchemyTags(id, tags)) ? detail : undefined; |
| 369 | }), |
| 370 | ), |
| 371 | Stream.filter((detail) => detail !== undefined), |
| 372 | Stream.runHead, |
| 373 | Effect.map(Option.getOrUndefined), |
| 374 | ), |
| 375 | ); |
| 376 | }); |
| 377 | |
| 378 | const waitForValidationRecords = Effect.fn(function* (certificateArn: string) { |
| 379 | return yield* describeCertificate(certificateArn).pipe( |
| 380 | Effect.flatMap((detail) => { |
| 381 | const validations = detail?.DomainValidationOptions ?? []; |
| 382 | if ( |
| 383 | validations.length === 0 || |
| 384 | validations.some((option) => option.ResourceRecord === undefined) |
| 385 | ) { |
| 386 | return Effect.fail( |
| 387 | new CertificateNotReady({ message: "CertificateValidationRecordPending" }), |
| 388 | ); |
| 389 | } |
| 390 | return Effect.succeed(detail!); |
| 391 | }), |
| 392 | Effect.retry({ |
| 393 | while: (error) => |
| 394 | error._tag === "CertificateNotReady" && |
| 395 | error.message === "CertificateValidationRecordPending", |
| 396 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]), |
| 397 | }), |
| 398 | ); |
| 399 | }); |
| 400 | |
| 401 | const waitForIssued = (certificateArn: string) => waitForCertificateIssued(certificateArn); |
| 402 | |
| 403 | const upsertValidationRecords = Effect.fn(function* ( |
| 404 | hostedZoneId: string, |
| 405 | certificate: acm.CertificateDetail, |
| 406 | ) { |
| 407 | // A name and its wildcard (`example.com` + `*.example.com`) share one |
| 408 | // validation record. Route 53 rejects a batch that changes the same |
| 409 | // record twice, so keep one change per name and type. |
| 410 | const records = new Map( |
| 411 | (certificate.DomainValidationOptions ?? []) |
| 412 | .flatMap((option) => (option.ResourceRecord ? [option.ResourceRecord] : [])) |
| 413 | .map((record) => [`${record.Name} ${record.Type}`, record] as const), |
| 414 | ); |
| 415 | const changes = [...records.values()].map((record) => ({ |
| 416 | Action: "UPSERT" as const, |
| 417 | ResourceRecordSet: { |
| 418 | Name: record.Name, |
| 419 | Type: record.Type, |
| 420 | TTL: 60, |
| 421 | ResourceRecords: [{ Value: record.Value }], |
| 422 | }, |
| 423 | })); |
| 424 | |
| 425 | if (changes.length === 0) { |
| 426 | return; |
| 427 | } |
| 428 | |
| 429 | const response = yield* route53.changeResourceRecordSets({ |
| 430 | HostedZoneId: normalizeHostedZoneId(hostedZoneId), |
| 431 | ChangeBatch: { |
| 432 | Comment: "Alchemy ACM DNS validation", |
| 433 | Changes: changes, |
| 434 | }, |
| 435 | }); |
| 436 | |
| 437 | yield* waitForRoute53Change(response.ChangeInfo.Id); |
| 438 | }); |
| 439 | |
| 440 | return { |
| 441 | stables: ["certificateArn"], |
| 442 | list: () => |
| 443 | Effect.gen(function* () { |
| 444 | // ACM certificates default to us-east-1 (CloudFront), but a |
| 445 | // `region` prop can place them in the ambient region (e.g. for |
| 446 | // ALB listeners) — enumerate both and dedupe by ARN, then |
| 447 | // hydrate each to the full Attributes shape via describe + tags. |
| 448 | const listPage = acm.listCertificates.pages({}).pipe( |
| 449 | Stream.runCollect, |
| 450 | Effect.map((chunk) => |
| 451 | Array.from(chunk).flatMap((page) => page.CertificateSummaryList ?? []), |
| 452 | ), |
| 453 | ); |
| 454 | const summaries = [ |
| 455 | ...new Map( |
| 456 | [...(yield* withAcmRegion(listPage)), ...(yield* listPage)].map( |
| 457 | (summary) => [summary.CertificateArn, summary] as const, |
| 458 | ), |
| 459 | ).values(), |
| 460 | ]; |
| 461 | const rows = yield* Effect.forEach( |
| 462 | summaries, |
| 463 | (summary) => |
| 464 | Effect.gen(function* () { |
| 465 | if (!summary.CertificateArn) { |
| 466 | return undefined; |
| 467 | } |
| 468 | const detail = yield* describeCertificate(summary.CertificateArn); |
| 469 | if (!detail?.CertificateArn) { |
| 470 | return undefined; |
| 471 | } |
| 472 | const tags = yield* listCertificateTags(detail.CertificateArn); |
| 473 | return toAttrs( |
| 474 | { |
| 475 | domainName: detail.DomainName ?? "", |
| 476 | validationMethod: detail.DomainValidationOptions?.[0]?.ValidationMethod, |
| 477 | }, |
| 478 | detail, |
| 479 | tags, |
| 480 | ); |
| 481 | }), |
| 482 | { concurrency: 10 }, |
| 483 | ); |
| 484 | return rows.filter((row): row is ReturnType<typeof toAttrs> => row !== undefined); |
| 485 | }), |
| 486 | diff: Effect.fn(function* ({ olds, news: _news, oldBindings, newBindings: _newBindings }) { |
| 487 | if (!isResolved(_news) || !isResolved(_newBindings)) { |
| 488 | return undefined; |
| 489 | } |
| 490 | const news = _news as typeof olds; |
| 491 | const newBindings = _newBindings as ResourceBinding<CertificateBinding>[]; |
| 492 | if ( |
| 493 | olds.domainName !== news.domainName || |
| 494 | // ACM certificates are immutable: the SAN set — declared props |
| 495 | // plus SANs contributed through the binding contract — cannot |
| 496 | // change in place, so any delta plans a replacement. |
| 497 | !deepEqual( |
| 498 | normalizeSanList(resolveEffectiveSans(olds.subjectAlternativeNames, oldBindings)), |
| 499 | normalizeSanList(resolveEffectiveSans(news.subjectAlternativeNames, newBindings)), |
| 500 | ) || |
| 501 | (olds.validationMethod ?? defaultValidationMethod) !== |
| 502 | (news.validationMethod ?? defaultValidationMethod) || |
| 503 | // An undefined side means "inferred" — only two explicit, |
| 504 | // differing zones are a replacement. |
| 505 | (olds.hostedZoneId !== undefined && |
| 506 | news.hostedZoneId !== undefined && |
| 507 | olds.hostedZoneId !== news.hostedZoneId) || |
| 508 | olds.keyAlgorithm !== news.keyAlgorithm || |
| 509 | // Certificates cannot move regions — a region change replaces. |
| 510 | (olds.region ?? ACM_REGION) !== (news.region ?? ACM_REGION) || |
| 511 | // Exportability is fixed at request time — ACM rejects |
| 512 | // `UpdateCertificateOptions` for it ("Export option for |
| 513 | // certificates cannot be updated"). |
| 514 | (olds.export ?? "DISABLED") !== (news.export ?? "DISABLED") |
| 515 | ) { |
| 516 | return { action: "replace" } as const; |
| 517 | } |
| 518 | // `certificateTransparencyLoggingPreference` is intentionally NOT |
| 519 | // a replacement trigger — it is updated in place via |
| 520 | // `UpdateCertificateOptions` in `reconcile`. |
| 521 | }), |
| 522 | read: Effect.fn(function* ({ id, olds, output }) { |
| 523 | // `olds.domainName` may be `undefined` when a `creating` row was |
| 524 | // persisted before upstream Outputs resolved — without a domain |
| 525 | // there is nothing to search for, so report "not found" and let |
| 526 | // the engine re-drive the create (reconcile finds any managed |
| 527 | // certificate by tags before requesting a new one). |
| 528 | const certificate = output?.certificateArn |
| 529 | ? yield* describeCertificate(output.certificateArn) |
| 530 | : olds?.domainName !== undefined |
| 531 | ? yield* findManagedCertificate(id, olds) |
| 532 | : undefined; |
| 533 | |
| 534 | if (!certificate?.CertificateArn) { |
| 535 | return undefined; |
| 536 | } |
| 537 | |
| 538 | const tags = yield* listCertificateTags(certificate.CertificateArn); |
| 539 | return toAttrs(olds ?? { domainName: certificate.DomainName! }, certificate, tags); |
| 540 | }), |
| 541 | reconcile: Effect.fn(function* ({ |
| 542 | id, |
| 543 | instanceId, |
| 544 | news: _news, |
| 545 | output, |
| 546 | session, |
| 547 | bindings, |
| 548 | }) { |
| 549 | // Fold bound SANs (see `CertificateBinding`) into the desired |
| 550 | // props up front so every downstream step — managed-certificate |
| 551 | // lookup, request, attrs — sees the effective SAN set. |
| 552 | const news: typeof _news = { |
| 553 | ..._news, |
| 554 | subjectAlternativeNames: resolveEffectiveSans(_news.subjectAlternativeNames, bindings), |
| 555 | }; |
| 556 | const internalTags = yield* createInternalTags(id); |
| 557 | const desiredTags = { ...internalTags, ...news.tags }; |
| 558 | |
| 559 | // Observe — find the live certificate. Domain + SAN combo plus |
| 560 | // alchemy-owned tags identify a certificate uniquely; if we have |
| 561 | // a cached ARN, prefer that as the fast path. ACM certificates |
| 562 | // can't be renamed, and most fields trigger replace via diff, |
| 563 | // so the only real ensure path is "request if no managed |
| 564 | // certificate exists". |
| 565 | let certificate = output?.certificateArn |
| 566 | ? yield* describeCertificate(output.certificateArn) |
| 567 | : undefined; |
| 568 | if (!certificate?.CertificateArn) { |
| 569 | certificate = yield* findManagedCertificate(id, news); |
| 570 | } |
| 571 | |
| 572 | // Ensure — request a new certificate if none exists. The |
| 573 | // `IdempotencyToken` (derived from `instanceId`) makes the |
| 574 | // request safe to retry. |
| 575 | if (!certificate?.CertificateArn) { |
| 576 | certificate = yield* withCertRegion(news.region)( |
| 577 | acm |
| 578 | .requestCertificate({ |
| 579 | DomainName: news.domainName, |
| 580 | // ACM rejects an empty list (min length 1) — composites |
| 581 | // pass `[]` for a domain without aliases. |
| 582 | SubjectAlternativeNames: |
| 583 | news.subjectAlternativeNames && news.subjectAlternativeNames.length > 0 |
| 584 | ? news.subjectAlternativeNames |
| 585 | : undefined, |
| 586 | ValidationMethod: news.validationMethod ?? defaultValidationMethod, |
| 587 | KeyAlgorithm: news.keyAlgorithm, |
| 588 | Options: |
| 589 | news.certificateTransparencyLoggingPreference || news.export |
| 590 | ? { |
| 591 | CertificateTransparencyLoggingPreference: |
| 592 | news.certificateTransparencyLoggingPreference, |
| 593 | Export: news.export, |
| 594 | } |
| 595 | : undefined, |
| 596 | IdempotencyToken: instanceId.replaceAll(/[^a-zA-Z0-9]/g, "").slice(0, 32), |
| 597 | Tags: createTagsList(desiredTags), |
| 598 | }) |
| 599 | .pipe( |
| 600 | Effect.flatMap( |
| 601 | Effect.fnUntraced(function* (response) { |
| 602 | if (!response.CertificateArn) { |
| 603 | return yield* new CertificateUnexpectedResponse({ |
| 604 | message: "requestCertificate returned no certificate ARN", |
| 605 | }); |
| 606 | } |
| 607 | return (yield* describeCertificate(response.CertificateArn))!; |
| 608 | }), |
| 609 | ), |
| 610 | ), |
| 611 | ); |
| 612 | } |
| 613 | |
| 614 | if (!certificate?.CertificateArn) { |
| 615 | return yield* new CertificateOperationFailed({ |
| 616 | message: "Failed to obtain ACM certificate", |
| 617 | }); |
| 618 | } |
| 619 | |
| 620 | const certificateArn = certificate.CertificateArn; |
| 621 | yield* session.note(certificateArn); |
| 622 | |
| 623 | // Sync DNS validation: ensure validation records are upserted and |
| 624 | // the cert reaches `ISSUED`. With `dnsValidation: "external"` the |
| 625 | // caller publishes them (a DNS adapter). Otherwise the zone is |
| 626 | // the explicit `hostedZoneId` when given, or the most specific |
| 627 | // public zone containing `domainName`; when neither yields a zone, |
| 628 | // validation is left to the caller (external DNS) and the |
| 629 | // certificate is returned pending — the pre-inference behavior. |
| 630 | // For an already-issued cert this is a fast-path: we only wait |
| 631 | // for validation records when the cert isn't already issued. |
| 632 | if ( |
| 633 | (news.validationMethod ?? defaultValidationMethod) === "DNS" && |
| 634 | certificate.Status !== "ISSUED" |
| 635 | ) { |
| 636 | if (news.dnsValidation === "external") { |
| 637 | // The caller publishes the records: surface them on the |
| 638 | // attributes and return pending. |
| 639 | certificate = yield* waitForValidationRecords(certificateArn); |
| 640 | } else { |
| 641 | const validationZoneId = |
| 642 | news.hostedZoneId ?? (yield* findPublicHostedZoneId(news.domainName)); |
| 643 | if (validationZoneId !== undefined) { |
| 644 | const withRecords = yield* waitForValidationRecords(certificateArn); |
| 645 | yield* upsertValidationRecords(validationZoneId, withRecords); |
| 646 | certificate = yield* waitForIssued(certificateArn); |
| 647 | } |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | // Sync options — only the CT logging preference is mutable in |
| 652 | // place via UpdateCertificateOptions (ACM rejects updating the |
| 653 | // export option; diff treats an `export` change as replacement). |
| 654 | // Diff OBSERVED options (adoption may hand us a certificate with |
| 655 | // foreign options); only call the API when an explicitly-desired |
| 656 | // value differs, and omit `Export` so the fixed option is left |
| 657 | // untouched. |
| 658 | const observedOptions = certificate.Options ?? {}; |
| 659 | const wantsCtChange = |
| 660 | news.certificateTransparencyLoggingPreference !== undefined && |
| 661 | news.certificateTransparencyLoggingPreference !== |
| 662 | observedOptions.CertificateTransparencyLoggingPreference; |
| 663 | if (wantsCtChange) { |
| 664 | yield* withCertRegion(regionOfCertificateArn(certificateArn))( |
| 665 | acm.updateCertificateOptions({ |
| 666 | CertificateArn: certificateArn, |
| 667 | Options: { |
| 668 | CertificateTransparencyLoggingPreference: |
| 669 | news.certificateTransparencyLoggingPreference, |
| 670 | }, |
| 671 | }), |
| 672 | ); |
| 673 | certificate = (yield* describeCertificate(certificateArn))!; |
| 674 | } |
| 675 | |
| 676 | // Sync tags — diff observed cloud tags against desired so |
| 677 | // adoption rewrites ownership tags correctly. |
| 678 | const observedTags = yield* listCertificateTags(certificateArn); |
| 679 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 680 | |
| 681 | if (upsert.length > 0) { |
| 682 | yield* withCertRegion(regionOfCertificateArn(certificateArn))( |
| 683 | acm.addTagsToCertificate({ |
| 684 | CertificateArn: certificateArn, |
| 685 | Tags: upsert, |
| 686 | }), |
| 687 | ); |
| 688 | } |
| 689 | if (removed.length > 0) { |
| 690 | yield* withCertRegion(regionOfCertificateArn(certificateArn))( |
| 691 | acm.removeTagsFromCertificate({ |
| 692 | CertificateArn: certificateArn, |
| 693 | Tags: removed.map((Key) => ({ Key })), |
| 694 | }), |
| 695 | ); |
| 696 | } |
| 697 | |
| 698 | // Re-read so the returned attributes reflect any tag mutation. |
| 699 | const finalTags = yield* listCertificateTags(certificateArn); |
| 700 | return toAttrs(news, certificate, finalTags); |
| 701 | }), |
| 702 | delete: Effect.fn(function* ({ output }) { |
| 703 | yield* withCertRegion(regionOfCertificateArn(output.certificateArn))( |
| 704 | acm |
| 705 | .deleteCertificate({ |
| 706 | CertificateArn: output.certificateArn, |
| 707 | }) |
| 708 | .pipe( |
| 709 | // `ResourceInUseException` covers the certificate-swap path: |
| 710 | // when a SAN change replaces the certificate, CloudFront can |
| 711 | // keep reporting the detached old certificate as in-use for a |
| 712 | // few minutes after the distribution update deploys — ride |
| 713 | // that out with a bounded wait instead of failing the delete. |
| 714 | Effect.retry({ |
| 715 | while: (e): boolean => |
| 716 | e._tag === "ConflictException" || e._tag === "ResourceInUseException", |
| 717 | schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(30)]), |
| 718 | }), |
| 719 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 720 | ), |
| 721 | ); |
| 722 | }), |
| 723 | }; |
| 724 | }), |
| 725 | ); |
| 726 | |
| 727 | /** @internal */ |
| 728 | export const waitForRoute53Change = Effect.fn(function* (changeId: string) { |
| 729 | return yield* route53 |
| 730 | .getChange({ |
| 731 | Id: changeId.replace(/^\/change\//, ""), |
| 732 | }) |
| 733 | .pipe( |
| 734 | Effect.map((response) => response.ChangeInfo), |
| 735 | Effect.flatMap((changeInfo) => |
| 736 | changeInfo.Status === "INSYNC" |
| 737 | ? Effect.succeed(changeInfo) |
| 738 | : Effect.fail(new CertificateNotReady({ message: "Route53ChangePending" })), |
| 739 | ), |
| 740 | Effect.retry({ |
| 741 | while: (error) => |
| 742 | error._tag === "CertificateNotReady" && error.message === "Route53ChangePending", |
| 743 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]), |
| 744 | }), |
| 745 | ); |
| 746 | }); |
| 747 | |
| 748 | const ACM_REGION = "us-east-1" as const; |
| 749 | const defaultValidationMethod = "DNS" as const; |
| 750 | |
| 751 | /** |
| 752 | * Region an existing certificate lives in, parsed from its ARN |
| 753 | * (`arn:aws:acm:{region}:{account}:certificate/...`). |
| 754 | */ |
| 755 | const regionOfCertificateArn = (certificateArn: string) => |
| 756 | certificateArn.split(":")[3] || ACM_REGION; |
| 757 | |
| 758 | const withAcmRegion = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 759 | // `AwsRegion`'s service value is an `Effect<RegionName>` (see |
| 760 | // `@distilled.cloud/aws/Region`), so it must be provided as an effect, not a |
| 761 | // bare string — providing a raw string yields a primitive into the run loop. |
| 762 | effect.pipe(Effect.provideService(AwsRegion, Effect.succeed(ACM_REGION))); |
| 763 | |
| 764 | /** |
| 765 | * Pin ACM calls to the certificate's region: the props-requested region for |
| 766 | * new certificates (default `us-east-1`), or the region parsed from an |
| 767 | * existing certificate's ARN. |
| 768 | */ |
| 769 | const withCertRegion = |
| 770 | (region: string | undefined) => |
| 771 | <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 772 | effect.pipe( |
| 773 | Effect.provideService(AwsRegion, Effect.succeed((region ?? ACM_REGION) as typeof ACM_REGION)), |
| 774 | ); |
| 775 | |
| 776 | const normalizeHostedZoneId = (hostedZoneId: string) => hostedZoneId.replace(/^\/hostedzone\//, ""); |
| 777 | |
| 778 | const normalizeSanList = (names: string[] | undefined) => |
| 779 | [...(names ?? [])].sort((a, b) => a.localeCompare(b)); |
| 780 | |
| 781 | const toTagRecord = (tags: acm.Tag[] | undefined) => |
| 782 | Object.fromEntries( |
| 783 | (tags ?? []) |
| 784 | .filter( |
| 785 | (tag): tag is { Key: string; Value: string } => |
| 786 | typeof tag.Key === "string" && typeof tag.Value === "string", |
| 787 | ) |
| 788 | .map((tag) => [tag.Key, tag.Value]), |
| 789 | ); |
| 790 | |
| 791 | const toAttrs = ( |
| 792 | props: CertificateProps, |
| 793 | detail: acm.CertificateDetail, |
| 794 | tags: Record<string, string>, |
| 795 | ) => ({ |
| 796 | certificateArn: detail.CertificateArn!, |
| 797 | domainName: detail.DomainName ?? props.domainName, |
| 798 | subjectAlternativeNames: detail.SubjectAlternativeNames ?? [], |
| 799 | status: detail.Status, |
| 800 | domainValidationOptions: detail.DomainValidationOptions ?? [], |
| 801 | validationMethod: props.validationMethod ?? defaultValidationMethod, |
| 802 | keyAlgorithm: detail.KeyAlgorithm ?? props.keyAlgorithm, |
| 803 | hostedZoneId: props.hostedZoneId ? normalizeHostedZoneId(props.hostedZoneId) : undefined, |
| 804 | certificateTransparencyLoggingPreference: |
| 805 | detail.Options?.CertificateTransparencyLoggingPreference, |
| 806 | export: detail.Options?.Export, |
| 807 | tags, |
| 808 | issuedAt: detail.IssuedAt, |
| 809 | notAfter: detail.NotAfter, |
| 810 | }); |
| 811 | |
| 812 | /** |
| 813 | * The DNS validation records of a certificate's `domainValidationOptions`, |
| 814 | * shaped for a DNS adapter's `records(...)` (or any `RecordList`). A |
| 815 | * wildcard and its apex (`*.example.com` + `example.com`) share one CNAME, |
| 816 | * so records are deduped by type + name. |
| 817 | * |
| 818 | * **Example:** |
| 819 | * ```typescript |
| 820 | * const cert = yield* AWS.ACM.Certificate("Cert", { |
| 821 | * domainName: "app.example.com", |
| 822 | * dnsValidation: "external", |
| 823 | * }); |
| 824 | * yield* Cloudflare.DNS.RecordList("CertValidation", { |
| 825 | * records: cert.domainValidationOptions.pipe( |
| 826 | * Output.map(AWS.ACM.validationRecordsOf), |
| 827 | * ), |
| 828 | * }); |
| 829 | * ``` |
| 830 | */ |
| 831 | export const validationRecordsOf = ( |
| 832 | domainValidationOptions: acm.DomainValidation[] | undefined, |
| 833 | ): DnsRecord[] => [ |
| 834 | ...new Map( |
| 835 | (domainValidationOptions ?? []).flatMap((option) => |
| 836 | option.ResourceRecord |
| 837 | ? [ |
| 838 | [ |
| 839 | `${option.ResourceRecord.Type}:${option.ResourceRecord.Name.toLowerCase()}`, |
| 840 | { |
| 841 | name: option.ResourceRecord.Name, |
| 842 | type: option.ResourceRecord.Type as DnsRecord["type"], |
| 843 | value: option.ResourceRecord.Value, |
| 844 | }, |
| 845 | ] as const, |
| 846 | ] |
| 847 | : [], |
| 848 | ), |
| 849 | ).values(), |
| 850 | ]; |
| 851 | |
| 852 | /** |
| 853 | * Describe a certificate in its own region; `undefined` when it is gone. |
| 854 | * @internal shared with `CertificateValidation` |
| 855 | */ |
| 856 | export const describeCertificateDetail = (certificateArn: string) => |
| 857 | acm.describeCertificate({ CertificateArn: certificateArn }).pipe( |
| 858 | Effect.map((response) => response.Certificate), |
| 859 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 860 | withCertRegion(regionOfCertificateArn(certificateArn)), |
| 861 | ); |
| 862 | |
| 863 | /** |
| 864 | * Poll a certificate until ACM issues it (bounded: 10s × 60). Fails with |
| 865 | * {@link CertificateCaaError} on `CAA_ERROR`, and with an error naming the |
| 866 | * status on any other terminal failure. |
| 867 | * @internal shared with `CertificateValidation` |
| 868 | */ |
| 869 | export const waitForCertificateIssued = (certificateArn: string) => |
| 870 | describeCertificateDetail(certificateArn).pipe( |
| 871 | Effect.flatMap( |
| 872 | Effect.fnUntraced(function* (detail) { |
| 873 | if (!detail?.CertificateArn) { |
| 874 | return yield* new CertificateUnexpectedResponse({ message: "CertificateNotFound" }); |
| 875 | } |
| 876 | if (detail.Status === "ISSUED") { |
| 877 | return detail; |
| 878 | } |
| 879 | if (isTerminalFailure(detail.Status)) { |
| 880 | if (detail.FailureReason === "CAA_ERROR") { |
| 881 | return yield* new CertificateCaaError({ |
| 882 | certificateArn, |
| 883 | domainName: detail.DomainName ?? "", |
| 884 | }); |
| 885 | } |
| 886 | return yield* new CertificateOperationFailed({ |
| 887 | message: `Certificate issuance failed with status ${detail.Status}${detail.FailureReason ? ` (${detail.FailureReason})` : ""}`, |
| 888 | }); |
| 889 | } |
| 890 | return yield* new CertificateNotReady({ message: "CertificatePendingValidation" }); |
| 891 | }), |
| 892 | ), |
| 893 | Effect.retry({ |
| 894 | while: (error) => |
| 895 | error._tag === "CertificateNotReady" && error.message === "CertificatePendingValidation", |
| 896 | schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]), |
| 897 | }), |
| 898 | ); |
| 899 | |
| 900 | const isTerminalFailure = (status: acm.CertificateStatus | undefined) => |
| 901 | status === "FAILED" || status === "VALIDATION_TIMED_OUT"; |