@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 228 lines 8.72 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 firewall from "@distilled.cloud/cloudflare/firewall";
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
14 const { test } = Test.make({ providers: Cloudflare.providers() });
15
16 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
17
18 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
19
20 // Deterministic per-test URL patterns. A lockdown rule's URL set is its
21 // identity within a zone (duplicates are rejected), so each test owns
22 // disjoint paths and the same values are reused on every run (never
23 // Date.now()/random). Zone Lockdown quota on Pro is 3 rules — each test
24 // holds at most one rule at a time.
25 const URL_LIFECYCLE_V1 = `${zoneName}/alchemy-lockdown-lifecycle*`;
26 const URL_LIFECYCLE_V2 = `${zoneName}/alchemy-lockdown-lifecycle-v2*`;
27 const IP_V1 = "198.51.100.111";
28 const RANGE_V2 = "203.0.113.0/24";
29
30 const URL_LIST = `${zoneName}/alchemy-lockdown-list*`;
31 const IP_LIST = "198.51.100.222";
32
33 const resolveZoneId = Effect.gen(function* () {
34 const { accountId } = yield* yield* CloudflareEnvironment;
35 const zone = yield* findZoneByName({ accountId, name: zoneName });
36 if (!zone) {
37 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
38 }
39 return zone.id;
40 });
41
42 // The scoped API token the test harness mints propagates eventually-
43 // consistently across Cloudflare's edge — ride out 403 blips (`Forbidden`,
44 // declared in the distilled error union via patches) on the test's own
45 // out-of-band verification calls.
46 const forbiddenRetry = {
47 while: (e: { _tag: string }) => e._tag === "Forbidden",
48 schedule: Schedule.exponential("500 millis"),
49 times: 8,
50 } as const;
51
52 const getLockdown = (zoneId: string, lockdownId: string) =>
53 firewall.getLockdown({ zoneId, lockDownsId: lockdownId }).pipe(Effect.retry(forbiddenRetry));
54
55 // List every lockdown whose URL set intersects the given urls — used both
56 // for assertions and to purge leftovers from interrupted runs so each test
57 // starts from a clean slate (a leaked rule would surface as
58 // Unowned/duplicate because the URL set is identity).
59 const listByUrls = (zoneId: string, urls: string[]) =>
60 firewall.listLockdowns.items({ zoneId }).pipe(
61 Stream.filter((r) => r.urls.some((u) => urls.includes(u))),
62 Stream.runCollect,
63 Effect.map((chunk) => Array.from(chunk)),
64 Effect.retry(forbiddenRetry),
65 );
66
67 const purgeLockdowns = (zoneId: string, urls: string[]) =>
68 listByUrls(zoneId, urls).pipe(
69 Effect.flatMap(
70 Effect.forEach((r) =>
71 firewall.deleteLockdown({ zoneId, lockDownsId: r.id }).pipe(
72 Effect.retry(forbiddenRetry),
73 Effect.catchTag("LockdownNotFound", () => Effect.void),
74 ),
75 ),
76 ),
77 );
78
79 // Poll until the rule is gone — a missing rule surfaces as the typed
80 // `LockdownNotFound` (Cloudflare code 10001, zonelockdown.api.not_found).
81 const expectLockdownGone = (zoneId: string, lockdownId: string) =>
82 getLockdown(zoneId, lockdownId).pipe(
83 Effect.flatMap(() => Effect.fail({ _tag: "LockdownNotDeleted" } as const)),
84 Effect.catchTag("LockdownNotFound", () => Effect.void),
85 Effect.retry({
86 while: (e) => e._tag === "LockdownNotDeleted",
87 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
88 }),
89 );
90
91 test.provider(
92 "create, update urls/configurations/description/paused in place, destroy",
93 (stack) =>
94 Effect.gen(function* () {
95 const zoneId = yield* resolveZoneId;
96
97 yield* stack.destroy();
98 yield* purgeLockdowns(zoneId, [URL_LIFECYCLE_V1, URL_LIFECYCLE_V2]);
99
100 const initial = yield* stack.deploy(
101 Effect.gen(function* () {
102 return yield* Cloudflare.Firewall.Lockdown("LifecycleLockdown", {
103 zoneId,
104 urls: [URL_LIFECYCLE_V1],
105 configurations: [{ target: "ip", value: IP_V1 }],
106 description: "alchemy lockdown test (v1)",
107 }).pipe(adopt(true));
108 }),
109 );
110
111 expect(initial.lockdownId).toBeDefined();
112 expect(initial.zoneId).toEqual(zoneId);
113 expect(initial.urls).toEqual([URL_LIFECYCLE_V1]);
114 expect(initial.configurations).toEqual([{ target: "ip", value: IP_V1 }]);
115 expect(initial.description).toEqual("alchemy lockdown test (v1)");
116 expect(initial.paused).toEqual(false);
117
118 const live = yield* getLockdown(zoneId, initial.lockdownId);
119 expect(live.id).toEqual(initial.lockdownId);
120 expect(live.urls).toEqual([URL_LIFECYCLE_V1]);
121 expect(live.configurations).toEqual([{ target: "ip", value: IP_V1 }]);
122
123 // Update every mutable aspect in one PUT: add a second url, add an
124 // ip_range allow entry, change the description, and pause the rule.
125 const updated = yield* stack.deploy(
126 Effect.gen(function* () {
127 return yield* Cloudflare.Firewall.Lockdown("LifecycleLockdown", {
128 zoneId,
129 urls: [URL_LIFECYCLE_V1, URL_LIFECYCLE_V2],
130 configurations: [
131 { target: "ip", value: IP_V1 },
132 { target: "ip_range", value: RANGE_V2 },
133 ],
134 description: "alchemy lockdown test (v2)",
135 paused: true,
136 }).pipe(adopt(true));
137 }),
138 );
139
140 // Same rule updated in place — not a replacement.
141 expect(updated.lockdownId).toEqual(initial.lockdownId);
142 expect([...updated.urls].sort()).toEqual([URL_LIFECYCLE_V1, URL_LIFECYCLE_V2].sort());
143 expect(updated.configurations).toHaveLength(2);
144 expect(updated.description).toEqual("alchemy lockdown test (v2)");
145 expect(updated.paused).toEqual(true);
146
147 const liveUpdated = yield* getLockdown(zoneId, updated.lockdownId);
148 expect([...liveUpdated.urls].sort()).toEqual([URL_LIFECYCLE_V1, URL_LIFECYCLE_V2].sort());
149 expect(liveUpdated.configurations).toHaveLength(2);
150 expect(liveUpdated.description).toEqual("alchemy lockdown test (v2)");
151 expect(liveUpdated.paused).toEqual(true);
152
153 // Redeploying identical props is a no-op (still the same rule).
154 const noop = yield* stack.deploy(
155 Effect.gen(function* () {
156 return yield* Cloudflare.Firewall.Lockdown("LifecycleLockdown", {
157 zoneId,
158 urls: [URL_LIFECYCLE_V1, URL_LIFECYCLE_V2],
159 configurations: [
160 { target: "ip", value: IP_V1 },
161 { target: "ip_range", value: RANGE_V2 },
162 ],
163 description: "alchemy lockdown test (v2)",
164 paused: true,
165 }).pipe(adopt(true));
166 }),
167 );
168 expect(noop.lockdownId).toEqual(initial.lockdownId);
169
170 yield* stack.destroy();
171
172 yield* expectLockdownGone(zoneId, initial.lockdownId);
173 }).pipe(logLevel),
174 {
175 tags: [
176 "provider:cloudflare",
177 "provider:cloudflare:firewall",
178 "provider:cloudflare:zone",
179 "live",
180 ],
181 },
182 );
183
184 // Canonical `list()` test (zone-scoped collection): `list()` fans out over
185 // every zone via `listAllZones`, exhaustively paginates each zone's lockdown
186 // rules, and hydrates them into the `read` Attributes shape. Deploy a rule and
187 // assert it appears in the enumerated result.
188 test.provider(
189 "list enumerates the deployed lockdown rule",
190 (stack) =>
191 Effect.gen(function* () {
192 const zoneId = yield* resolveZoneId;
193
194 yield* stack.destroy();
195 yield* purgeLockdowns(zoneId, [URL_LIST]);
196
197 const deployed = yield* stack.deploy(
198 Effect.gen(function* () {
199 return yield* Cloudflare.Firewall.Lockdown("ListLockdown", {
200 zoneId,
201 urls: [URL_LIST],
202 configurations: [{ target: "ip", value: IP_LIST }],
203 description: "alchemy lockdown list test",
204 }).pipe(adopt(true));
205 }),
206 );
207
208 const provider = yield* Provider.findProvider(Cloudflare.Firewall.Lockdown);
209 const all = yield* provider.list();
210
211 expect(all.some((r) => r.lockdownId === deployed.lockdownId)).toBe(true);
212 const found = all.find((r) => r.lockdownId === deployed.lockdownId);
213 expect(found?.zoneId).toEqual(zoneId);
214 expect(found?.urls).toEqual([URL_LIST]);
215
216 yield* stack.destroy();
217
218 yield* expectLockdownGone(zoneId, deployed.lockdownId);
219 }).pipe(logLevel),
220 {
221 tags: [
222 "provider:cloudflare",
223 "provider:cloudflare:firewall",
224 "provider:cloudflare:zone",
225 "live",
226 ],
227 },
228 );