The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust"; |
| 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 Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Predicate from "effect/Predicate"; |
| 10 | import * as Redacted from "effect/Redacted"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | |
| 15 | export class ServiceTokenUnexpectedResponse extends Data.TaggedError( |
| 16 | "ServiceTokenUnexpectedResponse", |
| 17 | )<{ |
| 18 | readonly message: string; |
| 19 | readonly cause?: unknown; |
| 20 | }> {} |
| 21 | |
| 22 | export type ServiceTokenProps = { |
| 23 | /** |
| 24 | * Display name for the service token. Used as a stable identifier so the |
| 25 | * provider can locate the token by name during adoption / state recovery. |
| 26 | * If omitted, a unique name is generated from the stack/stage/logical id. |
| 27 | * |
| 28 | * @default ${app}-${stage}-${id} |
| 29 | */ |
| 30 | name?: string; |
| 31 | /** |
| 32 | * How long the service token is valid. Must be in the format `300ms` or |
| 33 | * `2h45m`. Valid time units are: ns, us (or µs), ms, s, m, h. |
| 34 | * |
| 35 | * @default "8760h" (1 year) |
| 36 | */ |
| 37 | duration?: string; |
| 38 | /** |
| 39 | * A version number identifying the current client secret. Incrementing it |
| 40 | * triggers a rotation — a new client secret is generated and the previous |
| 41 | * secret remains valid until `previousClientSecretExpiresAt`. |
| 42 | * |
| 43 | * @default 1 |
| 44 | */ |
| 45 | clientSecretVersion?: number; |
| 46 | /** |
| 47 | * The expiration of the previous client secret (RFC3339 timestamp). Only |
| 48 | * meaningful after a rotation; may be extended to give consumers more |
| 49 | * time to roll over to the new secret. |
| 50 | */ |
| 51 | previousClientSecretExpiresAt?: string; |
| 52 | }; |
| 53 | |
| 54 | export type ServiceToken = Resource< |
| 55 | "Cloudflare.Access.ServiceToken", |
| 56 | ServiceTokenProps, |
| 57 | { |
| 58 | /** UUID of the service token assigned by Cloudflare. */ |
| 59 | serviceTokenId: string; |
| 60 | /** Cloudflare account that owns the service token. */ |
| 61 | accountId: string; |
| 62 | /** Client ID sent in the `CF-Access-Client-ID` request header. */ |
| 63 | clientId: string; |
| 64 | /** |
| 65 | * Client secret sent in the `CF-Access-Client-Secret` request header. |
| 66 | * Cloudflare only returns it on create and rotate, so the provider |
| 67 | * persists it (redacted) and carries it forward on read. |
| 68 | */ |
| 69 | clientSecret: Redacted.Redacted<string> | undefined; |
| 70 | /** Display name reported by Cloudflare. */ |
| 71 | name: string; |
| 72 | /** Validity duration reported by Cloudflare, e.g. `8760h`. */ |
| 73 | duration: string | undefined; |
| 74 | /** Expiration timestamp of the current client secret. */ |
| 75 | expiresAt: string | undefined; |
| 76 | /** The client secret version this token was last reconciled to. */ |
| 77 | clientSecretVersion: number; |
| 78 | }, |
| 79 | never, |
| 80 | Providers |
| 81 | >; |
| 82 | |
| 83 | /** |
| 84 | * A Cloudflare Zero Trust Access service token. Service tokens let |
| 85 | * machine-to-machine clients authenticate to Access-protected applications |
| 86 | * by sending the `CF-Access-Client-ID` / `CF-Access-Client-Secret` headers. |
| 87 | * |
| 88 | * The client secret is only revealed by Cloudflare on create and rotate; the |
| 89 | * provider stores it redacted in state and carries it forward across reads. |
| 90 | * ### Creating a Service Token |
| 91 | * **Example:** Basic token with a generated name |
| 92 | * ```typescript |
| 93 | * const token = yield* Cloudflare.Access.ServiceToken("Ci", {}); |
| 94 | * // token.clientId / token.clientSecret authenticate requests |
| 95 | * ``` |
| 96 | * |
| 97 | * **Example:** Token with an explicit name and validity |
| 98 | * ```typescript |
| 99 | * const token = yield* Cloudflare.Access.ServiceToken("Deploys", { |
| 100 | * name: "deploy-bot", |
| 101 | * duration: "17520h", // 2 years |
| 102 | * }); |
| 103 | * ``` |
| 104 | * |
| 105 | * ### Rotating the Secret |
| 106 | * **Example:** Increment clientSecretVersion to rotate |
| 107 | * ```typescript |
| 108 | * const token = yield* Cloudflare.Access.ServiceToken("Ci", { |
| 109 | * clientSecretVersion: 2, // was 1 — bumping rotates the secret |
| 110 | * }); |
| 111 | * ``` |
| 112 | * |
| 113 | * ### Authorizing a Token |
| 114 | * **Example:** Reference from an Access policy |
| 115 | * ```typescript |
| 116 | * const token = yield* Cloudflare.Access.ServiceToken("Ci", {}); |
| 117 | * |
| 118 | * const policy = yield* Cloudflare.Access.Policy("AllowCi", { |
| 119 | * decision: "non_identity", |
| 120 | * include: [{ serviceToken: { tokenId: token.serviceTokenId } }], |
| 121 | * }); |
| 122 | * ``` |
| 123 | * |
| 124 | * @resource |
| 125 | * @product Access |
| 126 | * @category Cloudflare One (Zero Trust) |
| 127 | */ |
| 128 | export const ServiceToken = Resource<ServiceToken>("Cloudflare.Access.ServiceToken"); |
| 129 | |
| 130 | export const isServiceToken = (value: unknown): value is ServiceToken => |
| 131 | Predicate.hasProperty(value, "Type") && value.Type === "Cloudflare.Access.ServiceToken"; |
| 132 | |
| 133 | export const ServiceTokenProvider = () => |
| 134 | Provider.succeed(ServiceToken, { |
| 135 | stables: ["serviceTokenId", "accountId", "clientId"], |
| 136 | list: Effect.fn(function* () { |
| 137 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 138 | return yield* zeroTrust.listAccessServiceTokensForAccount.pages({ accountId }).pipe( |
| 139 | Stream.runCollect, |
| 140 | Effect.map((chunk) => |
| 141 | Array.from(chunk).flatMap((page) => |
| 142 | (page.result ?? []) |
| 143 | .filter( |
| 144 | ( |
| 145 | t, |
| 146 | ): t is (typeof page.result)[number] & { |
| 147 | id: string; |
| 148 | clientId: string; |
| 149 | } => t.id != null && t.clientId != null, |
| 150 | ) |
| 151 | .map((t) => ({ |
| 152 | serviceTokenId: t.id, |
| 153 | accountId, |
| 154 | clientId: t.clientId, |
| 155 | // The secret is only revealed on create/rotate, never on |
| 156 | // enumeration — match read and leave it undefined. |
| 157 | clientSecret: undefined, |
| 158 | name: t.name ?? "", |
| 159 | duration: t.duration ?? undefined, |
| 160 | expiresAt: t.expiresAt ?? undefined, |
| 161 | clientSecretVersion: 1, |
| 162 | })), |
| 163 | ), |
| 164 | ), |
| 165 | ); |
| 166 | }), |
| 167 | diff: Effect.fn(function* ({ news, output }) { |
| 168 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 169 | if (!isResolved(news)) return undefined; |
| 170 | if ((output?.accountId ?? accountId) !== accountId) { |
| 171 | return { action: "replace" } as const; |
| 172 | } |
| 173 | // name/duration converge via PUT; clientSecretVersion bumps rotate. |
| 174 | }), |
| 175 | read: Effect.fn(function* ({ id, output, olds }) { |
| 176 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 177 | const acct = output?.accountId ?? accountId; |
| 178 | if (output?.serviceTokenId) { |
| 179 | const direct = yield* zeroTrust |
| 180 | .getAccessServiceTokenForAccount({ |
| 181 | accountId: acct, |
| 182 | serviceTokenId: output.serviceTokenId, |
| 183 | }) |
| 184 | .pipe(Effect.catchTag("AccessServiceTokenNotFound", () => Effect.undefined)); |
| 185 | if (direct && direct.id) { |
| 186 | return { |
| 187 | serviceTokenId: direct.id, |
| 188 | accountId: acct, |
| 189 | clientId: direct.clientId ?? output.clientId, |
| 190 | // The API never returns the secret on GET — carry it forward. |
| 191 | clientSecret: output.clientSecret, |
| 192 | name: direct.name ?? output.name, |
| 193 | duration: direct.duration ?? output.duration, |
| 194 | expiresAt: direct.expiresAt ?? output.expiresAt, |
| 195 | clientSecretVersion: output.clientSecretVersion, |
| 196 | }; |
| 197 | } |
| 198 | } |
| 199 | const name = yield* createTokenName(id, olds?.name ?? output?.name); |
| 200 | const existing = yield* findTokenByName(acct, name); |
| 201 | if (!existing || !existing.id || !existing.clientId) return undefined; |
| 202 | return { |
| 203 | serviceTokenId: existing.id, |
| 204 | accountId: acct, |
| 205 | clientId: existing.clientId, |
| 206 | clientSecret: output?.clientSecret, |
| 207 | name: existing.name ?? name, |
| 208 | duration: existing.duration ?? undefined, |
| 209 | expiresAt: existing.expiresAt ?? undefined, |
| 210 | clientSecretVersion: output?.clientSecretVersion ?? 1, |
| 211 | }; |
| 212 | }), |
| 213 | reconcile: Effect.fn(function* ({ id, news = {} as ServiceTokenProps, olds, output }) { |
| 214 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 215 | const name = yield* createTokenName(id, news.name); |
| 216 | const acct = output?.accountId ?? accountId; |
| 217 | const desiredVersion = news.clientSecretVersion ?? 1; |
| 218 | |
| 219 | // Observe — prefer the cached id, fall back to a name lookup so we |
| 220 | // recover from out-of-band deletes and partial state-persistence |
| 221 | // failures. |
| 222 | let observed: ObservedToken | undefined; |
| 223 | if (output?.serviceTokenId) { |
| 224 | observed = yield* zeroTrust |
| 225 | .getAccessServiceTokenForAccount({ |
| 226 | accountId: acct, |
| 227 | serviceTokenId: output.serviceTokenId, |
| 228 | }) |
| 229 | .pipe(Effect.catchTag("AccessServiceTokenNotFound", () => Effect.undefined)); |
| 230 | } |
| 231 | if (!observed || !observed.id) { |
| 232 | observed = yield* findTokenByName(acct, name); |
| 233 | } |
| 234 | |
| 235 | // Ensure — create the token when missing, capturing the one-time |
| 236 | // client secret. Tolerate a same-named create race by re-observing. |
| 237 | if (!observed || !observed.id) { |
| 238 | const created = yield* zeroTrust |
| 239 | .createAccessServiceTokenForAccount({ |
| 240 | accountId: acct, |
| 241 | name, |
| 242 | duration: news.duration, |
| 243 | clientSecretVersion: news.clientSecretVersion, |
| 244 | previousClientSecretExpiresAt: news.previousClientSecretExpiresAt, |
| 245 | }) |
| 246 | .pipe( |
| 247 | Effect.catch((err) => |
| 248 | Effect.gen(function* () { |
| 249 | const existing = yield* findTokenByName(acct, name); |
| 250 | if (existing && existing.id) return existing; |
| 251 | return yield* err; |
| 252 | }), |
| 253 | ), |
| 254 | ); |
| 255 | if (!created.id || !created.clientId) { |
| 256 | return yield* new ServiceTokenUnexpectedResponse({ |
| 257 | message: "ServiceToken: created token missing id", |
| 258 | }); |
| 259 | } |
| 260 | const fresh = yield* zeroTrust.getAccessServiceTokenForAccount({ |
| 261 | accountId: acct, |
| 262 | serviceTokenId: created.id, |
| 263 | }); |
| 264 | return { |
| 265 | serviceTokenId: created.id, |
| 266 | accountId: acct, |
| 267 | clientId: created.clientId, |
| 268 | clientSecret: |
| 269 | "clientSecret" in created && typeof created.clientSecret === "string" |
| 270 | ? Redacted.make(created.clientSecret) |
| 271 | : output?.clientSecret, |
| 272 | name: created.name ?? name, |
| 273 | duration: created.duration ?? news.duration, |
| 274 | expiresAt: fresh.expiresAt ?? undefined, |
| 275 | clientSecretVersion: desiredVersion, |
| 276 | }; |
| 277 | } |
| 278 | |
| 279 | // Sync — converge name/duration via PUT only when the observed state |
| 280 | // differs from the desired state. The PUT deliberately omits |
| 281 | // clientSecretVersion: rotation must go through the explicit rotate |
| 282 | // endpoint, which is the only call that returns the new secret. |
| 283 | let synced = observed; |
| 284 | if (observed.name !== name || differs(news.duration, observed.duration)) { |
| 285 | const updated = yield* zeroTrust.updateAccessServiceTokenForAccount({ |
| 286 | accountId: acct, |
| 287 | serviceTokenId: observed.id, |
| 288 | name, |
| 289 | duration: news.duration, |
| 290 | previousClientSecretExpiresAt: news.previousClientSecretExpiresAt, |
| 291 | }); |
| 292 | synced = { |
| 293 | id: updated.id ?? observed.id, |
| 294 | clientId: updated.clientId ?? observed.clientId, |
| 295 | name: updated.name ?? observed.name, |
| 296 | duration: updated.duration ?? observed.duration, |
| 297 | expiresAt: updated.expiresAt ?? observed.expiresAt, |
| 298 | }; |
| 299 | } |
| 300 | |
| 301 | // Rotate — when the declared secret version moved past the version we |
| 302 | // last reconciled, mint a new secret. The previous secret stays valid |
| 303 | // until previousClientSecretExpiresAt. |
| 304 | const priorVersion = output?.clientSecretVersion ?? olds?.clientSecretVersion ?? 1; |
| 305 | let clientSecret = output?.clientSecret; |
| 306 | if (desiredVersion > priorVersion) { |
| 307 | const rotated = yield* zeroTrust.rotateAccessServiceToken({ |
| 308 | accountId: acct, |
| 309 | serviceTokenId: synced.id!, |
| 310 | previousClientSecretExpiresAt: news.previousClientSecretExpiresAt, |
| 311 | }); |
| 312 | if (typeof rotated.clientSecret === "string") { |
| 313 | clientSecret = Redacted.make(rotated.clientSecret); |
| 314 | } |
| 315 | synced = { |
| 316 | ...synced, |
| 317 | clientId: rotated.clientId ?? synced.clientId, |
| 318 | name: rotated.name ?? synced.name, |
| 319 | duration: rotated.duration ?? synced.duration, |
| 320 | }; |
| 321 | } |
| 322 | |
| 323 | if (!synced.id || !synced.clientId) { |
| 324 | return yield* new ServiceTokenUnexpectedResponse({ |
| 325 | message: "ServiceToken: ensured token missing id", |
| 326 | }); |
| 327 | } |
| 328 | return { |
| 329 | serviceTokenId: synced.id, |
| 330 | accountId: acct, |
| 331 | clientId: synced.clientId, |
| 332 | clientSecret, |
| 333 | name: synced.name ?? name, |
| 334 | duration: synced.duration ?? news.duration, |
| 335 | expiresAt: synced.expiresAt ?? undefined, |
| 336 | clientSecretVersion: Math.max(desiredVersion, priorVersion), |
| 337 | }; |
| 338 | }), |
| 339 | delete: Effect.fn(function* ({ output }) { |
| 340 | yield* zeroTrust |
| 341 | .deleteAccessServiceTokenForAccount({ |
| 342 | accountId: output.accountId, |
| 343 | serviceTokenId: output.serviceTokenId, |
| 344 | }) |
| 345 | .pipe(Effect.catchTag("AccessServiceTokenNotFound", () => Effect.void)); |
| 346 | }), |
| 347 | }); |
| 348 | |
| 349 | const createTokenName = (id: string, name: string | undefined) => |
| 350 | Effect.gen(function* () { |
| 351 | if (name) return name; |
| 352 | return yield* createPhysicalName({ id }); |
| 353 | }); |
| 354 | |
| 355 | const findTokenByName = (acct: string, name: string) => |
| 356 | zeroTrust.listAccessServiceTokensForAccount.items({ accountId: acct }).pipe( |
| 357 | Stream.filter((t): t is ObservedToken => t.name === name), |
| 358 | Stream.runHead, |
| 359 | Effect.map(Option.getOrUndefined), |
| 360 | Effect.orElseSucceed(() => undefined), |
| 361 | ); |
| 362 | |
| 363 | // Skip no-op PUTs while treating an unset prop as "keep whatever Cloudflare |
| 364 | // has" rather than a difference. |
| 365 | const differs = (desired: string | undefined, observed: string | null | undefined) => |
| 366 | desired !== undefined && desired !== (observed ?? undefined); |
| 367 | |
| 368 | type ObservedToken = { |
| 369 | id?: string; |
| 370 | clientId?: string | null; |
| 371 | clientSecret?: string | null; |
| 372 | name?: string | null; |
| 373 | duration?: string | null; |
| 374 | expiresAt?: string | null; |
| 375 | }; |