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

main
ts 401 lines 14.1 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 rules from "@distilled.cloud/cloudflare/rules";
7 import * as rulesets from "@distilled.cloud/cloudflare/rulesets";
8 import * as Output from "alchemy/Output";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import { MinimumLogLevel } from "effect/References";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import { testName } from "../../names.ts";
15 import { expectUrlRedirect, waitForDns } from "../Utils/Http.ts";
16
17 const { test } = Test.make({ providers: Cloudflare.providers() });
18
19 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
20
21 // The scoped API token the test harness mints propagates eventually-
22 // consistently across Cloudflare's edge — ride out 403 blips
23 // (`Forbidden`, declared in the distilled error union) on the test's
24 // own out-of-band verification calls.
25 const getList = (accountId: string, listId: string) =>
26 rules.getList({ accountId, listId }).pipe(
27 Effect.retry({
28 while: (e) => e._tag === "Forbidden",
29 schedule: Schedule.exponential("500 millis"),
30 times: 8,
31 }),
32 );
33
34 const getItems = (accountId: string, listId: string) =>
35 rules.listListItems.items({ accountId, listId }).pipe(
36 Stream.runCollect,
37 Effect.map((chunk) => Array.from(chunk)),
38 Effect.retry({
39 while: (e) => e._tag === "Forbidden",
40 schedule: Schedule.exponential("500 millis"),
41 times: 8,
42 }),
43 );
44
45 // Bulk Redirects live in the account's `http_request_redirect` phase
46 // entrypoint, available on every plan. An entrypoint that never materialized
47 // reads as empty.
48 const getEntrypoint = (accountId: string) =>
49 rulesets.getPhasForAccount({ accountId, rulesetPhase: "http_request_redirect" }).pipe(
50 Effect.retry({
51 while: (e) => e._tag === "Forbidden",
52 schedule: Schedule.exponential("500 millis"),
53 times: 8,
54 }),
55 Effect.map((entrypoint) => ({ rules: entrypoint.rules ?? [] })),
56 Effect.catchTag("RulesetNotFound", () => Effect.succeed({ rules: [] })),
57 );
58
59 const zoneName = "alchemy-test-2.us";
60
61 const expectGone = (accountId: string, listId: string) =>
62 getList(accountId, listId).pipe(
63 Effect.flatMap(() => Effect.fail({ _tag: "ListNotDeleted" } as const)),
64 // A missing list surfaces as `ListNotFound` (Cloudflare error code
65 // 10001) — that's the success condition here.
66 Effect.catchTag("ListNotFound", () => Effect.void),
67 Effect.retry({
68 while: (e) => e._tag === "ListNotDeleted",
69 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
70 }),
71 );
72
73 test.provider(
74 "create and delete an ip list with default name",
75 (stack) =>
76 Effect.gen(function* () {
77 const { accountId } = yield* yield* CloudflareEnvironment;
78
79 yield* stack.destroy();
80
81 const list = yield* stack.deploy(
82 Cloudflare.Rules.List("DefaultList", {
83 kind: "ip",
84 description: "alchemy rules list create test",
85 items: [{ ip: "203.0.113.7", comment: "scanner" }, { ip: "198.51.100.0/24" }],
86 }),
87 );
88
89 expect(list.listId).toBeDefined();
90 expect(list.accountId).toEqual(accountId);
91 expect(list.kind).toEqual("ip");
92 expect(list.description).toEqual("alchemy rules list create test");
93 // List names only allow letters, numbers, and underscores.
94 expect(list.name).toMatch(/^[a-zA-Z0-9_]+$/);
95 expect(list.numItems).toEqual(2);
96
97 const live = yield* getList(accountId, list.listId);
98 expect(live.name).toEqual(list.name);
99 expect(live.kind).toEqual("ip");
100
101 const items = yield* getItems(accountId, list.listId);
102 const ips = items.map((item) => ("ip" in item ? item.ip : undefined)).sort();
103 expect(ips).toEqual(["198.51.100.0/24", "203.0.113.7"]);
104
105 yield* stack.destroy();
106
107 yield* expectGone(accountId, list.listId);
108 }).pipe(logLevel),
109 { tags: ["provider:cloudflare", "provider:cloudflare:rules", "live"] },
110 );
111
112 test.provider(
113 "update description and items in place (same listId)",
114 (stack) =>
115 Effect.gen(function* () {
116 const { accountId } = yield* yield* CloudflareEnvironment;
117
118 yield* stack.destroy();
119
120 const initial = yield* stack.deploy(
121 Cloudflare.Rules.List("UpdateList", {
122 name: testName("alchemy_rules_list_update", "_"),
123 kind: "ip",
124 description: "v1",
125 items: [{ ip: "203.0.113.1" }, { ip: "203.0.113.2" }],
126 }),
127 );
128
129 expect(initial.name).toEqual(testName("alchemy_rules_list_update", "_"));
130 expect(initial.description).toEqual("v1");
131 expect(initial.numItems).toEqual(2);
132
133 const updated = yield* stack.deploy(
134 Cloudflare.Rules.List("UpdateList", {
135 name: testName("alchemy_rules_list_update", "_"),
136 kind: "ip",
137 description: "v2",
138 items: [{ ip: "203.0.113.2", comment: "kept" }, { ip: "192.0.2.0/24" }],
139 }),
140 );
141
142 // Same list mutated in place — not a replacement.
143 expect(updated.listId).toEqual(initial.listId);
144 expect(updated.description).toEqual("v2");
145 expect(updated.numItems).toEqual(2);
146
147 const items = yield* getItems(accountId, updated.listId);
148 const ips = items.map((item) => ("ip" in item ? item.ip : undefined)).sort();
149 expect(ips).toEqual(["192.0.2.0/24", "203.0.113.2"]);
150 const kept = items.find((item) => "ip" in item && item.ip === "203.0.113.2");
151 expect(kept && "comment" in kept ? kept.comment : undefined).toEqual("kept");
152
153 // Redeploying identical props is a no-op (still the same list).
154 const noop = yield* stack.deploy(
155 Cloudflare.Rules.List("UpdateList", {
156 name: testName("alchemy_rules_list_update", "_"),
157 kind: "ip",
158 description: "v2",
159 items: [{ ip: "203.0.113.2", comment: "kept" }, { ip: "192.0.2.0/24" }],
160 }),
161 );
162 expect(noop.listId).toEqual(initial.listId);
163
164 yield* stack.destroy();
165
166 yield* expectGone(accountId, initial.listId);
167 }).pipe(logLevel),
168 { tags: ["provider:cloudflare", "provider:cloudflare:rules", "live"] },
169 );
170
171 test.provider(
172 "changing kind replaces the list",
173 (stack) =>
174 Effect.gen(function* () {
175 const { accountId } = yield* yield* CloudflareEnvironment;
176
177 yield* stack.destroy();
178
179 const ipList = yield* stack.deploy(
180 Cloudflare.Rules.List("ReplaceList", {
181 name: testName("alchemy_rules_list_replace", "_"),
182 kind: "ip",
183 items: [{ ip: "203.0.113.9" }],
184 }),
185 );
186 expect(ipList.kind).toEqual("ip");
187
188 const hostnameList = yield* stack.deploy(
189 Cloudflare.Rules.List("ReplaceList", {
190 name: testName("alchemy_rules_list_replace", "_"),
191 kind: "hostname",
192 items: [{ hostname: { urlHostname: "example.com" } }],
193 }),
194 );
195
196 // Kind is immutable — the engine must replace the list.
197 expect(hostnameList.listId).not.toEqual(ipList.listId);
198 expect(hostnameList.kind).toEqual("hostname");
199
200 // The old list is gone, the new one is live.
201 yield* expectGone(accountId, ipList.listId);
202 const live = yield* getList(accountId, hostnameList.listId);
203 expect(live.kind).toEqual("hostname");
204
205 yield* stack.destroy();
206
207 yield* expectGone(accountId, hostnameList.listId);
208 }).pipe(logLevel),
209 { tags: ["provider:cloudflare", "provider:cloudflare:rules", "live"] },
210 );
211
212 test.provider(
213 "recreates after out-of-band delete",
214 (stack) =>
215 Effect.gen(function* () {
216 const { accountId } = yield* yield* CloudflareEnvironment;
217
218 yield* stack.destroy();
219
220 const list = yield* stack.deploy(
221 Cloudflare.Rules.List("HealList", {
222 name: testName("alchemy_rules_list_heal", "_"),
223 kind: "ip",
224 items: [{ ip: "203.0.113.11" }],
225 }),
226 );
227
228 // Delete the list out-of-band. A redeploy with identical props is a
229 // planner no-op, so change a prop to force reconcile — it must observe
230 // the list as missing and recreate it instead of failing on a 404.
231 yield* rules.deleteList({ accountId, listId: list.listId }).pipe(
232 Effect.retry({
233 while: (e) => e._tag === "Forbidden",
234 schedule: Schedule.exponential("500 millis"),
235 times: 8,
236 }),
237 );
238
239 const healed = yield* stack.deploy(
240 Cloudflare.Rules.List("HealList", {
241 name: testName("alchemy_rules_list_heal", "_"),
242 kind: "ip",
243 description: "healed",
244 items: [{ ip: "203.0.113.11" }],
245 }),
246 );
247
248 expect(healed.listId).not.toEqual(list.listId);
249 expect(healed.description).toEqual("healed");
250 const live = yield* getList(accountId, healed.listId);
251 expect(live.name).toEqual(testName("alchemy_rules_list_heal", "_"));
252
253 yield* stack.destroy();
254
255 yield* expectGone(accountId, healed.listId);
256 }).pipe(logLevel),
257 { tags: ["provider:cloudflare", "provider:cloudflare:rules", "live"] },
258 );
259
260 test.provider(
261 "adopts an existing list with the same name",
262 (stack) =>
263 Effect.gen(function* () {
264 const { accountId } = yield* yield* CloudflareEnvironment;
265
266 yield* stack.destroy();
267
268 // Create a list out-of-band with the exact name the resource will use —
269 // the create conflict (`ListAlreadyExists`, code 10021) must resolve by
270 // adopting the existing list.
271 const preexisting = yield* rules
272 .createList({ accountId, name: testName("alchemy_rules_list_adopt", "_"), kind: "ip" })
273 .pipe(
274 Effect.retry({
275 while: (e) => e._tag === "Forbidden",
276 schedule: Schedule.exponential("500 millis"),
277 times: 8,
278 }),
279 Effect.catchTag("ListAlreadyExists", () =>
280 rules.listLists.items({ accountId }).pipe(
281 Stream.filter((l) => l.name === testName("alchemy_rules_list_adopt", "_")),
282 Stream.runHead,
283 Effect.map(Option.getOrThrow),
284 ),
285 ),
286 );
287
288 const adopted = yield* stack.deploy(
289 Cloudflare.Rules.List("AdoptList", {
290 name: testName("alchemy_rules_list_adopt", "_"),
291 kind: "ip",
292 description: "adopted",
293 items: [{ ip: "203.0.113.21" }],
294 }),
295 );
296
297 expect(adopted.listId).toEqual(preexisting.id);
298 expect(adopted.description).toEqual("adopted");
299 expect(adopted.numItems).toEqual(1);
300
301 yield* stack.destroy();
302
303 yield* expectGone(accountId, preexisting.id);
304 }).pipe(logLevel),
305 { tags: ["provider:cloudflare", "provider:cloudflare:rules", "live"] },
306 );
307
308 test.provider(
309 "redirect list drives a Bulk Redirect rule",
310 (stack) =>
311 Effect.gen(function* () {
312 const { accountId } = yield* yield* CloudflareEnvironment;
313 const zone = yield* findZoneByName({ accountId, name: zoneName });
314 if (!zone) return yield* Effect.die(`test zone ${zoneName} not found`);
315 const hostname = `bulk-redirect-${stack.stage.toLowerCase().replace(/[^a-z0-9-]/g, "-")}.${zoneName}`;
316
317 yield* stack.destroy();
318
319 const bulkRedirects = (items: Cloudflare.Rules.ListItem[]) =>
320 Effect.gen(function* () {
321 yield* Cloudflare.DNS.Record("BulkRedirectHost", {
322 zoneId: zone.id,
323 name: hostname,
324 type: "A",
325 content: "192.0.2.1",
326 proxied: true,
327 });
328 const list = yield* Cloudflare.Rules.List("RetiredSlugs", {
329 kind: "redirect",
330 items,
331 });
332 const entrypoint = yield* Cloudflare.Ruleset.AccountEntrypoint("BulkRedirects", {
333 phase: "http_request_redirect",
334 rules: [
335 {
336 ref: "retired_slugs",
337 expression: Output.interpolate`http.request.full_uri in $${list.name}`,
338 action: "redirect",
339 actionParameters: {
340 fromList: { name: list.name, key: "http.request.full_uri" },
341 },
342 },
343 ],
344 });
345 return { list, entrypoint };
346 });
347
348 const redirect = (from: string, to: string): Cloudflare.Rules.ListItem => ({
349 redirect: {
350 sourceUrl: `${hostname}/${from}`,
351 targetUrl: `https://${hostname}/${to}`,
352 statusCode: 301,
353 preserveQueryString: true,
354 },
355 });
356
357 const v1 = yield* stack.deploy(
358 bulkRedirects([redirect("old-a", "new-a"), redirect("old-b", "new-b")]),
359 );
360
361 expect(v1.list.numItems).toEqual(2);
362 const live = yield* getEntrypoint(accountId);
363 expect(live.rules).toHaveLength(1);
364 expect(live.rules[0]).toMatchObject({
365 action: "redirect",
366 actionParameters: {
367 fromList: { name: v1.list.name, key: "http.request.full_uri" },
368 },
369 });
370
371 // The proxied record is brand new; confirm it on the authoritative
372 // nameservers before the first fetch so no resolver caches NXDOMAIN.
373 yield* waitForDns(hostname);
374 yield* expectUrlRedirect(`https://${hostname}/old-a`, "/new-a");
375 yield* expectUrlRedirect(`https://${hostname}/old-b`, "/new-b");
376
377 // Adding a mapping only touches the list — the single rule is unchanged.
378 const v2 = yield* stack.deploy(
379 bulkRedirects([
380 redirect("old-a", "new-a"),
381 redirect("old-b", "new-b"),
382 redirect("old-c", "new-c"),
383 ]),
384 );
385 expect(v2.list.listId).toEqual(v1.list.listId);
386 expect(v2.list.numItems).toEqual(3);
387 expect(v2.entrypoint.rules).toHaveLength(1);
388
389 yield* expectUrlRedirect(`https://${hostname}/old-c`, "/new-c");
390
391 yield* stack.destroy();
392
393 yield* expectGone(accountId, v1.list.listId);
394 const after = yield* getEntrypoint(accountId);
395 expect(after.rules).toHaveLength(0);
396 }).pipe(logLevel),
397 {
398 tags: ["provider:cloudflare", "provider:cloudflare:rules", "live"],
399 timeout: 300_000,
400 },
401 );