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
| 1 | import * as tokenValidation from "@distilled.cloud/cloudflare/token-validation"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Predicate from "effect/Predicate"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { listAllZones } from "../Zone/lookup.ts"; |
| 13 | |
| 14 | const TypeId = "Cloudflare.TokenValidation.Configuration" as const; |
| 15 | type TypeId = typeof TypeId; |
| 16 | |
| 17 | /** |
| 18 | * A JSON Web Key (JWK) in a token configuration's key set. These are public |
| 19 | * keys (the public half of a JWKS), not secrets. |
| 20 | */ |
| 21 | export type JwkKey = |
| 22 | | { |
| 23 | /** Key type — RSA. */ |
| 24 | kty: "RSA"; |
| 25 | /** RSA signing algorithm the key is used with. */ |
| 26 | alg: "RS256" | "RS384" | "RS512" | "PS256" | "PS384" | "PS512"; |
| 27 | /** Key ID — must match the `kid` header of incoming JWTs. */ |
| 28 | kid: string; |
| 29 | /** RSA modulus (base64url). */ |
| 30 | n: string; |
| 31 | /** RSA public exponent (base64url). */ |
| 32 | e: string; |
| 33 | } |
| 34 | | { |
| 35 | /** Key type — elliptic curve. */ |
| 36 | kty: "EC"; |
| 37 | /** ECDSA P-256 signing algorithm. */ |
| 38 | alg: "ES256"; |
| 39 | /** Curve — P-256. */ |
| 40 | crv: "P-256"; |
| 41 | /** Key ID — must match the `kid` header of incoming JWTs. */ |
| 42 | kid: string; |
| 43 | /** EC x coordinate (base64url). */ |
| 44 | x: string; |
| 45 | /** EC y coordinate (base64url). */ |
| 46 | y: string; |
| 47 | } |
| 48 | | { |
| 49 | /** Key type — elliptic curve. */ |
| 50 | kty: "EC"; |
| 51 | /** ECDSA P-384 signing algorithm. */ |
| 52 | alg: "ES384"; |
| 53 | /** Curve — P-384. */ |
| 54 | crv: "P-384"; |
| 55 | /** Key ID — must match the `kid` header of incoming JWTs. */ |
| 56 | kid: string; |
| 57 | /** EC x coordinate (base64url). */ |
| 58 | x: string; |
| 59 | /** EC y coordinate (base64url). */ |
| 60 | y: string; |
| 61 | }; |
| 62 | |
| 63 | export interface TokenConfigurationProps { |
| 64 | /** |
| 65 | * Zone the token configuration belongs to. |
| 66 | * |
| 67 | * Stable — moving a configuration between zones triggers a replacement. |
| 68 | */ |
| 69 | zoneId: string; |
| 70 | /** |
| 71 | * Human-readable name for the configuration. If omitted, a unique name is |
| 72 | * generated from the app, stage, and logical ID. |
| 73 | * @default ${app}-${stage}-${id} |
| 74 | */ |
| 75 | title?: string; |
| 76 | /** |
| 77 | * A description that gives more details than `title`. |
| 78 | * @default "" |
| 79 | */ |
| 80 | description?: string; |
| 81 | /** |
| 82 | * Where to look for the token on incoming requests, as firewall fields — |
| 83 | * e.g. `http.request.headers["authorization"][0]`. |
| 84 | */ |
| 85 | tokenSources: string[]; |
| 86 | /** |
| 87 | * The JWKS key set used to validate token signatures. Replacing entries |
| 88 | * rotates the key set in place via the credentials endpoint. |
| 89 | */ |
| 90 | keys: JwkKey[]; |
| 91 | /** |
| 92 | * The token format. Only JWT is supported today. Cannot be changed after |
| 93 | * creation — updating this property triggers a replacement. |
| 94 | * @default "JWT" |
| 95 | */ |
| 96 | tokenType?: "JWT"; |
| 97 | } |
| 98 | |
| 99 | export interface TokenConfigurationAttributes { |
| 100 | /** Cloudflare-assigned UUID of the token configuration. */ |
| 101 | configId: string; |
| 102 | /** Zone the configuration belongs to. */ |
| 103 | zoneId: string; |
| 104 | /** Human-readable name of the configuration. */ |
| 105 | title: string; |
| 106 | /** Description of the configuration. */ |
| 107 | description: string; |
| 108 | /** Where the token is looked for on incoming requests. */ |
| 109 | tokenSources: string[]; |
| 110 | /** The token format. */ |
| 111 | tokenType: "JWT" | (string & {}); |
| 112 | /** The JWKS key set currently active on the configuration. */ |
| 113 | keys: JwkKey[]; |
| 114 | /** ISO8601 creation timestamp. */ |
| 115 | createdAt: string; |
| 116 | /** ISO8601 last-modified timestamp. */ |
| 117 | lastUpdated: string; |
| 118 | } |
| 119 | |
| 120 | export type TokenConfiguration = Resource< |
| 121 | TypeId, |
| 122 | TokenConfigurationProps, |
| 123 | TokenConfigurationAttributes, |
| 124 | never, |
| 125 | Providers |
| 126 | >; |
| 127 | |
| 128 | /** |
| 129 | * An API Shield JWT validation token configuration — the JWKS key material |
| 130 | * and token source locations used to validate JSON Web Tokens on a zone. |
| 131 | * |
| 132 | * A configuration holds a set of public JWKs (`keys`) plus the request |
| 133 | * fields where the token is found (`tokenSources`). Rules |
| 134 | * ({@link Rule}) then reference the configuration by UUID in |
| 135 | * their expression (e.g. `is_jwt_valid("<configId>")`) to enforce |
| 136 | * validation on selected hosts/operations. |
| 137 | * |
| 138 | * JWT validation is an API Shield feature (Enterprise add-on) — accounts |
| 139 | * without the entitlement receive the typed `TokenValidationNotEntitled` |
| 140 | * error (Cloudflare code 10403) on every call. |
| 141 | * |
| 142 | * Title, description, and token sources are patched in place; the key set |
| 143 | * is rotated in place via the credentials endpoint. Only `zoneId` and |
| 144 | * `tokenType` force a replacement. |
| 145 | * ### Creating a Configuration |
| 146 | * **Example:** JWT configuration with an RSA key |
| 147 | * ```typescript |
| 148 | * const config = yield* Cloudflare.TokenValidation.TokenConfiguration("ApiJwt", { |
| 149 | * zoneId: zone.zoneId, |
| 150 | * tokenSources: ['http.request.headers["authorization"][0]'], |
| 151 | * keys: [ |
| 152 | * { |
| 153 | * kty: "RSA", |
| 154 | * alg: "RS256", |
| 155 | * kid: "key-2026-01", |
| 156 | * n: "<base64url modulus>", |
| 157 | * e: "AQAB", |
| 158 | * }, |
| 159 | * ], |
| 160 | * }); |
| 161 | * ``` |
| 162 | * |
| 163 | * ### Rotating Keys |
| 164 | * **Example:** Replace the key set in place |
| 165 | * ```typescript |
| 166 | * // Changing `keys` PUTs the full key set to the credentials endpoint — |
| 167 | * // the configuration (and its UUID) stays in place. |
| 168 | * const config = yield* Cloudflare.TokenValidation.TokenConfiguration("ApiJwt", { |
| 169 | * zoneId: zone.zoneId, |
| 170 | * tokenSources: ['http.request.headers["authorization"][0]'], |
| 171 | * keys: [oldKey, newKey], |
| 172 | * }); |
| 173 | * ``` |
| 174 | * |
| 175 | * ### Enforcing Validation |
| 176 | * **Example:** Reference the configuration from a rule |
| 177 | * ```typescript |
| 178 | * yield* Cloudflare.TokenValidation.Rule("RequireJwt", { |
| 179 | * zoneId: zone.zoneId, |
| 180 | * action: "block", |
| 181 | * expression: Output.interpolate`is_jwt_valid("${config.configId}")`, |
| 182 | * selector: { include: [{ host: ["api.example.com"] }] }, |
| 183 | * }); |
| 184 | * ``` |
| 185 | * |
| 186 | * @see https://developers.cloudflare.com/api-shield/security/jwt-validation/ |
| 187 | * |
| 188 | * @resource |
| 189 | * @product Token Validation |
| 190 | * @category Application Security |
| 191 | */ |
| 192 | export const TokenConfiguration = Resource<TokenConfiguration>(TypeId); |
| 193 | |
| 194 | /** |
| 195 | * Returns true if the given value is a TokenConfiguration resource. |
| 196 | */ |
| 197 | export const isTokenConfiguration = (value: unknown): value is TokenConfiguration => |
| 198 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 199 | |
| 200 | export const TokenConfigurationProvider = () => |
| 201 | Provider.succeed(TokenConfiguration, { |
| 202 | stables: ["configId", "zoneId", "tokenType", "createdAt"], |
| 203 | |
| 204 | list: Effect.fn(function* () { |
| 205 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 206 | // Configurations are zone-scoped; the list op is keyed per zone. |
| 207 | // Enumerate every zone, fan out the per-zone list, and flatten. |
| 208 | const zones = yield* listAllZones(accountId); |
| 209 | const rows = yield* Effect.forEach( |
| 210 | zones, |
| 211 | (zone) => |
| 212 | tokenValidation.listConfigurations.items({ zoneId: zone.id }).pipe( |
| 213 | Stream.runCollect, |
| 214 | Effect.map((chunk) => Array.from(chunk).map((c) => toAttributes(c, zone.id))), |
| 215 | // JWT validation is entitlement-gated and freshly minted tokens |
| 216 | // can briefly 403 — skip zones we can't enumerate. |
| 217 | Effect.catchTag(["TokenValidationNotEntitled", "Forbidden"], () => Effect.succeed([])), |
| 218 | ), |
| 219 | { concurrency: 10 }, |
| 220 | ); |
| 221 | return rows.flat(); |
| 222 | }), |
| 223 | |
| 224 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 225 | if (!isResolved(news)) return undefined; |
| 226 | // Moving between zones replaces the configuration. |
| 227 | const oldZoneId = output?.zoneId ?? olds?.zoneId; |
| 228 | if (typeof oldZoneId === "string" && oldZoneId !== news.zoneId) { |
| 229 | return { action: "replace" } as const; |
| 230 | } |
| 231 | // tokenType is not patchable (and "JWT" is the only value today). |
| 232 | const oldType = output?.tokenType ?? olds?.tokenType ?? "JWT"; |
| 233 | if ((news.tokenType ?? "JWT") !== oldType) { |
| 234 | return { action: "replace" } as const; |
| 235 | } |
| 236 | return undefined; |
| 237 | }), |
| 238 | |
| 239 | read: Effect.fn(function* ({ id, output, olds }) { |
| 240 | const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined); |
| 241 | if (zoneId === undefined) return undefined; |
| 242 | |
| 243 | // Owned path: refresh by our persisted UUID. |
| 244 | if (output?.configId) { |
| 245 | const observed = yield* getConfiguration(zoneId, output.configId); |
| 246 | if (observed) return toAttributes(observed, zoneId); |
| 247 | } |
| 248 | |
| 249 | // Cold read — recover from lost state by matching the deterministic |
| 250 | // physical title. Configurations carry no ownership markers, so an |
| 251 | // existing match is reported as `Unowned` and the engine gates |
| 252 | // takeover behind the adopt policy. |
| 253 | const title = yield* createConfigurationTitle(id, olds?.title); |
| 254 | const match = yield* findByTitle(zoneId, title); |
| 255 | if (match) return Unowned(toAttributes(match, zoneId)); |
| 256 | return undefined; |
| 257 | }), |
| 258 | |
| 259 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 260 | // Inputs have been resolved to concrete values by Plan. |
| 261 | const zoneId = news.zoneId as string; |
| 262 | const title = yield* createConfigurationTitle(id, news.title); |
| 263 | |
| 264 | // 1. Observe — the UUID cached on `output` is a hint, not a |
| 265 | // guarantee: a 404 falls through to "missing" and we recreate. |
| 266 | let observed = output?.configId |
| 267 | ? yield* getConfiguration(zoneId, output.configId) |
| 268 | : undefined; |
| 269 | |
| 270 | // 2. Ensure — greenfield (or out-of-band delete): create with the |
| 271 | // full desired body. Titles are not unique on Cloudflare's side, |
| 272 | // so there is no AlreadyExists race to tolerate. |
| 273 | if (!observed) { |
| 274 | observed = yield* tokenValidation.createConfiguration({ |
| 275 | zoneId, |
| 276 | title, |
| 277 | description: news.description ?? "", |
| 278 | tokenSources: news.tokenSources, |
| 279 | tokenType: news.tokenType ?? "JWT", |
| 280 | credentials: { keys: news.keys }, |
| 281 | }); |
| 282 | return toAttributes(observed, zoneId); |
| 283 | } |
| 284 | |
| 285 | // 3. Sync metadata — diff observed title/description/tokenSources |
| 286 | // against desired; PATCH only the delta, skip on no-op. |
| 287 | const desiredDescription = news.description ?? ""; |
| 288 | const metadataDirty = |
| 289 | observed.title !== title || |
| 290 | observed.description !== desiredDescription || |
| 291 | !sameStrings(observed.tokenSources, news.tokenSources); |
| 292 | if (metadataDirty) { |
| 293 | yield* tokenValidation.patchConfiguration({ |
| 294 | zoneId, |
| 295 | configId: observed.id, |
| 296 | title, |
| 297 | description: desiredDescription, |
| 298 | tokenSources: news.tokenSources, |
| 299 | }); |
| 300 | } |
| 301 | |
| 302 | // 4. Sync key set — compare the observed JWKS against the desired |
| 303 | // one by full key material; PUT the full set on any difference |
| 304 | // (the credentials endpoint replaces the whole key set). |
| 305 | if (!sameKeys(observed.credentials.keys, news.keys)) { |
| 306 | yield* tokenValidation.putConfigurationCredential({ |
| 307 | zoneId, |
| 308 | configId: observed.id, |
| 309 | keys: news.keys, |
| 310 | }); |
| 311 | } |
| 312 | |
| 313 | // 5. Return — re-read so attributes reflect the final cloud state. |
| 314 | const final = yield* getConfiguration(zoneId, observed.id); |
| 315 | return toAttributes(final ?? observed, zoneId); |
| 316 | }), |
| 317 | |
| 318 | delete: Effect.fn(function* ({ output }) { |
| 319 | // Cloudflare may answer DELETE for an already-gone configuration with |
| 320 | // `result: null`, which the typed response decode rejects — observe |
| 321 | // first and treat missing as done. |
| 322 | const observed = yield* getConfiguration(output.zoneId, output.configId); |
| 323 | if (!observed) return; |
| 324 | yield* tokenValidation |
| 325 | .deleteConfiguration({ |
| 326 | zoneId: output.zoneId, |
| 327 | configId: output.configId, |
| 328 | }) |
| 329 | .pipe(Effect.catchTag("TokenConfigurationNotFound", () => Effect.void)); |
| 330 | }), |
| 331 | }); |
| 332 | |
| 333 | type ObservedConfiguration = tokenValidation.GetConfigurationResponse; |
| 334 | |
| 335 | /** |
| 336 | * Read a configuration by UUID, mapping "gone" |
| 337 | * (`TokenConfigurationNotFound`, HTTP 404) to `undefined`. |
| 338 | */ |
| 339 | const getConfiguration = (zoneId: string, configId: string) => |
| 340 | tokenValidation.getConfiguration({ zoneId, configId }).pipe( |
| 341 | Effect.map((c): ObservedConfiguration | undefined => c), |
| 342 | Effect.catchTag("TokenConfigurationNotFound", () => Effect.undefined), |
| 343 | ); |
| 344 | |
| 345 | /** |
| 346 | * Find a configuration by exact title. Titles are not unique on |
| 347 | * Cloudflare's side; if several match, pick the oldest for determinism. |
| 348 | */ |
| 349 | const findByTitle = (zoneId: string, title: string) => |
| 350 | tokenValidation.listConfigurations.items({ zoneId }).pipe( |
| 351 | Stream.runCollect, |
| 352 | Effect.map((chunk) => |
| 353 | Array.from(chunk) |
| 354 | .filter((c) => c.title === title) |
| 355 | .sort((a, b) => a.createdAt.localeCompare(b.createdAt)) |
| 356 | .at(0), |
| 357 | ), |
| 358 | ); |
| 359 | |
| 360 | const createConfigurationTitle = (id: string, title: string | undefined) => |
| 361 | Effect.gen(function* () { |
| 362 | return title ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 363 | }); |
| 364 | |
| 365 | const sameStrings = (observed: readonly string[], desired: readonly string[]) => |
| 366 | observed.length === desired.length && |
| 367 | [...observed].sort().join(" |