@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 464 lines 18.1 KB
Raw
1 import { resolve4, resolveNs, Resolver } from "node:dns/promises";
2 import { fileURLToPath } from "node:url";
3 /**
4 * Custom domains on AWS website composites through each DNS host `domain.dns`
5 * can name — live deployments served over HTTPS:
6 *
7 * - `Cloudflare.DNS.Adapter()` on a `StaticSite` (canonical name + alias) and
8 * on a `Router` whose attached `StaticSite` binds an extra hostname onto the
9 * Router's record set.
10 * - The Route 53 default (no `dns`): a plain-string domain under a Route 53
11 * zone delegated from the standing Cloudflare test zone; the zone is
12 * inferred.
13 * - `Hetzner.DNS.Adapter({ zone })` on a subdomain delegated from the
14 * Cloudflare test zone to Hetzner's nameservers.
15 *
16 * Skipped under --fast: every test deploys (and deletes) a CloudFront
17 * distribution and waits for ACM issuance — minutes each (speed doctrine).
18 * The tests run concurrently.
19 */
20 import * as AWS from "@alchemy.run/aws";
21 import * as Cloudflare from "@alchemy.run/cloudflare";
22 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
23 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
24 import * as Hetzner from "@alchemy.run/hetzner";
25 import { describe, expect } from "@alchemy.run/test";
26 import * as Test from "@alchemy.run/test/Alchemy";
27 import * as acm from "@distilled.cloud/aws/acm";
28 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
29 import { Region } from "@distilled.cloud/aws/Region";
30 import * as route53 from "@distilled.cloud/aws/route-53";
31 import * as dns from "@distilled.cloud/cloudflare/dns";
32 import * as zoneRrsets from "@distilled.cloud/hetzner/zone_rrsets";
33 import * as zones from "@distilled.cloud/hetzner/zones";
34 import * as Data from "effect/Data";
35 import * as Effect from "effect/Effect";
36 import * as HttpClient from "effect/http/HttpClient";
37 import * as Layer from "effect/Layer";
38 import * as Schedule from "effect/Schedule";
39 import * as Stream from "effect/Stream";
40
41 const { test } = Test.make({
42 providers: Layer.mergeAll(AWS.providers(), Cloudflare.providers(), Hetzner.providers()),
43 });
44
45 // Anchor the fixture to the repo root regardless of the runner's cwd.
46 const fixtureDir = fileURLToPath(
47 new URL("../../../../../examples/aws-static-site/site", import.meta.url),
48 );
49
50 const ZONE = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
51
52 const CF_SITE = `aws-site-cf.${ZONE}`;
53 const CF_SITE_ALIAS = `aws-site-cf-alias.${ZONE}`;
54 const ROUTER_HOST = `aws-site-router.${ZONE}`;
55 const ROUTER_DOCS_HOST = `aws-site-router-docs.${ZONE}`;
56 const R53_ZONE = `aws-site-r53.${ZONE}`;
57 const R53_SITE = `www.${R53_ZONE}`;
58 // Hetzner DNS only hosts registrable apex zones ("unsupported tld" for a
59 // subdomain zone), so the Hetzner zone is the apex itself and Cloudflare
60 // delegates just this subdomain to Hetzner's nameservers. Zone names are
61 // unique per Hetzner account: a concurrent suite owning the same apex zone
62 // makes this test's zone read as unowned.
63 const HZ_DELEGATED = `aws-site-hz.${ZONE}`;
64 const HZ_SITE = `www.${HZ_DELEGATED}`;
65
66 class NotYet extends Data.TaggedError("NotYet")<{ readonly what: string }> {}
67
68 const bare = (name: string) => name.replace(/\.$/, "").toLowerCase();
69
70 const cloudflareZoneId = Effect.gen(function* () {
71 const { accountId } = yield* yield* CloudflareEnvironment;
72 const zone = yield* findZoneByName({ accountId, name: ZONE });
73 if (!zone) {
74 return yield* Effect.die(new Error(`zone "${ZONE}" not found in account`));
75 }
76 return zone.id;
77 });
78
79 const listCloudflareRecords = (zoneId: string, name: string, type: "CNAME" | "NS") =>
80 dns.listRecords.items({ zoneId, name: { exact: name }, type }).pipe(
81 Stream.runCollect,
82 Effect.map((chunk) => Array.from(chunk)),
83 );
84
85 /** NS records in the Cloudflare zone delegating `name` to `nameServers`. */
86 const delegate = (zoneId: string, name: string, nameServers: readonly string[]) =>
87 Effect.forEach(nameServers, (nameServer, index) =>
88 Cloudflare.DNS.Record(`Delegation${index + 1}`, {
89 zoneId,
90 name,
91 type: "NS",
92 content: bare(nameServer),
93 }),
94 );
95
96 const cloudflareNameServers = Effect.tryPromise(() => resolveNs(ZONE)).pipe(Effect.orDie);
97
98 /**
99 * Wait until every authoritative nameserver answers `name` acceptably, so
100 * the first HTTPS request never resolves (and negatively caches) the
101 * hostname before it exists.
102 */
103 const waitForAuthoritative = (
104 nameServers: readonly string[],
105 name: string,
106 query: (resolver: Resolver, name: string) => Promise<string[]>,
107 accept: (answers: string[]) => boolean,
108 ) =>
109 Effect.gen(function* () {
110 const servers = (yield* Effect.forEach(nameServers, (nameServer) =>
111 Effect.tryPromise(() => resolve4(bare(nameServer))).pipe(Effect.orDie),
112 )).flat();
113 yield* Effect.forEach(
114 servers,
115 (server) =>
116 Effect.gen(function* () {
117 const resolver = yield* Effect.sync(() => {
118 const r = new Resolver();
119 r.setServers([server]);
120 return r;
121 });
122 const answers = yield* Effect.tryPromise(() => query(resolver, name)).pipe(
123 Effect.orElseSucceed(() => [] as string[]),
124 );
125 if (!accept(answers)) {
126 return yield* new NotYet({ what: `${name} @ ${server}` });
127 }
128 }).pipe(Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 20 })),
129 { discard: true },
130 );
131 });
132
133 const cnameTo =
134 (target: string) =>
135 (answers: string[]): boolean =>
136 answers.some((answer) => bare(answer) === bare(target));
137
138 const queryCname = (resolver: Resolver, name: string) => resolver.resolveCname(name);
139
140 const queryA = (resolver: Resolver, name: string) => resolver.resolve4(name);
141
142 /** `https://{hostname}/` answers 200 — bounded through the edge rollout. */
143 const expectServesHttps = (hostname: string) =>
144 Effect.gen(function* () {
145 const client = yield* HttpClient.HttpClient;
146 const status = yield* client.get(`https://${hostname}/`).pipe(
147 Effect.flatMap((res): Effect.Effect<number, NotYet> =>
148 res.status === 200
149 ? Effect.succeed(res.status)
150 : Effect.fail(new NotYet({ what: `https://${hostname}/ -> ${res.status}` })),
151 ),
152 Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 60 }),
153 );
154 expect(status).toBe(200);
155 });
156
157 /** The distribution's viewer certificate, read from ACM. */
158 const viewerCertificateOf = (distributionId: string) =>
159 Effect.gen(function* () {
160 const { DistributionConfig } = yield* cloudfront.getDistributionConfig({
161 Id: distributionId,
162 });
163 const certificateArn = DistributionConfig?.ViewerCertificate?.ACMCertificateArn;
164 expect(certificateArn).toBeDefined();
165 const { Certificate } = yield* acm
166 .describeCertificate({ CertificateArn: certificateArn! })
167 .pipe(Effect.provideService(Region, Effect.succeed("us-east-1" as const)));
168 expect(Certificate).toBeDefined();
169 return {
170 certificate: Certificate!,
171 aliases: DistributionConfig?.Aliases?.Items ?? [],
172 };
173 });
174
175 const expectRecordsGone = (zoneId: string, names: readonly string[], type: "CNAME" | "NS") =>
176 Effect.forEach(names, (name) =>
177 listCloudflareRecords(zoneId, name, type).pipe(
178 Effect.map((records) => expect(records).toHaveLength(0)),
179 ),
180 );
181
182 describe.skipIf(!!process.env.FAST)(
183 "AWS.Website custom domain DNS (live)",
184 {
185 concurrent: true,
186 tags: [
187 "provider:aws",
188 "provider:aws:acm",
189 "provider:aws:cloudfront",
190 "provider:aws:route53",
191 "provider:aws:website",
192 "provider:cloudflare",
193 "provider:cloudflare:dns",
194 "provider:hetzner",
195 "live",
196 ],
197 },
198 () => {
199 test.provider(
200 "StaticSite on Cloudflare DNS serves its name and alias over HTTPS",
201 (stack) =>
202 Effect.gen(function* () {
203 yield* stack.destroy();
204 const zoneId = yield* cloudflareZoneId;
205
206 const site = yield* stack.deploy(
207 Effect.gen(function* () {
208 const site = yield* AWS.Website.StaticSite("Site", {
209 path: fixtureDir,
210 forceDestroy: true,
211 domain: {
212 name: CF_SITE,
213 aliases: [CF_SITE_ALIAS],
214 dns: Cloudflare.DNS.Adapter(),
215 },
216 });
217 return {
218 urls: site.urls,
219 distributionId: site.distribution!.distributionId,
220 domainName: site.distribution!.domainName as unknown as string,
221 };
222 }),
223 );
224 expect(site.urls.slice(0, 2)).toEqual([`https://${CF_SITE}`, `https://${CF_SITE_ALIAS}`]);
225
226 // Each hostname is a DNS-only CNAME to the distribution.
227 for (const name of [CF_SITE, CF_SITE_ALIAS]) {
228 const records = yield* listCloudflareRecords(zoneId, name, "CNAME");
229 expect(records).toHaveLength(1);
230 expect(bare(records[0]!.content!)).toBe(bare(site.domainName));
231 expect(records[0]!.proxied).toBe(false);
232 }
233
234 // The certificate was validated through Cloudflare and is issued.
235 const { certificate, aliases } = yield* viewerCertificateOf(site.distributionId);
236 expect(aliases).toEqual(expect.arrayContaining([CF_SITE, CF_SITE_ALIAS]));
237 expect(certificate.Status).toBe("ISSUED");
238 expect(certificate.SubjectAlternativeNames).toEqual(
239 expect.arrayContaining([CF_SITE, CF_SITE_ALIAS]),
240 );
241 const validation = (certificate.DomainValidationOptions ?? []).map(
242 (option) => option.ResourceRecord,
243 );
244 expect(validation.length).toBeGreaterThan(0);
245 for (const record of validation) {
246 expect(record).toBeDefined();
247 const published = yield* listCloudflareRecords(zoneId, bare(record!.Name), "CNAME");
248 expect(published.map((r) => bare(r.content!))).toContain(bare(record!.Value));
249 }
250
251 const nameServers = yield* cloudflareNameServers;
252 for (const name of [CF_SITE, CF_SITE_ALIAS]) {
253 yield* waitForAuthoritative(nameServers, name, queryCname, cnameTo(site.domainName));
254 yield* expectServesHttps(name);
255 }
256
257 yield* stack.destroy();
258 yield* expectRecordsGone(zoneId, [CF_SITE, CF_SITE_ALIAS], "CNAME");
259 }),
260 { timeout: 2_400_000 },
261 );
262
263 test.provider(
264 "Router on Cloudflare DNS serves an attached site's bound hostname over HTTPS",
265 (stack) =>
266 Effect.gen(function* () {
267 yield* stack.destroy();
268 const zoneId = yield* cloudflareZoneId;
269
270 const deployed = yield* stack.deploy(
271 Effect.gen(function* () {
272 const router = yield* AWS.Website.Router("Router", {
273 domain: { name: ROUTER_HOST, dns: Cloudflare.DNS.Adapter() },
274 });
275 // `domain: { name, router }` alone binds the hostname onto the
276 // Router's distribution, certificate, and record set.
277 const docs = yield* AWS.Website.StaticSite("Docs", {
278 path: fixtureDir,
279 forceDestroy: true,
280 domain: { name: ROUTER_DOCS_HOST, router },
281 });
282 return {
283 distributionId: router.distributionId as unknown as string,
284 domainName: router.distribution.domainName as unknown as string,
285 docsUrl: docs.url,
286 };
287 }),
288 );
289 expect(deployed.docsUrl).toBe(`https://${ROUTER_DOCS_HOST}`);
290
291 // The Router's own hostname and the bound hostname are DNS-only
292 // CNAMEs to the Router's distribution.
293 for (const name of [ROUTER_HOST, ROUTER_DOCS_HOST]) {
294 const records = yield* listCloudflareRecords(zoneId, name, "CNAME");
295 expect(records).toHaveLength(1);
296 expect(bare(records[0]!.content!)).toBe(bare(deployed.domainName));
297 expect(records[0]!.proxied).toBe(false);
298 }
299
300 const { certificate, aliases } = yield* viewerCertificateOf(deployed.distributionId);
301 expect(aliases).toEqual(expect.arrayContaining([ROUTER_HOST, ROUTER_DOCS_HOST]));
302 expect(certificate.Status).toBe("ISSUED");
303 expect(certificate.SubjectAlternativeNames).toContain(ROUTER_DOCS_HOST);
304
305 yield* waitForAuthoritative(
306 yield* cloudflareNameServers,
307 ROUTER_DOCS_HOST,
308 queryCname,
309 cnameTo(deployed.domainName),
310 );
311 yield* expectServesHttps(ROUTER_DOCS_HOST);
312
313 yield* stack.destroy();
314 yield* expectRecordsGone(zoneId, [ROUTER_HOST, ROUTER_DOCS_HOST], "CNAME");
315 }),
316 { timeout: 2_400_000 },
317 );
318
319 test.provider(
320 "StaticSite without `dns` infers a Route 53 zone and serves over HTTPS",
321 (stack) =>
322 Effect.gen(function* () {
323 yield* stack.destroy();
324 const cfZoneId = yield* cloudflareZoneId;
325
326 const hostedZone = AWS.Route53.HostedZone("Zone", {
327 name: R53_ZONE,
328 forceDestroy: true,
329 });
330 // The zone must exist before the site's certificate and alias
331 // record infer it at reconcile time.
332 const { nameServers } = yield* stack.deploy(hostedZone);
333 expect(nameServers).toHaveLength(4);
334
335 const deployed = yield* stack.deploy(
336 Effect.gen(function* () {
337 const zone = yield* hostedZone;
338 yield* delegate(cfZoneId, R53_ZONE, nameServers);
339 const site = yield* AWS.Website.StaticSite("Site", {
340 path: fixtureDir,
341 forceDestroy: true,
342 domain: R53_SITE,
343 });
344 return {
345 hostedZoneId: zone.id,
346 url: site.url,
347 distributionId: site.distribution!.distributionId,
348 domainName: site.distribution!.domainName as unknown as string,
349 };
350 }),
351 );
352 expect(deployed.url).toBe(`https://${R53_SITE}`);
353
354 // Cloudflare delegates the subdomain to Route 53.
355 const delegation = yield* listCloudflareRecords(cfZoneId, R53_ZONE, "NS");
356 expect(delegation.map((r) => bare(r.content!)).sort()).toEqual(
357 nameServers.map(bare).sort(),
358 );
359
360 // An `A` alias record at the distribution in the inferred zone.
361 const { ResourceRecordSets } = yield* route53.listResourceRecordSets({
362 HostedZoneId: deployed.hostedZoneId,
363 StartRecordName: `${R53_SITE}.`,
364 StartRecordType: "A",
365 MaxItems: 1,
366 });
367 const alias = ResourceRecordSets?.[0];
368 expect(alias?.Name).toBe(`${R53_SITE}.`);
369 expect(alias?.Type).toBe("A");
370 expect(bare(alias?.AliasTarget?.DNSName ?? "")).toBe(bare(deployed.domainName));
371
372 const { certificate } = yield* viewerCertificateOf(deployed.distributionId);
373 expect(certificate.Status).toBe("ISSUED");
374
375 yield* waitForAuthoritative(
376 nameServers,
377 R53_SITE,
378 queryA,
379 (answers) => answers.length > 0,
380 );
381 yield* expectServesHttps(R53_SITE);
382
383 yield* stack.destroy();
384 const zoneGone = yield* route53.getHostedZone({ Id: deployed.hostedZoneId }).pipe(
385 Effect.as(false),
386 Effect.catchTag("NoSuchHostedZone", () => Effect.succeed(true)),
387 Effect.repeat({
388 schedule: Schedule.spaced("2 seconds"),
389 until: (gone) => gone,
390 times: 10,
391 }),
392 );
393 expect(zoneGone).toBe(true);
394 yield* expectRecordsGone(cfZoneId, [R53_ZONE], "NS");
395 }),
396 { timeout: 2_400_000 },
397 );
398
399 test.provider.skipIf(!process.env.HCLOUD_TOKEN)(
400 "StaticSite on Hetzner DNS serves a delegated subdomain over HTTPS",
401 (stack) =>
402 Effect.gen(function* () {
403 yield* stack.destroy();
404 const cfZoneId = yield* cloudflareZoneId;
405
406 const hetznerZone = Hetzner.Zone("Zone", { name: ZONE, ttl: 300 });
407 const { assignedNameservers } = yield* stack.deploy(hetznerZone);
408 expect(assignedNameservers.length).toBeGreaterThan(0);
409
410 const deployed = yield* stack.deploy(
411 Effect.gen(function* () {
412 const zone = yield* hetznerZone;
413 yield* delegate(cfZoneId, HZ_DELEGATED, assignedNameservers);
414 const site = yield* AWS.Website.StaticSite("Site", {
415 path: fixtureDir,
416 forceDestroy: true,
417 domain: { name: HZ_SITE, dns: Hetzner.DNS.Adapter({ zone }) },
418 });
419 return {
420 zoneId: zone.zoneId,
421 url: site.url,
422 distributionId: site.distribution!.distributionId,
423 domainName: site.distribution!.domainName as unknown as string,
424 };
425 }),
426 );
427 expect(deployed.url).toBe(`https://${HZ_SITE}`);
428
429 // The hostname is a CNAME to the distribution in the Hetzner zone.
430 const { rrset } = yield* zoneRrsets.getZoneRrset({
431 id_or_name: String(deployed.zoneId),
432 rr_name: HZ_SITE.slice(0, -(ZONE.length + 1)),
433 rr_type: "CNAME",
434 });
435 expect(rrset.records.map((r) => bare(r.value))).toEqual([bare(deployed.domainName)]);
436
437 const { certificate } = yield* viewerCertificateOf(deployed.distributionId);
438 expect(certificate.Status).toBe("ISSUED");
439
440 yield* waitForAuthoritative(
441 assignedNameservers,
442 HZ_SITE,
443 queryCname,
444 cnameTo(deployed.domainName),
445 );
446 yield* expectServesHttps(HZ_SITE);
447
448 yield* stack.destroy();
449 const zoneGone = yield* zones.getZone({ id_or_name: String(deployed.zoneId) }).pipe(
450 Effect.as(false),
451 Effect.catchTag("NotFound", () => Effect.succeed(true)),
452 Effect.repeat({
453 schedule: Schedule.spaced("2 seconds"),
454 until: (gone) => gone,
455 times: 10,
456 }),
457 );
458 expect(zoneGone).toBe(true);
459 yield* expectRecordsGone(cfZoneId, [HZ_DELEGATED], "NS");
460 }),
461 { timeout: 2_400_000 },
462 );
463 },
464 );