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

main
ts 223 lines 8.88 KB
Raw
1 import {
2 clientFor,
3 deviceAuthorize,
4 deviceToken,
5 LEGACY_OAUTH_CLIENT_ID,
6 OAUTH_CLIENT_ID,
7 type OAuthCredentials,
8 } from "@alchemy.run/cloudflare/Auth/OAuthClient";
9 import {
10 ALL_SCOPE_IDS,
11 ALL_SCOPES,
12 BASIC_SCOPES,
13 customOAuthScopeDefaults,
14 OAUTH_SCOPE_GROUPS,
15 partitionOAuthScopes,
16 } from "@alchemy.run/cloudflare/Auth/OAuthScopes";
17 import { describe, expect, it } from "@alchemy.run/test";
18 import * as Effect from "effect/Effect";
19 import * as FetchHttpClient from "effect/http/FetchHttpClient";
20 import * as Redacted from "effect/Redacted";
21
22 describe(
23 "Cloudflare public OAuth client",
24 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:auth", "local"] },
25 () => {
26 it("uses a duplicate-free catalog of allowed scopes", () => {
27 const scopes = OAUTH_SCOPE_GROUPS.flatMap((group) => group.scopes);
28
29 expect(scopes.length).toBeGreaterThan(0);
30 expect(new Set(scopes).size).toBe(scopes.length);
31 });
32
33 it("partitions stored scopes against the current catalog", () => {
34 // Profiles configured against an older OAuth client can hold scopes the
35 // current client rejects; login must drop them instead of building an
36 // authorize URL that Cloudflare refuses wholesale.
37 const { valid, dropped } = partitionOAuthScopes([
38 "workers-scripts.write",
39 "account:read", // wrangler-era scope id, not in the alchemy catalog
40 "zone.read",
41 ]);
42 expect(valid).toEqual(["workers-scripts.write", "zone.read"]);
43 expect(dropped).toEqual(["account:read"]);
44 });
45
46 it("neither keeps nor drops the offline_access scope", () => {
47 // The token response echoes offline_access into the stored scopes;
48 // the authorize step adds it back itself.
49 expect(partitionOAuthScopes(["zone.read", "offline_access"])).toEqual({
50 valid: ["zone.read"],
51 dropped: [],
52 });
53 });
54
55 it("keeps the basic template inside the client allowlist", () => {
56 expect(BASIC_SCOPES.length).toBeGreaterThan(0);
57 expect(BASIC_SCOPES.every((scope) => scope in ALL_SCOPES)).toBe(true);
58 expect(BASIC_SCOPES).toContain("memberships.read");
59 expect(BASIC_SCOPES).toContain("workers-scripts.write");
60 expect(BASIC_SCOPES).toContain("zone.read");
61 });
62
63 it("defaults to all scopes and restores valid scopes when reconfigured", () => {
64 expect(
65 customOAuthScopeDefaults({
66 method: "oauth",
67 scopes: ["workers-scripts.write", "account:read", "zone.read"],
68 accountId: "account-id",
69 }),
70 ).toEqual(["workers-scripts.write", "zone.read"]);
71
72 expect(customOAuthScopeDefaults({ method: "stored", credentialType: "apiToken" })).toEqual(
73 ALL_SCOPE_IDS,
74 );
75 });
76
77 const fakeFetch = (
78 requests: Array<{ url: string; body: URLSearchParams }>,
79 respond: (body: URLSearchParams) => { status: number; json: unknown },
80 ) =>
81 // SAFETY: the test double implements the callable fetch contract; Bun's
82 // nonstandard static `preconnect` member is not used by FetchHttpClient.
83 (async (input, init) => {
84 const body = new URLSearchParams(await new Response(init?.body).text());
85 requests.push({ url: input instanceof Request ? input.url : String(input), body });
86 const { status, json } = respond(body);
87 return new Response(JSON.stringify(json), {
88 status,
89 headers: { "Content-Type": "application/json" },
90 });
91 }) as typeof globalThis.fetch;
92
93 it("authorizes new logins with the cf CLI client's device flow", async () => {
94 const requests: Array<{ url: string; body: URLSearchParams }> = [];
95 let polls = 0;
96 const fetch = fakeFetch(requests, (body) => {
97 if (body.get("grant_type") === null) {
98 return {
99 status: 200,
100 json: {
101 device_code: "device",
102 user_code: "ABCD-EFGH",
103 verification_uri: "https://dash.cloudflare.com/oauth2/device",
104 expires_in: 300,
105 interval: 1,
106 },
107 };
108 }
109 polls++;
110 return polls === 1
111 ? { status: 400, json: { error: "authorization_pending" } }
112 : polls === 2
113 ? { status: 502, json: "<!DOCTYPE html>bad gateway" }
114 : {
115 status: 200,
116 json: {
117 access_token: "access",
118 refresh_token: "refresh",
119 expires_in: 3600,
120 scope: "zone.read offline_access",
121 },
122 };
123 });
124
125 const credentials = await Effect.runPromise(
126 Effect.gen(function* () {
127 const authorization = yield* deviceAuthorize(["zone.read", "offline_access"]);
128 expect(authorization.userCode).toBe("ABCD-EFGH");
129 expect(authorization.verificationUriComplete).toBe(
130 "https://dash.cloudflare.com/oauth2/device?user_code=ABCD-EFGH",
131 );
132 return yield* deviceToken(authorization);
133 }).pipe(Effect.provideService(FetchHttpClient.Fetch, fetch)),
134 );
135
136 expect(requests[0]?.url).toBe("https://dash.cloudflare.com/oauth2/device/auth");
137 expect(requests[0]?.body.get("client_id")).toBe(OAUTH_CLIENT_ID);
138 expect(requests[0]?.body.get("scope")).toBe("zone.read offline_access");
139 expect(requests[1]?.body.get("grant_type")).toBe(
140 "urn:ietf:params:oauth:grant-type:device_code",
141 );
142 expect(requests[1]?.body.get("device_code")).toBe("device");
143 expect(polls).toBe(3);
144 expect(credentials.clientId).toBe(OAUTH_CLIENT_ID);
145 expect(Redacted.value(credentials.refresh)).toBe("refresh");
146 });
147
148 it("stops polling when the user denies the device authorization", async () => {
149 const fetch = fakeFetch([], () => ({ status: 400, json: { error: "access_denied" } }));
150 const error = await Effect.runPromise(
151 deviceToken({
152 deviceCode: "device",
153 userCode: "ABCD-EFGH",
154 verificationUri: "https://dash.cloudflare.com/oauth2/device",
155 verificationUriComplete: "https://dash.cloudflare.com/oauth2/device?user_code=ABCD-EFGH",
156 expiresIn: 300,
157 interval: 1,
158 }).pipe(Effect.flip, Effect.provideService(FetchHttpClient.Fetch, fetch)),
159 );
160 expect(error._tag).toBe("DeviceAuthorizationDenied");
161 });
162
163 it("refuses a verification URL outside dash.cloudflare.com", async () => {
164 const fetch = fakeFetch([], () => ({
165 status: 200,
166 json: {
167 device_code: "device",
168 user_code: "ABCD-EFGH",
169 verification_uri: "https://evil.example/device",
170 expires_in: 300,
171 },
172 }));
173 const error = await Effect.runPromise(
174 deviceAuthorize(["zone.read"]).pipe(
175 Effect.flip,
176 Effect.provideService(FetchHttpClient.Fetch, fetch),
177 ),
178 );
179 expect(error._tag).toBe("UntrustedVerificationUriError");
180 });
181
182 it("keeps refreshing and revoking legacy-client grants with the legacy client", async () => {
183 const requests: URLSearchParams[] = [];
184 // SAFETY: the test double implements the callable fetch contract; Bun's
185 // nonstandard static `preconnect` member is not used by FetchHttpClient.
186 const fetch = (async (_input, init) => {
187 requests.push(new URLSearchParams(await new Response(init?.body).text()));
188 return new Response(JSON.stringify({ access_token: "next-access", expires_in: 3600 }), {
189 status: 200,
190 headers: { "Content-Type": "application/json" },
191 });
192 }) as typeof globalThis.fetch;
193
194 const current: OAuthCredentials = {
195 type: "oauth",
196 clientId: LEGACY_OAUTH_CLIENT_ID,
197 access: Redacted.make("current-access"),
198 refresh: Redacted.make("current-refresh"),
199 expires: 0,
200 scopes: ["workers-scripts.write"],
201 };
202
203 const withFetch = <A, E>(effect: Effect.Effect<A, E>) =>
204 effect.pipe(Effect.provideService(FetchHttpClient.Fetch, fetch));
205 const client = clientFor(current);
206 if (client === undefined) throw new Error("legacy client not recognized");
207 const next = await Effect.runPromise(withFetch(client.refresh(current)));
208 await Effect.runPromise(withFetch(client.revoke(next)));
209
210 expect(Redacted.value(next.refresh)).toBe("current-refresh");
211 expect(next.scopes).toEqual(current.scopes);
212 expect(next.clientId).toBe(current.clientId);
213 expect(clientFor({ clientId: "unknown" })).toBeUndefined();
214 expect(requests[0]?.get("grant_type")).toBe("refresh_token");
215 expect(requests[0]?.get("client_id")).toBe(LEGACY_OAUTH_CLIENT_ID);
216 expect(requests[1]?.get("client_id")).toBe(LEGACY_OAUTH_CLIENT_ID);
217 expect(requests[0]?.has("redirect_uri")).toBe(false);
218 expect(requests[1]?.get("token")).toBe("current-refresh");
219 expect(requests[1]?.get("token_type_hint")).toBe("refresh_token");
220 expect(requests[1]?.has("refresh_token")).toBe(false);
221 });
222 },
223 );