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

main
ts 318 lines 10.7 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import OwnedAccessWorker from "./fixtures/access-owned-worker.ts";
12 import SecondAccessWorker from "./fixtures/access-worker-b.ts";
13 import AccessProtectedWorker, { App } from "./fixtures/access-worker.ts";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 class NotYetProtected extends Data.TaggedError("NotYetProtected")<{
20 status: number;
21 location: string | null;
22 bodyExcerpt: string;
23 }> {}
24
25 /**
26 * Probe `url` without following redirects until Cloudflare Access
27 * intercepts it — a 302 to the team's `cloudflareaccess.com` login page.
28 * Freshly-deployed workers.dev URLs 404/530 briefly and then serve the
29 * open worker until the Access policy propagates, so every non-intercepted
30 * response is retried.
31 */
32 const expectAccessLoginRedirect = (url: string) =>
33 Effect.gen(function* () {
34 const probe = Effect.tryPromise({
35 try: async (signal) => {
36 const res = await fetch(url, {
37 signal,
38 redirect: "manual",
39 cache: "no-store",
40 });
41 const location = res.headers.get("location");
42 if (res.status === 302 && location !== null && location.includes("cloudflareaccess.com")) {
43 return location;
44 }
45 const body = await res.text();
46 throw new NotYetProtected({
47 status: res.status,
48 location,
49 bodyExcerpt: body.slice(0, 200),
50 });
51 },
52 catch: (e) =>
53 e instanceof NotYetProtected
54 ? e
55 : new NotYetProtected({
56 status: 0,
57 location: null,
58 bodyExcerpt: e instanceof Error ? e.message : String(e),
59 }),
60 });
61 return yield* probe.pipe(
62 Effect.retry({
63 while: (e) => e._tag === "NotYetProtected",
64 schedule: Schedule.max([
65 Schedule.min([Schedule.exponential("1 second", 1.5), Schedule.spaced("5 seconds")]),
66 Schedule.recurs(24),
67 ]),
68 }),
69 );
70 });
71
72 /** Structural view of the live application for out-of-band assertions. */
73 interface LiveApp {
74 destinations?: ReadonlyArray<{
75 type?: string | null;
76 workerId?: string | null;
77 }> | null;
78 policies?: ReadonlyArray<{
79 id?: string | null;
80 decision?: string | null;
81 reusable?: boolean | null;
82 }> | null;
83 }
84
85 test.provider(
86 "the access prop enrolls a Worker into an Access application with inline policies",
87 (stack) =>
88 Effect.gen(function* () {
89 const { accountId } = yield* yield* CloudflareEnvironment;
90
91 yield* stack.destroy();
92
93 const deployStack = Effect.gen(function* () {
94 const worker = yield* AccessProtectedWorker;
95 const app = yield* App;
96 return { worker, app };
97 });
98
99 const { worker, app } = yield* stack.deploy(deployStack);
100
101 // The application carries the inline (application-owned) policy.
102 expect(app.applicationId).toBeDefined();
103 expect(app.aud.length).toBeGreaterThan(0);
104 const live = (yield* zeroTrust.getAccessApplicationForAccount({
105 accountId,
106 appId: app.applicationId,
107 })) as unknown as LiveApp;
108 expect(live.policies?.length).toBe(1);
109 expect(live.policies![0].decision).toBe("allow");
110 expect(live.policies![0].reusable).toBe(false);
111 const inlinePolicyId = live.policies![0].id;
112 expect(inlinePolicyId).toBeDefined();
113
114 // The Worker enrolled itself: worker + preview destinations keyed by
115 // its immutable script id, contributed through the application's
116 // binding contract.
117 expect(worker.workerId).toBeDefined();
118 expect(app.destinations).toEqual(
119 expect.arrayContaining([
120 expect.objectContaining({
121 type: "worker",
122 workerId: worker.workerId,
123 }),
124 ]),
125 );
126 expect(live.destinations).toEqual(
127 expect.arrayContaining([
128 expect.objectContaining({
129 type: "worker",
130 workerId: worker.workerId,
131 }),
132 expect.objectContaining({
133 type: "preview_worker",
134 workerId: worker.workerId,
135 }),
136 ]),
137 );
138
139 // Unauthenticated requests are redirected to the Access login page
140 // instead of reaching the worker.
141 const location = yield* expectAccessLoginRedirect(worker.url!);
142 expect(location).toContain("cloudflareaccess.com");
143
144 // Idempotence: a second deploy must not churn the inline policy (an
145 // id-less inline item in an update PUT would mint a fresh policy) or
146 // duplicate the destinations.
147 yield* stack.deploy(deployStack);
148 const liveAfter = (yield* zeroTrust.getAccessApplicationForAccount({
149 accountId,
150 appId: app.applicationId,
151 })) as unknown as LiveApp;
152 expect(liveAfter.policies?.length).toBe(1);
153 expect(liveAfter.policies![0].id).toBe(inlinePolicyId);
154 expect(
155 (liveAfter.destinations ?? []).filter((d) => d.workerId === worker.workerId),
156 ).toHaveLength(2);
157
158 yield* stack.destroy();
159
160 // The application (and its inline policy with it) is gone.
161 const gone = yield* zeroTrust
162 .getAccessApplicationForAccount({ accountId, appId: app.applicationId })
163 .pipe(
164 Effect.map(() => "still-exists" as const),
165 Effect.catchTag("AccessApplicationNotFound", () => Effect.succeed("gone" as const)),
166 );
167 expect(gone).toBe("gone");
168 }).pipe(logLevel),
169 {
170 tags: [
171 "provider:cloudflare",
172 "provider:cloudflare:access",
173 "provider:cloudflare:worker",
174 "live",
175 ],
176 timeout: 300_000,
177 },
178 );
179
180 /** Find a live application by its exact display name, or undefined. */
181 const findAppByName = (accountId: string, name: string) =>
182 zeroTrust.listAccessApplicationsForAccount.pages({ accountId }).pipe(
183 Stream.runCollect,
184 Effect.map((chunk) =>
185 Array.from(chunk)
186 .flatMap((page) => page.result ?? [])
187 .map((raw) => raw as unknown as LiveApp & { id?: string; name?: string })
188 .find((app) => app.name === name),
189 ),
190 );
191
192 test.provider(
193 "access.policies declares a dedicated application owned by the Worker",
194 (stack) =>
195 Effect.gen(function* () {
196 const { accountId } = yield* yield* CloudflareEnvironment;
197
198 yield* stack.destroy();
199
200 const { worker } = yield* stack.deploy(
201 Effect.gen(function* () {
202 const worker = yield* OwnedAccessWorker;
203 return { worker };
204 }),
205 );
206
207 // The dedicated application exists with the inline policy and this
208 // Worker's destinations — declared entirely from the `access` prop.
209 const app = yield* findAppByName(accountId, "Access for alchemy owned-app test");
210 expect(app).toBeDefined();
211 expect(app!.policies?.length).toBe(1);
212 expect(app!.policies![0].decision).toBe("allow");
213 expect(app!.policies![0].reusable).toBe(false);
214 // `previews: false` — production destination only.
215 expect(app!.destinations).toEqual([
216 expect.objectContaining({ type: "worker", workerId: worker.workerId }),
217 ]);
218
219 // Unauthenticated requests are intercepted.
220 const location = yield* expectAccessLoginRedirect(worker.url!);
221 expect(location).toContain("cloudflareaccess.com");
222
223 yield* stack.destroy();
224
225 // The dedicated application is deleted with the Worker's stack.
226 const appAfter = yield* findAppByName(accountId, "Access for alchemy owned-app test");
227 expect(appAfter).toBeUndefined();
228 }).pipe(logLevel),
229 {
230 tags: [
231 "provider:cloudflare",
232 "provider:cloudflare:access",
233 "provider:cloudflare:worker",
234 "live",
235 ],
236 timeout: 300_000,
237 },
238 );
239
240 test.provider(
241 "a shared application merges enrollments from multiple Workers",
242 (stack) =>
243 Effect.gen(function* () {
244 const { accountId } = yield* yield* CloudflareEnvironment;
245
246 yield* stack.destroy();
247
248 // Two Workers enroll into the SAME application.
249 const both = Effect.gen(function* () {
250 const a = yield* AccessProtectedWorker;
251 const b = yield* SecondAccessWorker;
252 const app = yield* App;
253 return { a, b, app };
254 });
255 const { a, b, app } = yield* stack.deploy(both);
256
257 const live = (yield* zeroTrust.getAccessApplicationForAccount({
258 accountId,
259 appId: app.applicationId,
260 })) as unknown as LiveApp;
261 const workerDestinations = (live.destinations ?? []).filter(
262 (d) => d.workerId === a.workerId || d.workerId === b.workerId,
263 );
264 expect(workerDestinations).toEqual(
265 expect.arrayContaining([
266 expect.objectContaining({ type: "worker", workerId: a.workerId }),
267 expect.objectContaining({
268 type: "preview_worker",
269 workerId: a.workerId,
270 }),
271 expect.objectContaining({ type: "worker", workerId: b.workerId }),
272 expect.objectContaining({
273 type: "preview_worker",
274 workerId: b.workerId,
275 }),
276 ]),
277 );
278 expect(workerDestinations).toHaveLength(4);
279
280 // Un-enrollment without destroy: remove worker B from the stack —
281 // its binding contribution disappears and the application converges
282 // to worker A's destinations only.
283 const onlyA = Effect.gen(function* () {
284 const a = yield* AccessProtectedWorker;
285 const app = yield* App;
286 return { a, app };
287 });
288 yield* stack.deploy(onlyA);
289 const liveAfter = (yield* zeroTrust.getAccessApplicationForAccount({
290 accountId,
291 appId: app.applicationId,
292 })) as unknown as LiveApp;
293 const remaining = (liveAfter.destinations ?? []).filter(
294 (d) => d.workerId === a.workerId || d.workerId === b.workerId,
295 );
296 expect(remaining).toEqual(
297 expect.arrayContaining([
298 expect.objectContaining({ type: "worker", workerId: a.workerId }),
299 expect.objectContaining({
300 type: "preview_worker",
301 workerId: a.workerId,
302 }),
303 ]),
304 );
305 expect(remaining).toHaveLength(2);
306
307 yield* stack.destroy();
308 }).pipe(logLevel),
309 {
310 tags: [
311 "provider:cloudflare",
312 "provider:cloudflare:access",
313 "provider:cloudflare:worker",
314 "live",
315 ],
316 timeout: 300_000,
317 },
318 );