@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 189 lines 7.64 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as user from "@distilled.cloud/cloudflare/user";
6 import * as Provider from "alchemy/Provider";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Result from "effect/Result";
12 import * as Schedule from "effect/Schedule";
13 import { testName } from "../../names.ts";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 // User-owned tokens need the user-level `API Tokens Write` permission. The
20 // standing testing credential is an account-scoped API token without it (even
21 // `API Tokens Read` is refused with the typed `Unauthorized: Unauthorized to
22 // access requested resource` — pinned by the probe below), so the lifecycle is
23 // gated behind CLOUDFLARE_TEST_USER_TOKENS for a user-API-key credential.
24 describe.skipIf(!process.env.CLOUDFLARE_TEST_USER_TOKENS)(
25 "UserApiToken",
26 { tags: ["provider:cloudflare", "provider:cloudflare:apitoken", "live"] },
27 () => {
28 test.provider("create and delete user token with default props", (stack) =>
29 Effect.gen(function* () {
30 const { accountId } = yield* yield* CloudflareEnvironment;
31
32 yield* stack.destroy();
33
34 const token = yield* stack.deploy(
35 Effect.gen(function* () {
36 return yield* Cloudflare.ApiToken.UserApiToken("DefaultUserToken", {
37 policies: [
38 {
39 effect: "allow",
40 permissionGroups: ["Workers Scripts Read"],
41 resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
42 },
43 ],
44 });
45 }),
46 );
47
48 expect(token.tokenId).toBeDefined();
49 expect(token.name).toBeDefined();
50 expect(token.status).toEqual("active");
51 expect(Redacted.value(token.value)).toMatch(/.+/);
52
53 const actualToken = yield* user.getToken({ tokenId: token.tokenId });
54 expect(actualToken.id).toEqual(token.tokenId);
55 expect(actualToken.name).toEqual(token.name);
56
57 yield* stack.destroy();
58
59 yield* waitForTokenToBeDeleted(token.tokenId);
60 }).pipe(logLevel),
61 );
62
63 test.provider("create, update, delete user token", (stack) =>
64 Effect.gen(function* () {
65 const { accountId } = yield* yield* CloudflareEnvironment;
66
67 yield* stack.destroy();
68
69 const token = yield* stack.deploy(
70 Effect.gen(function* () {
71 return yield* Cloudflare.ApiToken.UserApiToken("UpdateUserToken", {
72 name: testName("alchemy-test-user-update-initial"),
73 policies: [
74 {
75 effect: "allow",
76 permissionGroups: ["Workers Scripts Read"],
77 resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
78 },
79 ],
80 });
81 }),
82 );
83
84 expect(token.name).toEqual(testName("alchemy-test-user-update-initial"));
85 const initialValue = Redacted.value(token.value);
86
87 const updated = yield* stack.deploy(
88 Effect.gen(function* () {
89 return yield* Cloudflare.ApiToken.UserApiToken("UpdateUserToken", {
90 name: testName("alchemy-test-user-update-renamed"),
91 policies: [
92 {
93 effect: "allow",
94 permissionGroups: ["Workers Scripts Read", "Workers KV Storage Read"],
95 resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
96 },
97 ],
98 });
99 }),
100 );
101
102 expect(updated.tokenId).toEqual(token.tokenId);
103 expect(updated.name).toEqual(testName("alchemy-test-user-update-renamed"));
104 expect(Redacted.value(updated.value)).toEqual(initialValue);
105
106 const actual = yield* user.getToken({ tokenId: updated.tokenId });
107 expect(actual.name).toEqual(testName("alchemy-test-user-update-renamed"));
108 expect(actual.policies?.[0]?.permissionGroups.length).toEqual(2);
109
110 yield* stack.destroy();
111
112 yield* waitForTokenToBeDeleted(token.tokenId);
113 }).pipe(logLevel),
114 );
115
116 const waitForTokenToBeDeleted = Effect.fn(function* (tokenId: string) {
117 yield* user.getToken({ tokenId }).pipe(
118 Effect.flatMap(() => Effect.fail(new TokenStillExists())),
119 Effect.retry({
120 while: (e): e is TokenStillExists => e instanceof TokenStillExists,
121 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(8)]),
122 }),
123 Effect.catchTag("TokenStillExists", () =>
124 Effect.die(`Cloudflare API token ${tokenId} was not deleted after retries`),
125 ),
126 Effect.catchTag("TokenNotFound", () => Effect.void),
127 Effect.catchTag("InvalidRoute", () => Effect.void),
128 );
129 });
130 },
131 );
132
133 describe(
134 "UserApiToken list",
135 { tags: ["provider:cloudflare", "provider:cloudflare:apitoken", "live"] },
136 () => {
137 // Read-only: `GET /user/tokens` requires the authenticated *user's* identity.
138 // The standing testing profile authenticates with a scoped API token that
139 // lacks the `API Tokens > Read` user permission, so the live call rejects
140 // with the typed error:
141 // Unauthorized: Unauthorized to access requested resource (_tag: "Unauthorized")
142 // The `list()` impl is correct (it propagates the typed error rather than
143 // masking it as []), so we gate the live assertion behind an env var an
144 // entitled (user-API-key) credential can set. The test only asserts the
145 // provider exhaustively enumerates into the read-shaped Attributes.
146 test.provider.skipIf(!process.env.CLOUDFLARE_TEST_USER_TOKENS)(
147 "list enumerates user tokens",
148 () =>
149 Effect.gen(function* () {
150 const provider = yield* Provider.findProvider(Cloudflare.ApiToken.UserApiToken);
151 const all = yield* provider.list();
152
153 expect(Array.isArray(all)).toBe(true);
154 for (const token of all) {
155 expect(typeof token.tokenId).toBe("string");
156 expect(typeof token.name).toBe("string");
157 expect(["active", "disabled", "expired"]).toContain(token.status);
158 // List never returns the plaintext value; read shape is preserved
159 // with an empty Redacted secret.
160 expect(typeof Redacted.value(token.value)).toBe("string");
161 }
162 }).pipe(logLevel),
163 );
164 },
165 );
166
167 // Ungated probe: the standing scoped-token testing profile must surface the
168 // auth gap as the typed `Unauthorized` tag (not an UnknownCloudflareError),
169 // proving the error is in the typed union and the gating above is correct.
170 describe(
171 "UserApiToken list probe",
172 { tags: ["provider:cloudflare", "provider:cloudflare:apitoken", "live"] },
173 () => {
174 test.provider("list rejects with typed Unauthorized under scoped token", () =>
175 Effect.gen(function* () {
176 const provider = yield* Provider.findProvider(Cloudflare.ApiToken.UserApiToken);
177 const result = yield* Effect.result(provider.list());
178 if (Result.isSuccess(result)) {
179 // An entitled credential can list — that's fine, nothing to assert.
180 expect(Array.isArray(result.success)).toBe(true);
181 return;
182 }
183 expect(result.failure._tag).toBe("Unauthorized");
184 }).pipe(logLevel),
185 );
186 },
187 );
188
189 class TokenStillExists extends Data.TaggedError("TokenStillExists") {}