@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, 04:45 UTC

main
ts 237 lines 8.71 KB
Raw
1 import * as user from "@distilled.cloud/cloudflare/user";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import {
11 buildConditionPayload,
12 collectPolicies,
13 conditionFingerprint,
14 policyFingerprint,
15 resolvePolicies,
16 type ApiTokenBinding,
17 type Props,
18 } from "./Common.ts";
19 import { uniqueTokens } from "./internal.ts";
20
21 export type UserApiToken = Resource<
22 "Cloudflare.ApiToken.UserApiToken",
23 Props,
24 {
25 tokenId: string;
26 name: string;
27 status: "active" | "disabled" | "expired";
28 /**
29 * The plaintext token value. Cloudflare returns this only once, on
30 * creation, so we persist it here for downstream consumers.
31 */
32 value: Redacted.Redacted<string>;
33 },
34 ApiTokenBinding,
35 Providers
36 >;
37
38 /**
39 * A Cloudflare user-owned API token (`POST /user/tokens`).
40 *
41 * User-owned tokens are tied to the authenticated user's identity. They can
42 * be created by any authenticated user (including OAuth-derived sessions
43 * from `alchemy profile edit`) without needing the account-level
44 * `API Tokens > Write` permission, but they are also revoked if the user
45 * leaves the account.
46 *
47 * For CI tokens, prefer {@link AccountApiToken} so the token survives
48 * personnel changes.
49 *
50 * Policy `resources` are passed through verbatim — no `accountId` rewriting
51 * is performed because user tokens aren't bound to a single account.
52 * ### Creating a Token
53 * **Example:** A token bound to the authenticated user
54 * ```typescript
55 * const token = yield* Cloudflare.ApiToken.UserApiToken("personal-token", {
56 * name: "my-personal-token",
57 * policies: [
58 * {
59 * effect: "allow",
60 * permissionGroups: ["Workers Scripts Read"],
61 * resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
62 * },
63 * ],
64 * });
65 * ```
66 *
67 * ### Attaching Policies via Bindings
68 * **Example:** Let a downstream capability contribute its own policies
69 * A token can be created with no `policies` of its own; the policies are
70 * supplied through its binding contract (see {@link ApiTokenBinding}).
71 * ```typescript
72 * const token = yield* Cloudflare.ApiToken.UserApiToken("scoped-token");
73 *
74 * yield* token.bind("MyCapability", {
75 * policies: [
76 * {
77 * effect: "allow",
78 * permissionGroups: ["Workers Scripts Read"],
79 * resources: { [`com.cloudflare.api.account.${accountId}`]: "*" },
80 * },
81 * ],
82 * });
83 * ```
84 *
85 * ### Exposing a Token to a Worker
86 * **Example:** Read the token value at runtime
87 * Bind the token's value output in the Worker's Init phase to get a runtime
88 * accessor. Binding it injects a `secret_text` Worker binding; the returned
89 * accessor reads it back (as `Redacted`) at runtime.
90 * ```typescript
91 * // init
92 * const value = yield* token.value; // Accessor<Redacted<string>>
93 *
94 * return {
95 * fetch: Effect.gen(function* () {
96 * const apiToken = yield* value; // Redacted<string>
97 * // ... call the Cloudflare API with `apiToken`
98 * return HttpServerResponse.text("ok");
99 * }),
100 * };
101 * ```
102 *
103 * @resource
104 * @product API Tokens
105 * @category Account & Identity
106 */
107 export const UserApiToken = Resource<UserApiToken>("Cloudflare.ApiToken.UserApiToken", {
108 aliases: ["Cloudflare.UserApiToken"],
109 });
110
111 type UserApiTokenAttributes = UserApiToken["Attributes"];
112
113 export const UserApiTokenProvider = () =>
114 Provider.succeed(UserApiToken, {
115 stables: ["tokenId"],
116 diff: Effect.fn(function* ({ id, olds, news = {}, output }) {
117 if (!isResolved(news)) return undefined;
118 const oldName = output?.name ?? (yield* resolveName(id, olds?.name));
119 const newName = yield* resolveName(id, news.name);
120 const oldPolicyFp = policyFingerprint(resolvePolicies(olds?.policies ?? []));
121 const newPolicyFp = policyFingerprint(resolvePolicies(news.policies ?? []));
122 const oldCondFp = conditionFingerprint(olds?.condition);
123 const newCondFp = conditionFingerprint(news.condition);
124 if (
125 oldName !== newName ||
126 oldPolicyFp !== newPolicyFp ||
127 oldCondFp !== newCondFp ||
128 (olds?.expiresOn ?? undefined) !== (news.expiresOn ?? undefined) ||
129 (olds?.notBefore ?? undefined) !== (news.notBefore ?? undefined)
130 ) {
131 return { action: "update" } as const;
132 }
133 }),
134 reconcile: Effect.fn(function* ({ id, news = {}, output, bindings }) {
135 const name = yield* resolveName(id, news.name);
136 const collected = collectPolicies(news.policies, bindings);
137 if (collected.length === 0) {
138 return yield* Effect.die(
139 `Cloudflare requires at least one policy on token "${name}". ` +
140 "Pass `policies` or attach them via a binding.",
141 );
142 }
143 const policies = resolvePolicies(collected);
144
145 // Observe — fetch current state if we know the token id;
146 // Cloudflare reports a deleted token as `TokenNotFound`, which
147 // we treat as "create from scratch".
148 const observed = output?.tokenId
149 ? yield* user.getToken({ tokenId: output.tokenId }).pipe(
150 Effect.map((token) => token),
151 Effect.catchTag("TokenNotFound", () => Effect.undefined),
152 )
153 : undefined;
154
155 // Ensure — create if missing. Cloudflare returns the plaintext
156 // token value exactly once on create, so we must persist it.
157 // No idempotency token is available; we accept a duplicate over
158 // losing the secret value.
159 if (observed === undefined) {
160 const result = yield* user.createToken({
161 name,
162 policies,
163 condition: buildConditionPayload(news.condition),
164 expiresOn: news.expiresOn,
165 notBefore: news.notBefore,
166 });
167 if (!result.value) {
168 return yield* Effect.die(`Cloudflare did not return a value for token "${name}".`);
169 }
170 return buildAttributes(result, Redacted.make(result.value));
171 }
172
173 // Sync — the update API replaces all mutable fields. Cloudflare
174 // does not return the plaintext value on update, so preserve
175 // the one captured at creation.
176 const result = yield* user.updateToken({
177 tokenId: output!.tokenId,
178 name,
179 policies,
180 condition: buildConditionPayload(news.condition),
181 expiresOn: news.expiresOn,
182 notBefore: news.notBefore,
183 });
184 return buildAttributes(result, output!.value);
185 }),
186 delete: Effect.fn(function* ({ output }) {
187 yield* user
188 .deleteToken({ tokenId: output.tokenId })
189 .pipe(Effect.catchTag("TokenNotFound", () => Effect.void));
190 }),
191 read: Effect.fn(function* ({ output }) {
192 if (!output?.tokenId) return undefined;
193 return yield* user.getToken({ tokenId: output.tokenId }).pipe(
194 Effect.map((token) => buildAttributes(token, output.value)),
195 Effect.catchTag("TokenNotFound", () => Effect.undefined),
196 );
197 }),
198 // User-scoped: enumerate every token owned by the authenticated user via
199 // `GET /user/tokens` (no account scope). The list API never returns the
200 // plaintext token value — it is only emitted once at creation — so we
201 // hydrate the read shape with an empty Redacted value, matching what
202 // `read` produces when the secret was never captured.
203 list: () =>
204 // Offset-paginated over a name-sorted list: concurrent creates/deletes
205 // between page fetches duplicate or skip tokens. Use the API's maximum
206 // page size (1000) for a single-snapshot read and de-duplicate by id.
207 user.listTokens.pages({ perPage: 1000 }).pipe(
208 Stream.runCollect,
209 Effect.map((chunk) =>
210 uniqueTokens(Array.from(chunk).flatMap((page) => page.result ?? [])).map((token) =>
211 buildAttributes(token, Redacted.make("")),
212 ),
213 ),
214 // User-scoped tokens require user-level auth; an account-scoped token
215 // (e.g. a CI profile) gets `Unauthorized` here — nothing to enumerate.
216 Effect.catchTag("Unauthorized", () => Effect.succeed([])),
217 ),
218 });
219
220 const resolveName = (id: string, name: string | undefined) =>
221 Effect.gen(function* () {
222 return name ?? (yield* createPhysicalName({ id }));
223 });
224 const buildAttributes = (
225 tokenData: {
226 id?: string | null;
227 name?: string | null;
228 // Distilled widened generated string enums to open unions (`string & {}`).
229 status?: string | null;
230 },
231 value: Redacted.Redacted<string>,
232 ): UserApiTokenAttributes => ({
233 tokenId: tokenData.id ?? "",
234 name: tokenData.name ?? "",
235 status: (tokenData.status ?? "active") as "active" | "disabled" | "expired",
236 value,
237 });