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 { resolve4, resolveNs, Resolver } from "node:dns/promises"; |
| 2 | /** |
| 3 | * `Cloudflare.Worker` `domain.dns`, deployed live: |
| 4 | * |
| 5 | * - a Cloudflare adapter keeps the native custom-domain path; |
| 6 | * - invalid SaaS configurations die with `WorkerDomainDnsError` on deploy; |
| 7 | * - an ungated Cloudflare for SaaS entitlement probe; |
| 8 | * - the full Cloudflare for SaaS lifecycle (a Worker on a Route 53 |
| 9 | * hostname), gated behind CLOUDFLARE_TEST_SAAS=1 because Cloudflare for |
| 10 | * SaaS is not provisioned on the test account (see the probe). |
| 11 | */ |
| 12 | import * as AWS from "@alchemy.run/aws"; |
| 13 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 14 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 15 | import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup"; |
| 16 | import { describe, expect } from "@alchemy.run/test"; |
| 17 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 18 | import * as route53 from "@distilled.cloud/aws/route-53"; |
| 19 | import * as customHostnames from "@distilled.cloud/cloudflare/custom-hostnames"; |
| 20 | import * as workers from "@distilled.cloud/cloudflare/workers"; |
| 21 | import * as Output from "alchemy/Output"; |
| 22 | import * as Data from "effect/Data"; |
| 23 | import * as Effect from "effect/Effect"; |
| 24 | import * as Exit from "effect/Exit"; |
| 25 | import * as Layer from "effect/Layer"; |
| 26 | import * as Schedule from "effect/Schedule"; |
| 27 | import * as Stream from "effect/Stream"; |
| 28 | import * as pathe from "pathe"; |
| 29 | import { testName } from "../../names.ts"; |
| 30 | import { expectUrlContains } from "../Utils/Http.ts"; |
| 31 | import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts"; |
| 32 | |
| 33 | const { test } = Test.make({ |
| 34 | providers: Layer.mergeAll(Cloudflare.providers(), AWS.providers()), |
| 35 | }); |
| 36 | |
| 37 | const main = pathe.resolve(import.meta.dirname, "fixtures", "saas-worker.ts"); |
| 38 | const MARKER = "worker-dns-ok"; |
| 39 | |
| 40 | const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us"; |
| 41 | |
| 42 | // Deterministic hostnames under this suite's `worker-dns` prefix. |
| 43 | const NATIVE_HOSTNAME = `${testName("worker-dns")}.${zoneName}`; |
| 44 | const INVALID_HOSTNAME = `${testName("worker-dns-invalid")}.${zoneName}`; |
| 45 | const PROBE_HOSTNAME = "worker-dns-probe.alchemy-saas-example.com"; |
| 46 | const ORIGIN_NAME = `${testName("worker-dns-origin")}.${zoneName}`; |
| 47 | const R53_ZONE_NAME = `${testName("worker-dns-r53")}.${zoneName}`; |
| 48 | const SAAS_HOSTNAME = `app.${R53_ZONE_NAME}`; |
| 49 | |
| 50 | const resolveZoneId = Effect.gen(function* () { |
| 51 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 52 | const zone = yield* findZoneByName({ accountId, name: zoneName }); |
| 53 | if (!zone) { |
| 54 | return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`)); |
| 55 | } |
| 56 | return zone.id; |
| 57 | }); |
| 58 | |
| 59 | // Rate-limit blips and freshly minted scoped tokens that 403 while they |
| 60 | // propagate. |
| 61 | const transientBlips = Schedule.exponential("500 millis"); |
| 62 | |
| 63 | class StillPresent extends Data.TaggedError("StillPresent")<{ |
| 64 | readonly what: string; |
| 65 | }> {} |
| 66 | |
| 67 | class NotPublished extends Data.TaggedError("NotPublished")<{ |
| 68 | readonly server: string; |
| 69 | readonly hostname: string; |
| 70 | }> {} |
| 71 | |
| 72 | /** The Worker custom-domain attachments of `hostname`. */ |
| 73 | const listAttachments = (hostname: string) => |
| 74 | Effect.gen(function* () { |
| 75 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 76 | return yield* workers.listDomains({ accountId, hostname }).pipe( |
| 77 | Effect.map((r) => (r.result ?? []).filter((d) => d.hostname === hostname)), |
| 78 | Effect.retry({ |
| 79 | while: (e) => e._tag === "TooManyRequests", |
| 80 | schedule: transientBlips, |
| 81 | times: 8, |
| 82 | }), |
| 83 | ); |
| 84 | }); |
| 85 | |
| 86 | const findCustomHostname = (zoneId: string, hostname: string) => |
| 87 | customHostnames.listCustomHostnames.items({ zoneId, hostname: { contain: hostname } }).pipe( |
| 88 | Stream.filter((h) => h.hostname === hostname), |
| 89 | Stream.runCollect, |
| 90 | Effect.map((chunk) => Array.from(chunk)[0]), |
| 91 | Effect.retry({ |
| 92 | while: (e) => e._tag === "Forbidden", |
| 93 | schedule: transientBlips, |
| 94 | times: 8, |
| 95 | }), |
| 96 | ); |
| 97 | |
| 98 | const listWorkerRoutes = (zoneId: string, pattern: string) => |
| 99 | workers.listRoutes.items({ zoneId }).pipe( |
| 100 | Stream.filter((route) => route.pattern === pattern), |
| 101 | Stream.runCollect, |
| 102 | Effect.map((chunk) => Array.from(chunk)), |
| 103 | ); |
| 104 | |
| 105 | /** Retry `check` (bounded) until it stops failing with `StillPresent`. */ |
| 106 | const waitUntilGone = <E, R>(check: Effect.Effect<void, E, R>) => |
| 107 | check.pipe( |
| 108 | Effect.retry({ |
| 109 | while: (e) => e instanceof StillPresent, |
| 110 | schedule: Schedule.spaced("2 seconds"), |
| 111 | times: 15, |
| 112 | }), |
| 113 | ); |
| 114 | |
| 115 | /** |
| 116 | * Wait until every authoritative nameserver answers `lookup` for |
| 117 | * `hostname`, so the first HTTPS request never resolves (and negatively |
| 118 | * caches) the hostname before it exists. |
| 119 | */ |
| 120 | const waitForAuthoritative = ( |
| 121 | nameServers: readonly string[], |
| 122 | hostname: string, |
| 123 | lookup: (resolver: Resolver, hostname: string) => Promise<string[]>, |
| 124 | ) => |
| 125 | Effect.gen(function* () { |
| 126 | const servers = (yield* Effect.forEach(nameServers, (ns) => |
| 127 | Effect.tryPromise(() => resolve4(ns)).pipe( |
| 128 | Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 10 }), |
| 129 | Effect.orDie, |
| 130 | ), |
| 131 | )).flat(); |
| 132 | yield* Effect.forEach(servers, (server) => |
| 133 | Effect.gen(function* () { |
| 134 | const resolver = yield* Effect.sync(() => { |
| 135 | const r = new Resolver(); |
| 136 | r.setServers([server]); |
| 137 | return r; |
| 138 | }); |
| 139 | const answers = yield* Effect.tryPromise(() => lookup(resolver, hostname)).pipe( |
| 140 | Effect.orElseSucceed(() => [] as string[]), |
| 141 | ); |
| 142 | if (answers.length === 0) { |
| 143 | return yield* Effect.fail(new NotPublished({ server, hostname })); |
| 144 | } |
| 145 | }).pipe(Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 30 })), |
| 146 | ); |
| 147 | }); |
| 148 | |
| 149 | /** Die defects of a failed exit. */ |
| 150 | const defectsOf = <A, E>(exit: Exit.Exit<A, E>): unknown[] => |
| 151 | Exit.isFailure(exit) |
| 152 | ? exit.cause.reasons.flatMap((reason) => (reason._tag === "Die" ? [reason.defect] : [])) |
| 153 | : []; |
| 154 | |
| 155 | const workerDomainDnsError = (exit: Exit.Exit<unknown, unknown>) => |
| 156 | defectsOf(exit).find( |
| 157 | (defect): defect is Cloudflare.WorkerDomainDnsError => |
| 158 | defect instanceof Cloudflare.WorkerDomainDnsError, |
| 159 | ); |
| 160 | |
| 161 | const tags = [ |
| 162 | "provider:cloudflare", |
| 163 | "provider:cloudflare:workers", |
| 164 | "provider:cloudflare:customhostname", |
| 165 | "live", |
| 166 | ]; |
| 167 | |
| 168 | describe("Cloudflare.Worker domain.dns", { tags }, () => { |
| 169 | test.provider( |
| 170 | "a Cloudflare adapter attaches a native custom domain that serves the Worker", |
| 171 | (stack) => |
| 172 | Effect.gen(function* () { |
| 173 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 174 | yield* stack.destroy(); |
| 175 | |
| 176 | const worker = yield* stack.deploy( |
| 177 | Effect.gen(function* () { |
| 178 | return yield* Cloudflare.Worker("NativeDomainWorker", { |
| 179 | main, |
| 180 | domain: { name: NATIVE_HOSTNAME, dns: Cloudflare.DNS.Adapter() }, |
| 181 | }); |
| 182 | }), |
| 183 | ); |
| 184 | |
| 185 | // The native path: the hostname is the Worker's canonical URL and |
| 186 | // domain output — a SaaS-served domain would keep workers.dev. |
| 187 | expect(worker.url).toBe(`https://${NATIVE_HOSTNAME}`); |
| 188 | expect(worker.domain).toEqual({ |
| 189 | name: NATIVE_HOSTNAME, |
| 190 | aliases: [], |
| 191 | redirects: [], |
| 192 | }); |
| 193 | |
| 194 | // Out-of-band: the custom domain is attached to the script. |
| 195 | const attachments = yield* listAttachments(NATIVE_HOSTNAME); |
| 196 | expect(attachments.map((d) => d.service)).toEqual([worker.workerName]); |
| 197 | |
| 198 | const nameServers = yield* Effect.tryPromise(() => resolveNs(zoneName)).pipe(Effect.orDie); |
| 199 | yield* waitForAuthoritative(nameServers, NATIVE_HOSTNAME, (r, h) => r.resolve4(h)); |
| 200 | yield* expectUrlContains(`https://${NATIVE_HOSTNAME}/`, MARKER, { |
| 201 | label: "native custom domain serves the worker", |
| 202 | timeout: "180 seconds", |
| 203 | }); |
| 204 | |
| 205 | yield* stack.destroy(); |
| 206 | yield* waitUntilGone( |
| 207 | listAttachments(NATIVE_HOSTNAME).pipe( |
| 208 | Effect.flatMap((remaining) => |
| 209 | remaining.length === 0 |
| 210 | ? Effect.void |
| 211 | : Effect.fail(new StillPresent({ what: `domain ${NATIVE_HOSTNAME}` })), |
| 212 | ), |
| 213 | ), |
| 214 | ); |
| 215 | yield* waitForWorkerToBeDeleted(worker.workerName, accountId); |
| 216 | }), |
| 217 | { timeout: 300_000 }, |
| 218 | ); |
| 219 | |
| 220 | test.provider( |
| 221 | "`redirects` with a Route 53 adapter fails the deploy with WorkerDomainDnsError", |
| 222 | (stack) => |
| 223 | Effect.gen(function* () { |
| 224 | yield* stack.destroy(); |
| 225 | const zoneId = yield* resolveZoneId; |
| 226 | |
| 227 | const exit = yield* stack |
| 228 | .deploy( |
| 229 | Effect.gen(function* () { |
| 230 | return yield* Cloudflare.Worker("RedirectsWorker", { |
| 231 | main, |
| 232 | domain: { |
| 233 | name: INVALID_HOSTNAME, |
| 234 | redirects: [`old-${INVALID_HOSTNAME}`], |
| 235 | zoneId, |
| 236 | cnameTarget: ORIGIN_NAME, |
| 237 | dns: AWS.Route53.Adapter(), |
| 238 | }, |
| 239 | }); |
| 240 | }), |
| 241 | ) |
| 242 | .pipe(Effect.exit); |
| 243 | |
| 244 | expect(Exit.isFailure(exit)).toBe(true); |
| 245 | const error = workerDomainDnsError(exit); |
| 246 | expect(error?.workerId).toBe("RedirectsWorker"); |
| 247 | expect(error?.message).toContain("domain.redirects"); |
| 248 | |
| 249 | yield* stack.destroy(); |
| 250 | }), |
| 251 | { timeout: 120_000 }, |
| 252 | ); |
| 253 | |
| 254 | test.provider( |
| 255 | "a missing `cnameTarget` fails the deploy with WorkerDomainDnsError", |
| 256 | (stack) => |
| 257 | Effect.gen(function* () { |
| 258 | yield* stack.destroy(); |
| 259 | const zoneId = yield* resolveZoneId; |
| 260 | |
| 261 | const exit = yield* stack |
| 262 | .deploy( |
| 263 | Effect.gen(function* () { |
| 264 | return yield* Cloudflare.Worker("NoTargetWorker", { |
| 265 | main, |
| 266 | domain: { |
| 267 | name: INVALID_HOSTNAME, |
| 268 | zoneId, |
| 269 | dns: AWS.Route53.Adapter(), |
| 270 | }, |
| 271 | }); |
| 272 | }), |
| 273 | ) |
| 274 | .pipe(Effect.exit); |
| 275 | |
| 276 | expect(Exit.isFailure(exit)).toBe(true); |
| 277 | const error = workerDomainDnsError(exit); |
| 278 | expect(error?.workerId).toBe("NoTargetWorker"); |
| 279 | expect(error?.message).toContain("domain.cnameTarget"); |
| 280 | |
| 281 | yield* stack.destroy(); |
| 282 | }), |
| 283 | { timeout: 120_000 }, |
| 284 | ); |
| 285 | |
| 286 | // Cloudflare for SaaS needs a one-time dashboard enablement (payment on |
| 287 | // file). On a zone without it, creating a custom hostname is rejected |
| 288 | // with the typed `SaasQuotaNotAllocated` (code 1404). On an entitled |
| 289 | // zone the probe hostname is created and removed again. |
| 290 | test.provider( |
| 291 | "custom hostname creation on the test zone is typed (entitlement probe)", |
| 292 | (stack) => |
| 293 | Effect.gen(function* () { |
| 294 | yield* stack.destroy(); |
| 295 | const zoneId = yield* resolveZoneId; |
| 296 | const created = yield* customHostnames |
| 297 | .createCustomHostname({ |
| 298 | zoneId, |
| 299 | hostname: PROBE_HOSTNAME, |
| 300 | ssl: { method: "txt", type: "dv" }, |
| 301 | }) |
| 302 | .pipe( |
| 303 | Effect.map((hostname) => ({ entitled: true, hostname }) as const), |
| 304 | Effect.catchTag("SaasQuotaNotAllocated", (error) => |
| 305 | Effect.succeed({ entitled: false, error } as const), |
| 306 | ), |
| 307 | ); |
| 308 | yield* Effect.logInfo( |
| 309 | created.entitled |
| 310 | ? `Cloudflare for SaaS is enabled on ${zoneName}` |
| 311 | : `Cloudflare for SaaS is not enabled on ${zoneName}: ${created.error.message}`, |
| 312 | ); |
| 313 | if (!created.entitled) { |
| 314 | expect(created.error._tag).toBe("SaasQuotaNotAllocated"); |
| 315 | } else { |
| 316 | yield* customHostnames |
| 317 | .deleteCustomHostname({ |
| 318 | zoneId, |
| 319 | customHostnameId: created.hostname.id, |
| 320 | }) |
| 321 | .pipe(Effect.catchTag("CustomHostnameNotFound", () => Effect.void)); |
| 322 | expect(yield* findCustomHostname(zoneId, PROBE_HOSTNAME)).toBe(undefined); |
| 323 | } |
| 324 | yield* stack.destroy(); |
| 325 | }), |
| 326 | { timeout: 60_000 }, |
| 327 | ); |
| 328 | |
| 329 | test.provider.skipIf(!process.env.CLOUDFLARE_TEST_SAAS)( |
| 330 | "a Worker on a Route 53 hostname serves through Cloudflare for SaaS", |
| 331 | (stack) => |
| 332 | Effect.gen(function* () { |
| 333 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 334 | yield* stack.destroy(); |
| 335 | const zoneId = yield* resolveZoneId; |
| 336 | |
| 337 | const deployed = yield* stack.deploy( |
| 338 | Effect.gen(function* () { |
| 339 | // The SaaS zone's fallback origin: an originless proxied record. |
| 340 | const origin = yield* Cloudflare.DNS.Record("SaasOrigin", { |
| 341 | zoneId, |
| 342 | name: ORIGIN_NAME, |
| 343 | type: "AAAA", |
| 344 | content: "100::", |
| 345 | proxied: true, |
| 346 | }); |
| 347 | const fallback = yield* Cloudflare.CustomHostname.FallbackOrigin("SaasFallback", { |
| 348 | zoneId, |
| 349 | origin: origin.name, |
| 350 | }); |
| 351 | |
| 352 | // A Route 53 zone publicly delegated from the Cloudflare zone: |
| 353 | // the custom hostname's DNS host. |
| 354 | const r53Zone = yield* AWS.Route53.HostedZone("R53Zone", { |
| 355 | name: R53_ZONE_NAME, |
| 356 | forceDestroy: true, |
| 357 | }); |
| 358 | for (const index of [0, 1, 2, 3]) { |
| 359 | yield* Cloudflare.DNS.Record(`R53Delegation${index}`, { |
| 360 | zoneId, |
| 361 | name: R53_ZONE_NAME, |
| 362 | type: "NS", |
| 363 | content: Output.map(r53Zone.nameServers, (nameServers) => nameServers[index]!), |
| 364 | }); |
| 365 | } |
| 366 | |
| 367 | const worker = yield* Cloudflare.Worker("SaasWorker", { |
| 368 | main, |
| 369 | domain: { |
| 370 | name: SAAS_HOSTNAME, |
| 371 | zoneId, |
| 372 | cnameTarget: fallback.origin, |
| 373 | dns: AWS.Route53.Adapter({ hostedZoneId: r53Zone.id }), |
| 374 | }, |
| 375 | }); |
| 376 | return { |
| 377 | workerName: worker.workerName, |
| 378 | hostedZoneId: r53Zone.id, |
| 379 | nameServers: r53Zone.nameServers, |
| 380 | }; |
| 381 | }), |
| 382 | ); |
| 383 | |
| 384 | // Out-of-band: the custom hostname and the SaaS-zone route exist. |
| 385 | const customHostname = yield* findCustomHostname(zoneId, SAAS_HOSTNAME); |
| 386 | expect(customHostname?.hostname).toBe(SAAS_HOSTNAME); |
| 387 | const routes = yield* listWorkerRoutes(zoneId, `${SAAS_HOSTNAME}/*`); |
| 388 | expect(routes.map((route) => route.script)).toEqual([deployed.workerName]); |
| 389 | |
| 390 | // Out-of-band: Route 53 publishes the CNAME to the fallback origin |
| 391 | // and the ownership-verification TXT record. |
| 392 | const { ResourceRecordSets = [] } = yield* route53.listResourceRecordSets({ |
| 393 | HostedZoneId: deployed.hostedZoneId, |
| 394 | }); |
| 395 | const recordSet = (name: string, type: string) => |
| 396 | ResourceRecordSets.find((set) => set.Name === `${name}.` && set.Type === type); |
| 397 | expect( |
| 398 | recordSet(SAAS_HOSTNAME, "CNAME")?.ResourceRecords?.map((record) => record.Value), |
| 399 | ).toEqual([ORIGIN_NAME]); |
| 400 | expect(recordSet(`_cf-custom-hostname.${SAAS_HOSTNAME}`, "TXT")).toBeDefined(); |
| 401 | |
| 402 | // Ownership + DCV complete asynchronously once Route 53 serves the |
| 403 | // TXT records and the CNAME — bounded retry until it serves. |
| 404 | yield* waitForAuthoritative(deployed.nameServers, SAAS_HOSTNAME, (r, h) => |
| 405 | r.resolveCname(h), |
| 406 | ); |
| 407 | yield* expectUrlContains(`https://${SAAS_HOSTNAME}/`, MARKER, { |
| 408 | label: "SaaS custom hostname serves the worker", |
| 409 | timeout: "240 seconds", |
| 410 | }); |
| 411 | |
| 412 | yield* stack.destroy(); |
| 413 | yield* waitUntilGone( |
| 414 | findCustomHostname(zoneId, SAAS_HOSTNAME).pipe( |
| 415 | Effect.flatMap((remaining) => |
| 416 | remaining === undefined |
| 417 | ? Effect.void |
| 418 | : Effect.fail(new StillPresent({ what: `hostname ${SAAS_HOSTNAME}` })), |
| 419 | ), |
| 420 | ), |
| 421 | ); |
| 422 | expect(yield* listWorkerRoutes(zoneId, `${SAAS_HOSTNAME}/*`)).toHaveLength(0); |
| 423 | yield* waitUntilGone( |
| 424 | route53.getHostedZone({ Id: deployed.hostedZoneId }).pipe( |
| 425 | Effect.flatMap(() => Effect.fail(new StillPresent({ what: `zone ${R53_ZONE_NAME}` }))), |
| 426 | Effect.catchTag("NoSuchHostedZone", () => Effect.void), |
| 427 | ), |
| 428 | ); |
| 429 | yield* waitForWorkerToBeDeleted(deployed.workerName, accountId); |
| 430 | }), |
| 431 | { timeout: 600_000 }, |
| 432 | ); |
| 433 | }); |