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

main
ts 244 lines 9.85 KB
Raw
1 import * as DNS from "alchemy/DNS/Adapter";
2 import type { Input } from "alchemy/Input";
3 import * as Namespace from "alchemy/Namespace";
4 import * as Output from "alchemy/Output";
5 import { defaultProviderMode } from "alchemy/ProviderMode";
6 /**
7 * `Cloudflare.Worker` custom domains whose DNS lives outside Cloudflare
8 * (Route 53, Hetzner DNS, …), served through Cloudflare for SaaS.
9 *
10 * A native Worker custom domain only works for a hostname in a Cloudflare
11 * zone of the account. For any other DNS host, each hostname becomes a
12 * `Cloudflare.CustomHostname.CustomHostname` on a Cloudflare zone the user
13 * owns (the "SaaS zone"), the DNS host publishes the ownership and
14 * certificate-validation TXT records plus a CNAME to the SaaS zone, and a
15 * Worker route on the SaaS zone serves the traffic.
16 *
17 * Composition happens in the Worker's `transformProps` hook, at construct
18 * time: the WorkerProvider never sees `domain.dns`.
19 */
20 import * as Data from "effect/Data";
21 import * as Effect from "effect/Effect";
22 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
23 import {
24 CustomHostname,
25 type OwnershipVerification,
26 type ValidationRecord,
27 } from "../CustomHostname/CustomHostname.ts";
28 import { CLOUDFLARE_DNS } from "../DNS/Adapter.ts";
29 import { findZoneByName, isId, type Reference as ZoneReference } from "../Zone/lookup.ts";
30 import type { WorkerDomainConfig, WorkerProps, WorkerRouteConfig } from "./Worker.ts";
31
32 /**
33 * A Worker's `domain` cannot be served through Cloudflare for SaaS as
34 * configured — the SaaS zone or `cnameTarget` is missing, or it uses an
35 * option (`redirects`, `previews`) that only native custom domains
36 * support. Raised as a defect while the stack program is being built,
37 * before anything is deployed.
38 */
39 export class WorkerDomainDnsError extends Data.TaggedError("WorkerDomainDnsError")<{
40 readonly workerId: string;
41 readonly message: string;
42 }> {}
43
44 type Props = WorkerProps<any, any>;
45
46 /**
47 * The ownership-verification TXT record plus the certificate DCV TXT
48 * records of a custom hostname, de-duplicated. Entries Cloudflare has not
49 * populated (yet) are skipped.
50 *
51 * @internal exported for unit testing.
52 */
53 export const customHostnameVerificationRecords = (
54 ownership: OwnershipVerification | undefined,
55 validation: ValidationRecord[] | undefined,
56 ): DNS.DnsRecord[] => {
57 const records: DNS.DnsRecord[] = [];
58 const seen = new Set<string>();
59 const push = (name: string | undefined, value: string | undefined) => {
60 if (!name || !value) return;
61 const key = `${DNS.normalizeDnsName(name)} ${value}`;
62 if (seen.has(key)) return;
63 seen.add(key);
64 records.push({ name, type: "TXT", value });
65 };
66 push(ownership?.name, ownership?.value);
67 for (const record of validation ?? []) {
68 push(record.txtName, record.txtValue);
69 }
70 return records;
71 };
72
73 const sanitize = (hostname: string) => hostname.replaceAll(/[^a-zA-Z0-9-]/g, "-");
74
75 /**
76 * The Worker's `transformProps` hook. `domain.dns` omitted keeps the
77 * native custom-domain path with the props untouched; a Cloudflare
78 * adapter is stripped back to the native path; any other adapter composes
79 * the Cloudflare for SaaS resources and replaces `domain` with routes on
80 * the SaaS zone. A no-op at runtime and for Workers running locally under
81 * `alchemy dev` (the local Worker ignores `domain`).
82 */
83 export const transformWorkerDomainProps = (
84 id: string,
85 props: Props | undefined,
86 ): Effect.Effect<Props | undefined, never, any> =>
87 Effect.gen(function* () {
88 // `Platform` hands a bare-tag forward reference (no props yet) to the
89 // hook as `{}`. Keep it `undefined` so `Plan.make` still fails fast
90 // when the tag's `.make` Layer is never provided (#1054).
91 if (props === undefined || Object.keys(props).length === 0) {
92 return undefined;
93 }
94 if (globalThis.__ALCHEMY_RUNTIME__) return props;
95 const domain = props.domain;
96 if (domain === undefined || domain === null || typeof domain !== "object") {
97 return props;
98 }
99 const dns = domain.dns;
100 if (dns === undefined) return props;
101 if (dns.type === CLOUDFLARE_DNS) {
102 const { dns: _dns, cnameTarget: _cnameTarget, ...native } = domain;
103 // Native custom domains already publish their own DNS. The adapter's
104 // zone pins the zone when the domain config does not.
105 const pinned =
106 native.zoneId !== undefined || native.zoneName !== undefined || native.zone !== undefined;
107 return {
108 ...props,
109 domain:
110 pinned || dns.zone === undefined
111 ? native
112 : { ...native, zone: dns.zone as unknown as ZoneReference },
113 };
114 }
115 // The local Worker serves on localhost and ignores `domain`.
116 if ((yield* defaultProviderMode) === "local") return props;
117 return yield* composeSaasDomain(id, props, domain, dns).pipe(Namespace.push(id));
118 });
119
120 const composeSaasDomain = (
121 id: string,
122 props: Props,
123 domain: WorkerDomainConfig,
124 dns: DNS.DnsConfig,
125 ) =>
126 Effect.gen(function* () {
127 const fail = (message: string) =>
128 Effect.die(
129 new WorkerDomainDnsError({
130 workerId: id,
131 message: `Cloudflare.Worker "${id}": ${message}`,
132 }),
133 );
134 const via = `\`domain.dns\` is "${dns.type}" (served through Cloudflare for SaaS)`;
135 if ((domain.redirects?.length ?? 0) > 0) {
136 return yield* fail(
137 `\`domain.redirects\` is not supported when ${via} — redirect rules need the hostname in a Cloudflare zone. Serve the redirect hostnames from the Worker, or move their DNS to Cloudflare.`,
138 );
139 }
140 if (domain.previews === true) {
141 return yield* fail(
142 `\`domain.previews\` is not supported when ${via} — Worker Previews need a native custom domain in a Cloudflare zone.`,
143 );
144 }
145 const cnameTarget = domain.cnameTarget;
146 if (cnameTarget === undefined) {
147 return yield* fail(
148 `\`domain.cnameTarget\` is required when ${via}: the hostname in the SaaS zone that custom hostnames CNAME to, typically the zone's fallback origin (\`Cloudflare.CustomHostname.FallbackOrigin\`).`,
149 );
150 }
151 const hostnames = [...new Set([domain.name, ...(domain.aliases ?? [])])] as unknown[];
152 for (const hostname of hostnames) {
153 if (typeof hostname !== "string") {
154 return yield* fail(
155 `domain hostnames must be plain strings when ${via} — each one names its own resources.`,
156 );
157 }
158 }
159 const zoneId = yield* resolveSaasZoneId(domain, fail, via);
160 const adapter = yield* DNS.resolve(dns);
161
162 const routes: WorkerRouteConfig[] = [];
163 for (const hostname of hostnames as string[]) {
164 const key = sanitize(hostname);
165 const customHostname = yield* CustomHostname(`CustomHostname-${key}`, {
166 zoneId: zoneId as string,
167 hostname,
168 // TXT DCV yields `txtName`/`txtValue` validation records the DNS
169 // host publishes alongside the ownership TXT.
170 ssl: { method: "txt", type: "dv" },
171 });
172 yield* adapter.records(`Hostname-${key}-Verification`, {
173 records: Output.map(
174 Output.all(customHostname.ownershipVerification, customHostname.validationRecords),
175 ([ownership, validation]) =>
176 customHostnameVerificationRecords(
177 ownership as OwnershipVerification | undefined,
178 validation as ValidationRecord[] | undefined,
179 ),
180 ) as unknown as Input<DNS.DnsRecord[]>,
181 });
182 yield* adapter.alias(`Hostname-${key}`, {
183 name: hostname,
184 target: { hostname: cnameTarget },
185 });
186 // The route API only accepts a pattern outside the zone's own names
187 // for a custom hostname of a Cloudflare for SaaS zone (otherwise
188 // `InvalidRoutePattern`, code 10022), so derive the pattern from the
189 // custom hostname: the Worker deploys after it.
190 routes.push({
191 pattern: Output.map(customHostname.hostname, (name) => `${name}/*`) as unknown as string,
192 zoneId: zoneId as string,
193 });
194 }
195
196 const { domain: _domain, ...rest } = props;
197 return {
198 ...rest,
199 routes: [...(props.routes ?? []), ...routes],
200 } satisfies Props;
201 });
202
203 /**
204 * The SaaS zone's id: `zoneId`, a `{ zoneId }` zone (e.g. a
205 * `Cloudflare.Zone.Zone`), or a zone-id string are used as-is; a zone name
206 * is looked up in the account.
207 */
208 const resolveSaasZoneId = (
209 domain: WorkerDomainConfig,
210 fail: (message: string) => Effect.Effect<never>,
211 via: string,
212 ) =>
213 Effect.gen(function* () {
214 if (domain.zoneId !== undefined) return domain.zoneId as Input<string>;
215 const zone = domain.zone as Input<ZoneReference> | undefined;
216 if (Output.isOutput(zone)) {
217 return Output.map(zone as Output.Output<ZoneReference>, (value) =>
218 typeof value === "string" ? value : value.zoneId,
219 ) as unknown as Input<string>;
220 }
221 if (typeof zone === "object") {
222 return (zone as { zoneId: Input<string> }).zoneId;
223 }
224 if (typeof zone === "string" && isId(zone)) return zone;
225 const name = typeof zone === "string" ? zone : domain.zoneName;
226 if (name === undefined) {
227 return yield* fail(
228 `\`domain.zoneId\`, \`domain.zone\`, or \`domain.zoneName\` is required when ${via}: the Cloudflare zone (with Cloudflare for SaaS enabled) that hosts the custom hostnames and the Worker routes.`,
229 );
230 }
231 if (typeof name !== "string") {
232 return yield* fail(
233 `a zone name given as an Output cannot be looked up while the stack is built — pass the zone id (\`domain.zoneId\`) or the \`Cloudflare.Zone.Zone\` resource (\`domain.zone\`).`,
234 );
235 }
236 const { accountId } = yield* yield* CloudflareEnvironment;
237 const match = yield* findZoneByName({ accountId, name }).pipe(
238 Effect.catch((error) => fail(`looking up the SaaS zone "${name}" failed: ${String(error)}`)),
239 );
240 if (match === undefined) {
241 return yield* fail(`the SaaS zone "${name}" was not found in the Cloudflare account.`);
242 }
243 return match.id as Input<string>;
244 });