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

main
ts 288 lines 11.2 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as customHostnames from "@distilled.cloud/cloudflare/custom-hostnames";
7 import { adopt } from "alchemy/AdoptPolicy";
8 import * as Provider from "alchemy/Provider";
9 import * as Effect from "effect/Effect";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { testName } from "../../names.ts";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 // Cloudflare for SaaS (SSL for SaaS) is NOT provisioned on the test account:
18 // every custom-hostnames API call fails with `SaasQuotaNotAllocated`
19 // (code 1404): "No quota has been allocated for this zone or for this
20 // account. If you're already a paid SSL for SaaS customer, please contact
21 // your Customer Success Manager for additional provisioning. ..."
22 // Enabling Cloudflare for SaaS is a one-time dashboard action (SSL/TLS →
23 // Custom Hostnames → Enable) with no public API — verified directly against
24 // the API: POST /custom_hostnames and PUT /custom_hostnames/fallback_origin
25 // are both rejected with the same entitlement errors. Set
26 // CLOUDFLARE_SAAS_ENABLED=1 once the zone is provisioned to run these tests.
27 const saasEnabled = !!process.env.CLOUDFLARE_SAAS_ENABLED;
28 const testSaas = test.provider.skipIf(!saasEnabled);
29
30 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
31
32 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
33
34 // Deterministic per-test hostnames on a domain we do not control — the
35 // hostnames stay `pending` forever, which is fine: CRUD is still fully
36 // exercisable. Each test owns a disjoint hostname so reruns and parallel
37 // runs never collide (never derive names from Date.now()/random).
38 const HOST_DEFAULT = `${testName("alchemy-ch-default")}.alchemy-saas-example.com`;
39 const HOST_UPDATE = `${testName("alchemy-ch-update")}.alchemy-saas-example.com`;
40 const HOST_REPLACE_A = `${testName("alchemy-ch-replace-a")}.alchemy-saas-example.com`;
41 const HOST_REPLACE_B = `${testName("alchemy-ch-replace-b")}.alchemy-saas-example.com`;
42
43 const resolveZoneId = Effect.gen(function* () {
44 const { accountId } = yield* yield* CloudflareEnvironment;
45 const zone = yield* findZoneByName({ accountId, name: zoneName });
46 if (!zone) {
47 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
48 }
49 return zone.id;
50 });
51
52 // The scoped API token the test harness mints propagates eventually-
53 // consistently across Cloudflare's edge — a fresh token intermittently 403s
54 // (typed as `Forbidden` in the distilled unions). Ride out the blips on the
55 // test's own out-of-band verification calls. Inlined at each call site so the
56 // retry predicate is checked against the operation's inferred error union.
57 const forbiddenBlips = Schedule.exponential("500 millis");
58
59 const findByHostname = (zoneId: string, hostname: string) =>
60 customHostnames.listCustomHostnames.items({ zoneId, hostname: { contain: hostname } }).pipe(
61 Stream.filter((h) => h.hostname === hostname),
62 Stream.runCollect,
63 Effect.map((chunk) => Array.from(chunk)[0]),
64 Effect.retry({ while: (e) => e._tag === "Forbidden", schedule: forbiddenBlips, times: 8 }),
65 );
66
67 const getHostname = (zoneId: string, customHostnameId: string) =>
68 customHostnames
69 .getCustomHostname({ zoneId, customHostnameId })
70 .pipe(
71 Effect.retry({ while: (e) => e._tag === "Forbidden", schedule: forbiddenBlips, times: 8 }),
72 );
73
74 // Typed entitlement probe: every custom-hostnames call on an unprovisioned
75 // zone is rejected with `SaasQuotaNotAllocated` (code 1404). When the suite
76 // is enabled but the zone still lacks the entitlement, fail fast with a
77 // clear message instead of surfacing raw entitlement errors mid-deploy.
78 const probeSaasEntitlement = (zoneId: string) =>
79 customHostnames.listCustomHostnames.items({ zoneId }).pipe(
80 Stream.runDrain,
81 Effect.retry({ while: (e) => e._tag === "Forbidden", schedule: forbiddenBlips, times: 8 }),
82 Effect.catchTag("SaasQuotaNotAllocated", (e) =>
83 Effect.die(
84 new Error(
85 `Cloudflare for SaaS is not provisioned on zone "${zoneName}" — ` +
86 `unset CLOUDFLARE_SAAS_ENABLED or enable SSL for SaaS first: ${e.message}`,
87 ),
88 ),
89 ),
90 );
91
92 testSaas(
93 "create and delete a custom hostname with default ssl",
94 (stack) =>
95 Effect.gen(function* () {
96 const zoneId = yield* resolveZoneId;
97 yield* probeSaasEntitlement(zoneId);
98
99 yield* stack.destroy();
100
101 const hostname = yield* stack.deploy(
102 Effect.gen(function* () {
103 return yield* Cloudflare.CustomHostname.CustomHostname("Default", {
104 zoneId,
105 hostname: HOST_DEFAULT,
106 }).pipe(adopt(true));
107 }),
108 );
109
110 expect(hostname.customHostnameId).toBeDefined();
111 expect(hostname.zoneId).toEqual(zoneId);
112 expect(hostname.hostname).toEqual(HOST_DEFAULT);
113 // We don't control the domain, so activation never completes.
114 expect(hostname.status).toBeDefined();
115
116 const live = yield* getHostname(zoneId, hostname.customHostnameId);
117 expect(live.id).toEqual(hostname.customHostnameId);
118 expect(live.hostname).toEqual(HOST_DEFAULT);
119 expect(live.ssl?.method).toEqual("txt");
120 expect(live.ssl?.type).toEqual("dv");
121
122 yield* stack.destroy();
123
124 const gone = yield* findByHostname(zoneId, HOST_DEFAULT);
125 expect(gone).toBeUndefined();
126 }).pipe(logLevel),
127 { tags: ["provider:cloudflare", "provider:cloudflare:customhostname", "live"], timeout: 120_000 },
128 );
129
130 testSaas(
131 "updating ssl method patches in place",
132 (stack) =>
133 Effect.gen(function* () {
134 const zoneId = yield* resolveZoneId;
135 yield* probeSaasEntitlement(zoneId);
136
137 yield* stack.destroy();
138
139 const initial = yield* stack.deploy(
140 Effect.gen(function* () {
141 return yield* Cloudflare.CustomHostname.CustomHostname("Update", {
142 zoneId,
143 hostname: HOST_UPDATE,
144 ssl: { method: "txt", type: "dv" },
145 }).pipe(adopt(true));
146 }),
147 );
148
149 expect(initial.customHostnameId).toBeDefined();
150
151 const updated = yield* stack.deploy(
152 Effect.gen(function* () {
153 return yield* Cloudflare.CustomHostname.CustomHostname("Update", {
154 zoneId,
155 hostname: HOST_UPDATE,
156 ssl: { method: "http", type: "dv" },
157 }).pipe(adopt(true));
158 }),
159 );
160
161 // Same custom hostname patched in place — not a replacement.
162 expect(updated.customHostnameId).toEqual(initial.customHostnameId);
163
164 const live = yield* getHostname(zoneId, updated.customHostnameId);
165 expect(live.ssl?.method).toEqual("http");
166
167 // Re-deploying the same desired state is a no-op (does not error or
168 // trigger reissuance).
169 const again = yield* stack.deploy(
170 Effect.gen(function* () {
171 return yield* Cloudflare.CustomHostname.CustomHostname("Update", {
172 zoneId,
173 hostname: HOST_UPDATE,
174 ssl: { method: "http", type: "dv" },
175 }).pipe(adopt(true));
176 }),
177 );
178 expect(again.customHostnameId).toEqual(initial.customHostnameId);
179
180 yield* stack.destroy();
181 }).pipe(logLevel),
182 { tags: ["provider:cloudflare", "provider:cloudflare:customhostname", "live"], timeout: 120_000 },
183 );
184
185 // `list()` fans out over every zone in the account and skips zones without
186 // the SaaS entitlement (typed `SaasQuotaNotAllocated`/`Forbidden`). Without
187 // the entitlement on any zone the result is a well-typed empty array — this
188 // read-only assertion runs ungated and proves the per-zone skip path.
189 test.provider(
190 "list returns a well-typed array of custom hostnames",
191 (stack) =>
192 Effect.gen(function* () {
193 yield* stack.destroy();
194
195 const provider = yield* Provider.findProvider(Cloudflare.CustomHostname.CustomHostname);
196 const all = yield* provider.list();
197
198 expect(Array.isArray(all)).toBe(true);
199 for (const item of all) {
200 expect(typeof item.customHostnameId).toBe("string");
201 expect(typeof item.zoneId).toBe("string");
202 expect(typeof item.hostname).toBe("string");
203 }
204
205 yield* stack.destroy();
206 }).pipe(logLevel),
207 { tags: ["provider:cloudflare", "provider:cloudflare:customhostname", "live"] },
208 );
209
210 // Entitlement-gated: deploy a custom hostname and assert `list()` enumerates
211 // it. Skipped unless CLOUDFLARE_SAAS_ENABLED=1 because Cloudflare for SaaS is
212 // not provisioned on the test account (every create is rejected with
213 // `SaasQuotaNotAllocated`, code 1404).
214 testSaas(
215 "list enumerates the deployed custom hostname",
216 (stack) =>
217 Effect.gen(function* () {
218 const zoneId = yield* resolveZoneId;
219 yield* probeSaasEntitlement(zoneId);
220
221 yield* stack.destroy();
222
223 const deployed = yield* stack.deploy(
224 Effect.gen(function* () {
225 return yield* Cloudflare.CustomHostname.CustomHostname("ListResource", {
226 zoneId,
227 hostname: HOST_DEFAULT,
228 }).pipe(adopt(true));
229 }),
230 );
231
232 const provider = yield* Provider.findProvider(Cloudflare.CustomHostname.CustomHostname);
233 const all = yield* provider.list();
234
235 expect(all.some((h) => h.customHostnameId === deployed.customHostnameId)).toBe(true);
236
237 yield* stack.destroy();
238 }).pipe(logLevel),
239 { tags: ["provider:cloudflare", "provider:cloudflare:customhostname", "live"], timeout: 120_000 },
240 );
241
242 testSaas(
243 "changing the hostname triggers replacement",
244 (stack) =>
245 Effect.gen(function* () {
246 const zoneId = yield* resolveZoneId;
247 yield* probeSaasEntitlement(zoneId);
248
249 yield* stack.destroy();
250
251 const initial = yield* stack.deploy(
252 Effect.gen(function* () {
253 return yield* Cloudflare.CustomHostname.CustomHostname("Replace", {
254 zoneId,
255 hostname: HOST_REPLACE_A,
256 }).pipe(adopt(true));
257 }),
258 );
259
260 expect(initial.hostname).toEqual(HOST_REPLACE_A);
261
262 const replaced = yield* stack.deploy(
263 Effect.gen(function* () {
264 return yield* Cloudflare.CustomHostname.CustomHostname("Replace", {
265 zoneId,
266 hostname: HOST_REPLACE_B,
267 }).pipe(adopt(true));
268 }),
269 );
270
271 // hostname is the resource's identity — a new physical hostname exists.
272 expect(replaced.customHostnameId).not.toEqual(initial.customHostnameId);
273 expect(replaced.hostname).toEqual(HOST_REPLACE_B);
274
275 // The old hostname was deleted as part of the replacement.
276 const oldHostname = yield* findByHostname(zoneId, HOST_REPLACE_A);
277 expect(oldHostname).toBeUndefined();
278
279 const live = yield* getHostname(zoneId, replaced.customHostnameId);
280 expect(live.hostname).toEqual(HOST_REPLACE_B);
281
282 yield* stack.destroy();
283
284 const gone = yield* findByHostname(zoneId, HOST_REPLACE_B);
285 expect(gone).toBeUndefined();
286 }).pipe(logLevel),
287 { tags: ["provider:cloudflare", "provider:cloudflare:customhostname", "live"], timeout: 180_000 },
288 );