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

main
ts 203 lines 7.89 KB
Raw
1 import type { DnsConfig } from "alchemy/DNS/Adapter";
2 import * as Namespace from "alchemy/Namespace";
3 import * as Output from "alchemy/Output";
4 import { defaultProviderMode, type ProviderMode } from "alchemy/ProviderMode";
5 /**
6 * Custom domains for `AWS.Lambda.Function`.
7 *
8 * Lambda Function URLs cannot serve a custom hostname, so a Function's
9 * `domain` composes an API Gateway v2 HTTP API front door (the
10 * `ApiGatewayV2.HttpApi` composite: `$default` route, `AWS_PROXY`
11 * integration with payload 2.0 — the Function URL event shape — and an
12 * auto-deployed `$default` stage), a regional ACM certificate, one
13 * `ApiGatewayV2.DomainName` + `ApiMapping` per hostname, and the alias
14 * records, published through whichever DNS host `domain.dns` names.
15 *
16 * Composition references the Function's own outputs (ARN, name), so it
17 * runs from the platform's `onCreate` hook, after the Function resource is
18 * declared.
19 */
20 import * as Data from "effect/Data";
21 import * as Effect from "effect/Effect";
22 import { ApiMapping } from "../ApiGatewayV2/ApiMapping.ts";
23 import { DomainName } from "../ApiGatewayV2/DomainName.ts";
24 import { HttpApi } from "../ApiGatewayV2/HttpApi.ts";
25 import { domainCertificate, resolveDomainDns } from "../CustomDomain.ts";
26 import { qualifiedArnOf, qualifiedNameOf } from "./QualifiedArn.ts";
27
28 /** Object form of the `AWS.Lambda.Function` `domain` prop. */
29 export interface FunctionDomainConfig {
30 /**
31 * Hostname that serves the Function, e.g. `api.example.com`. The
32 * Function's `domainUrl` attribute is `https://{name}`.
33 */
34 name: string;
35 /**
36 * Additional hostnames that serve the Function. Each gets its own API
37 * Gateway domain name, API mapping, alias record, and a subject
38 * alternative name on the ACM certificate.
39 */
40 aliases?: string[];
41 /**
42 * Route 53 hosted zone for the certificate validation and alias records.
43 * Optional — when omitted, the most specific PUBLIC hosted zone in the
44 * account containing each hostname is inferred. Ignored when {@link dns}
45 * names another DNS host.
46 */
47 hostedZoneId?: string;
48 /**
49 * DNS host for the certificate validation and alias records (see
50 * [DNS Adapters](/infrastructure-as-code/dns-adapters)). Omitted: Route
51 * 53 (see {@link hostedZoneId}) with an `A` alias record per hostname.
52 * Pass `Cloudflare.DNS.Adapter()` or `Hetzner.DNS.Adapter()` for a
53 * domain whose DNS lives there — each hostname gets a `CNAME` to the API
54 * Gateway domain and the certificate is validated through that host.
55 */
56 dns?: DnsConfig;
57 }
58
59 /**
60 * A Function's custom domain: a hostname (Route 53 DNS), or a
61 * {@link FunctionDomainConfig}.
62 */
63 export type FunctionDomain = string | FunctionDomainConfig;
64
65 /**
66 * The `domain` prop of an `AWS.Lambda.Function` is invalid (empty or
67 * duplicate hostnames). Raised as a defect while the stack program is
68 * built, before anything is deployed.
69 */
70 export class InvalidFunctionDomain extends Data.TaggedError("InvalidFunctionDomain")<{
71 readonly functionId: string;
72 readonly message: string;
73 }> {}
74
75 /** Normalize the `domain` prop to its object form. */
76 export const normalizeFunctionDomain = (
77 domain: FunctionDomain | undefined,
78 ): FunctionDomainConfig | undefined =>
79 domain === undefined ? undefined : typeof domain === "string" ? { name: domain } : domain;
80
81 /** `https://{name}` of a Function's custom domain. */
82 export const functionDomainUrl = (domain: FunctionDomain | undefined): string | undefined => {
83 const config = normalizeFunctionDomain(domain);
84 return config === undefined ? undefined : `https://${config.name}`;
85 };
86
87 /** The Function outputs the front door references. */
88 interface FunctionDomainHost {
89 readonly LogicalId: string;
90 readonly Mode: ProviderMode | undefined;
91 readonly functionArn: Output.Output<string>;
92 readonly functionName: Output.Output<string>;
93 readonly qualifiedArn: Output.Output<string>;
94 }
95
96 /**
97 * Compose the API Gateway front door and DNS for a Function's `domain`
98 * under the Function's namespace. A no-op at runtime, without a `domain`,
99 * and when the Function runs locally under `alchemy dev` (a local Function
100 * has no cloud ARN to integrate; opt a Function out with `Alchemy.remote()`
101 * to serve its domain during dev).
102 *
103 * Resources (under `{FunctionId}/`):
104 *
105 * - `Api/*` — `ApiGatewayV2.HttpApi` (Api, Integration, `$default` Route,
106 * Stage, invoke Permission)
107 * - `Certificate` (+ `CertificateValidation` / `CertificateIssued` on a
108 * non-Route 53 DNS host) — in the Function's region
109 * - `DomainName-{host}` / `ApiMapping-{host}` — per hostname
110 * - `Domain-{host}` — the DNS host's alias record(s) per hostname
111 */
112 export const composeFunctionDomain = (
113 fn: FunctionDomainHost,
114 domainProp: FunctionDomain | undefined,
115 ): Effect.Effect<void, never, any> =>
116 Effect.gen(function* () {
117 if (globalThis.__ALCHEMY_RUNTIME__) return;
118 const domain = normalizeFunctionDomain(domainProp);
119 if (domain === undefined) return;
120 if ((fn.Mode ?? (yield* defaultProviderMode)) === "local") return;
121
122 const id = fn.LogicalId;
123 const names = [domain.name, ...(domain.aliases ?? [])];
124 if (names.some((name) => typeof name !== "string" || name.length === 0)) {
125 return yield* Effect.die(
126 new InvalidFunctionDomain({
127 functionId: id,
128 message: `AWS.Lambda.Function "${id}": \`domain\` names must be non-empty hostnames`,
129 }),
130 );
131 }
132 const ids = names.map((name) => name.replaceAll(/[^a-zA-Z0-9-]/g, "-"));
133 if (new Set(ids).size !== ids.length) {
134 return yield* Effect.die(
135 new InvalidFunctionDomain({
136 functionId: id,
137 message: `AWS.Lambda.Function "${id}": \`domain\` lists the same hostname more than once (${names.join(", ")})`,
138 }),
139 );
140 }
141
142 yield* Effect.gen(function* () {
143 // Integrate and grant invoke on the alias when the Function has one.
144 const { api, stage } = yield* HttpApi("Api", {
145 handler: {
146 LogicalId: id,
147 functionArn: qualifiedArnOf(fn),
148 functionName: qualifiedNameOf(fn),
149 },
150 });
151
152 // API Gateway regional domains need a certificate in the API's
153 // region, which is the Function's.
154 const region = Output.map(fn.functionArn, (arn: string) => arn.split(":")[3]!);
155 const { certificateArn } = yield* domainCertificate(
156 "Certificate",
157 {
158 domainName: domain.name,
159 ...(domain.aliases?.length ? { subjectAlternativeNames: domain.aliases } : {}),
160 ...(domain.hostedZoneId === undefined ? {} : { hostedZoneId: domain.hostedZoneId }),
161 region: region as unknown as string,
162 },
163 domain.dns,
164 );
165
166 const dns = yield* resolveDomainDns(domain.dns, domain.hostedZoneId);
167 for (const [index, name] of names.entries()) {
168 const host = ids[index]!;
169 const apiDomain = yield* DomainName(`DomainName-${host}`, {
170 domainName: name,
171 domainNameConfigurations: [
172 {
173 CertificateArn: certificateArn as unknown as string,
174 EndpointType: "REGIONAL",
175 SecurityPolicy: "TLS_1_2",
176 },
177 ],
178 });
179 yield* ApiMapping(`ApiMapping-${host}`, {
180 api,
181 domainName: apiDomain.domainName,
182 stage: stage.stageName,
183 });
184 // The API Gateway-managed target (`d-xxxx.execute-api.{region}.
185 // amazonaws.com`) and its Route 53 alias zone.
186 yield* dns.alias(`Domain-${host}`, {
187 name,
188 target: {
189 hostname: Output.map(
190 apiDomain.domainNameConfigurations,
191 (configs) => configs?.[0]?.ApiGatewayDomainName!,
192 ),
193 route53Alias: {
194 hostedZoneId: Output.map(
195 apiDomain.domainNameConfigurations,
196 (configs) => configs?.[0]?.HostedZoneId!,
197 ),
198 },
199 },
200 });
201 }
202 }).pipe(Namespace.push(id));
203 }) as Effect.Effect<void, never, any>;