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
| 1 | import * as accounts from "@distilled.cloud/cloudflare/accounts"; |
| 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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { |
| 12 | buildConditionPayload, |
| 13 | collectPolicies, |
| 14 | conditionFingerprint, |
| 15 | findTopLevelWorkerScriptKey, |
| 16 | policyFingerprint, |
| 17 | resolvePolicies, |
| 18 | type ApiTokenBinding, |
| 19 | type Props, |
| 20 | } from "./Common.ts"; |
| 21 | import { uniqueTokens } from "./internal.ts"; |
| 22 | |
| 23 | export type AccountApiToken = Resource< |
| 24 | "Cloudflare.ApiToken.AccountApiToken", |
| 25 | Props, |
| 26 | { |
| 27 | tokenId: string; |
| 28 | name: string; |
| 29 | status: "active" | "disabled" | "expired"; |
| 30 | /** |
| 31 | * The plaintext token value. Cloudflare returns this only once, on |
| 32 | * creation, so we persist it here for downstream consumers (e.g. a |
| 33 | * GitHub Actions secret). |
| 34 | */ |
| 35 | value: Redacted.Redacted<string>; |
| 36 | accountId: string; |
| 37 | }, |
| 38 | ApiTokenBinding, |
| 39 | Providers |
| 40 | >; |
| 41 | |
| 42 | /** |
| 43 | * A Cloudflare account-owned API token (`POST /accounts/{account_id}/tokens`). |
| 44 | * |
| 45 | * Account-owned tokens are managed at the account level and persist |
| 46 | * independently of any single user. Use these for CI tokens, third-party |
| 47 | * integrations, or anywhere the token should outlive an individual user's |
| 48 | * session. |
| 49 | * |
| 50 | * Creating account-owned tokens requires the caller to have the |
| 51 | * `API Tokens > Write` account permission. |
| 52 | * ### Creating a Token |
| 53 | * **Example:** A token for managing Workers and KV from CI |
| 54 | * ```typescript |
| 55 | * // the account ID resolves from the profile you're deploying with |
| 56 | * const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; |
| 57 | * |
| 58 | * const token = yield* Cloudflare.ApiToken.AccountApiToken("ci-token", { |
| 59 | * name: "my-ci-token", |
| 60 | * accountId, |
| 61 | * policies: [ |
| 62 | * { |
| 63 | * effect: "allow", |
| 64 | * permissionGroups: [ |
| 65 | * "Workers Scripts Write", |
| 66 | * "Workers KV Storage Write", |
| 67 | * ], |
| 68 | * resources: { [`com.cloudflare.api.account.${accountId}`]: "*" }, |
| 69 | * }, |
| 70 | * ], |
| 71 | * }); |
| 72 | * |
| 73 | * yield* GitHub.Secret("cf-api-token", { |
| 74 | * owner: "me", |
| 75 | * repository: "my-repo", |
| 76 | * name: "CLOUDFLARE_API_TOKEN", |
| 77 | * value: token.value, |
| 78 | * }); |
| 79 | * ``` |
| 80 | * |
| 81 | * ### Scoping a Token to One Worker |
| 82 | * **Example:** A deploy token that can only edit one Worker |
| 83 | * The `Individual Workers` roles (`Admin`, `Editor`, `Content Read-Only`, |
| 84 | * `Metadata Read-Only`) apply to a single Worker. Key the Worker by its |
| 85 | * `workerId`, nested under the account. Only account-owned tokens accept |
| 86 | * these roles. |
| 87 | * ```typescript |
| 88 | * const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; |
| 89 | * const api = yield* Cloudflare.Worker("Api", { main: "./src/api.ts" }); |
| 90 | * |
| 91 | * const token = yield* Cloudflare.ApiToken.AccountApiToken("api-deploy-token", { |
| 92 | * policies: [ |
| 93 | * { |
| 94 | * effect: "allow", |
| 95 | * permissionGroups: ["Individual Workers Editor"], |
| 96 | * resources: api.workerId.pipe( |
| 97 | * Output.map((workerId) => ({ |
| 98 | * [`com.cloudflare.api.account.${accountId}`]: { |
| 99 | * [`com.cloudflare.edge.worker.script.${workerId}`]: "*", |
| 100 | * }, |
| 101 | * })), |
| 102 | * ), |
| 103 | * }, |
| 104 | * ], |
| 105 | * }); |
| 106 | * ``` |
| 107 | * |
| 108 | * ### Attaching Policies via Bindings |
| 109 | * **Example:** Let a downstream capability contribute its own policies |
| 110 | * A token can be created with no `policies` of its own; the policies are |
| 111 | * supplied through its binding contract (see {@link ApiTokenBinding}). This is |
| 112 | * how capabilities like {@link CreateTunnel} provision a least-privilege token. |
| 113 | * ```typescript |
| 114 | * const token = yield* Cloudflare.ApiToken.AccountApiToken("scoped-token"); |
| 115 | * |
| 116 | * yield* token.bind("MyCapability", { |
| 117 | * policies: [ |
| 118 | * { |
| 119 | * effect: "allow", |
| 120 | * permissionGroups: ["Cloudflare Tunnel Write"], |
| 121 | * resources: { [`com.cloudflare.api.account.${accountId}`]: "*" }, |
| 122 | * }, |
| 123 | * ], |
| 124 | * }); |
| 125 | * ``` |
| 126 | * |
| 127 | * ### Exposing a Token to a Worker |
| 128 | * **Example:** Read the token value at runtime |
| 129 | * Bind the token's outputs in the Worker's Init phase to get runtime |
| 130 | * accessors. Binding `token.value` injects it as a `secret_text` Worker |
| 131 | * binding; the returned accessor reads it back (as `Redacted`) at runtime. |
| 132 | * ```typescript |
| 133 | * // init |
| 134 | * const value = yield* token.value; // Accessor<Redacted<string>> |
| 135 | * const accountId = yield* token.accountId; // Accessor<string> |
| 136 | * |
| 137 | * return { |
| 138 | * fetch: Effect.gen(function* () { |
| 139 | * const apiToken = yield* value; // Redacted<string> |
| 140 | * // ... call the Cloudflare API with `apiToken` |
| 141 | * return HttpServerResponse.text("ok"); |
| 142 | * }), |
| 143 | * }; |
| 144 | * ``` |
| 145 | * |
| 146 | * @resource |
| 147 | * @product API Tokens |
| 148 | * @category Account & Identity |
| 149 | */ |
| 150 | export const AccountApiToken = Resource<AccountApiToken>("Cloudflare.ApiToken.AccountApiToken", { |
| 151 | aliases: ["Cloudflare.AccountApiToken"], |
| 152 | }); |
| 153 | |
| 154 | type AccountApiTokenAttributes = AccountApiToken["Attributes"]; |
| 155 | |
| 156 | const resolveName = (id: string, name: string | undefined) => |
| 157 | Effect.gen(function* () { |
| 158 | return name ?? (yield* createPhysicalName({ id })); |
| 159 | }); |
| 160 | |
| 161 | const buildAttributes = ( |
| 162 | tokenData: { |
| 163 | id?: string | null; |
| 164 | name?: string | null; |
| 165 | // Distilled widened generated string enums to open unions (`string & {}`). |
| 166 | status?: string | null; |
| 167 | }, |
| 168 | value: Redacted.Redacted<string>, |
| 169 | accountId: string, |
| 170 | ): AccountApiTokenAttributes => ({ |
| 171 | tokenId: tokenData.id ?? "", |
| 172 | name: tokenData.name ?? "", |
| 173 | status: (tokenData.status ?? "active") as "active" | "disabled" | "expired", |
| 174 | value, |
| 175 | accountId, |
| 176 | }); |
| 177 | |
| 178 | export const AccountApiTokenProvider = () => |
| 179 | Provider.succeed(AccountApiToken, { |
| 180 | stables: ["tokenId", "accountId"], |
| 181 | diff: Effect.fn(function* ({ id, olds, news = {}, output }) { |
| 182 | if (!isResolved(news)) return undefined; |
| 183 | const { accountId: defaultAccountId } = yield* yield* CloudflareEnvironment; |
| 184 | |
| 185 | const newAccountId = news.accountId ?? defaultAccountId; |
| 186 | const oldAccountId = output?.accountId ?? olds?.accountId ?? defaultAccountId; |
| 187 | if (oldAccountId !== newAccountId) { |
| 188 | return { action: "replace" } as const; |
| 189 | } |
| 190 | const oldName = output?.name ?? (yield* resolveName(id, olds?.name)); |
| 191 | const newName = yield* resolveName(id, news.name); |
| 192 | const oldPolicyFp = policyFingerprint(resolvePolicies(olds?.policies ?? [])); |
| 193 | const newPolicyFp = policyFingerprint(resolvePolicies(news.policies ?? [])); |
| 194 | const oldCondFp = conditionFingerprint(olds?.condition); |
| 195 | const newCondFp = conditionFingerprint(news.condition); |
| 196 | if ( |
| 197 | oldName !== newName || |
| 198 | oldPolicyFp !== newPolicyFp || |
| 199 | oldCondFp !== newCondFp || |
| 200 | (olds?.expiresOn ?? undefined) !== (news.expiresOn ?? undefined) || |
| 201 | (olds?.notBefore ?? undefined) !== (news.notBefore ?? undefined) |
| 202 | ) { |
| 203 | return { action: "update" } as const; |
| 204 | } |
| 205 | }), |
| 206 | reconcile: Effect.fn(function* ({ id, news = {}, output, bindings }) { |
| 207 | const { accountId: defaultAccountId } = yield* yield* CloudflareEnvironment; |
| 208 | const accountId = news.accountId ?? defaultAccountId; |
| 209 | const name = yield* resolveName(id, news.name); |
| 210 | const collected = collectPolicies(news.policies, bindings); |
| 211 | if (collected.length === 0) { |
| 212 | return yield* Effect.die( |
| 213 | `Cloudflare requires at least one policy on token "${name}". ` + |
| 214 | "Pass `policies` or attach them via a binding.", |
| 215 | ); |
| 216 | } |
| 217 | const policies = resolvePolicies(collected); |
| 218 | const workerScriptKey = findTopLevelWorkerScriptKey(policies); |
| 219 | if (workerScriptKey) { |
| 220 | return yield* Effect.die( |
| 221 | `Token "${name}" lists "${workerScriptKey}" as a top-level resource. ` + |
| 222 | "Cloudflare only accepts Worker resources nested under the account: " + |
| 223 | `{ "com.cloudflare.api.account.${accountId}": { "${workerScriptKey}": "*" } }.`, |
| 224 | ); |
| 225 | } |
| 226 | |
| 227 | // Observe — fetch current state if we already know the token id. |
| 228 | // Cloudflare reports a deleted token as `InvalidRoute` or |
| 229 | // `TokenNotFound`; both mean "create from scratch". |
| 230 | const observed = output?.tokenId |
| 231 | ? yield* accounts |
| 232 | .getToken({ |
| 233 | accountId: output.accountId, |
| 234 | tokenId: output.tokenId, |
| 235 | }) |
| 236 | .pipe( |
| 237 | Effect.map((token) => token), |
| 238 | Effect.catchTags({ |
| 239 | InvalidRoute: () => Effect.undefined, |
| 240 | TokenNotFound: () => Effect.undefined, |
| 241 | }), |
| 242 | ) |
| 243 | : undefined; |
| 244 | |
| 245 | // Ensure — create if missing. Cloudflare returns the plaintext |
| 246 | // token value exactly once on create, so we must persist it for |
| 247 | // downstream consumers. There is no idempotency token here; if |
| 248 | // a stale write produced an orphan we accept the duplicate over |
| 249 | // the alternative of losing the secret value. |
| 250 | if (observed === undefined) { |
| 251 | const result = yield* accounts.createToken({ |
| 252 | accountId, |
| 253 | name, |
| 254 | policies, |
| 255 | condition: buildConditionPayload(news.condition), |
| 256 | expiresOn: news.expiresOn, |
| 257 | notBefore: news.notBefore, |
| 258 | }); |
| 259 | if (!result.value) { |
| 260 | return yield* Effect.die(`Cloudflare did not return a value for token "${name}".`); |
| 261 | } |
| 262 | return buildAttributes(result, Redacted.make(result.value), accountId); |
| 263 | } |
| 264 | |
| 265 | // Sync — the update API replaces all mutable fields (name, |
| 266 | // policies, condition, validity window). Cloudflare does not |
| 267 | // return the plaintext value on update, so we preserve the one |
| 268 | // captured at creation. |
| 269 | const result = yield* accounts.updateToken({ |
| 270 | accountId, |
| 271 | tokenId: output!.tokenId, |
| 272 | name, |
| 273 | policies, |
| 274 | condition: buildConditionPayload(news.condition), |
| 275 | expiresOn: news.expiresOn, |
| 276 | notBefore: news.notBefore, |
| 277 | }); |
| 278 | return buildAttributes(result, output!.value, accountId); |
| 279 | }), |
| 280 | delete: Effect.fn(function* ({ output }) { |
| 281 | yield* accounts |
| 282 | .deleteToken({ |
| 283 | accountId: output.accountId, |
| 284 | tokenId: output.tokenId, |
| 285 | }) |
| 286 | .pipe( |
| 287 | // Already gone — Cloudflare may report this as either an |
| 288 | // `InvalidRoute` (token-id no longer routable) or a generic |
| 289 | // `TokenNotFound`. Either is fine; we just want the resource gone. |
| 290 | Effect.catchTags({ |
| 291 | InvalidRoute: () => Effect.void, |
| 292 | TokenNotFound: () => Effect.void, |
| 293 | }), |
| 294 | // Cloudflare-managed tokens (e.g. "Cloudflare Resource Tagging |
| 295 | // System") can never be deleted (code 1001). We don't own them, so |
| 296 | // treat the refusal as a no-op rather than a failure. |
| 297 | Effect.catchTag("TokenManagedByCloudflare", () => Effect.void), |
| 298 | ); |
| 299 | }), |
| 300 | list: Effect.fn(function* () { |
| 301 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 302 | // The plaintext token value is only returned by Cloudflare once, at |
| 303 | // creation time. The list/get APIs never expose it, so we hydrate an |
| 304 | // empty redacted placeholder — matching what `read` returns when it |
| 305 | // re-observes a token whose value we no longer hold. |
| 306 | // |
| 307 | // `GET /accounts/{id}/tokens` is offset-paginated over a name-sorted |
| 308 | // list, so any token created or deleted between page fetches (e.g. a |
| 309 | // concurrent deploy) shifts the window: tokens get listed twice or |
| 310 | // skipped. Request the API's maximum page size (1000) so a typical |
| 311 | // account is enumerated in one snapshot, and de-duplicate by id in |
| 312 | // case it still spans pages. |
| 313 | return yield* accounts.listTokens.pages({ accountId, perPage: 1000 }).pipe( |
| 314 | Stream.runCollect, |
| 315 | Effect.map((chunk) => |
| 316 | uniqueTokens(Array.from(chunk).flatMap((page) => page.result ?? [])).map((token) => |
| 317 | buildAttributes(token, Redacted.make(""), accountId), |
| 318 | ), |
| 319 | ), |
| 320 | ); |
| 321 | }), |
| 322 | read: Effect.fn(function* ({ output }) { |
| 323 | if (!output?.tokenId) return undefined; |
| 324 | return yield* accounts |
| 325 | .getToken({ |
| 326 | accountId: output.accountId, |
| 327 | tokenId: output.tokenId, |
| 328 | }) |
| 329 | .pipe( |
| 330 | Effect.map((token) => buildAttributes(token, output.value, output.accountId)), |
| 331 | Effect.catchTags({ |
| 332 | InvalidRoute: () => Effect.undefined, |
| 333 | TokenNotFound: () => Effect.undefined, |
| 334 | }), |
| 335 | ); |
| 336 | }), |
| 337 | }); |