The best way to control Claude Code, Codex and more from any computer or phone
| 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.Rule" as const; |
| 15 | type TypeId = typeof TypeId; |
| 16 | |
| 17 | /** |
| 18 | * Action applied to requests that match the selector and fail the rule's |
| 19 | * expression. |
| 20 | */ |
| 21 | export type RuleAction = "log" | "block"; |
| 22 | |
| 23 | /** |
| 24 | * Selects the operations covered by a token validation rule. |
| 25 | */ |
| 26 | export interface RuleSelector { |
| 27 | /** |
| 28 | * Operations to include, by host. |
| 29 | */ |
| 30 | include?: { |
| 31 | /** Hostnames whose operations the rule covers. */ |
| 32 | host?: string[]; |
| 33 | }[]; |
| 34 | /** |
| 35 | * Operations to exclude, by API Shield operation ID. |
| 36 | */ |
| 37 | exclude?: { |
| 38 | /** API Shield operation IDs the rule must not cover. */ |
| 39 | operationIds?: string[]; |
| 40 | }[]; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Desired ordering of a rule among the zone's token validation rules. |
| 45 | * Applied via PATCH whenever set; ordering is not tracked in attributes. |
| 46 | */ |
| 47 | export type RulePosition = |
| 48 | | { /** Absolute position in the rule list. */ index: number } |
| 49 | | { /** Place the rule before this rule ID. */ before: string } |
| 50 | | { /** Place the rule after this rule ID. */ after: string }; |
| 51 | |
| 52 | export interface RuleProps { |
| 53 | /** |
| 54 | * Zone the rule applies to. |
| 55 | * |
| 56 | * Stable — moving a rule between zones triggers a replacement. |
| 57 | */ |
| 58 | zoneId: string; |
| 59 | /** |
| 60 | * Human-readable name for the rule. If omitted, a unique name is |
| 61 | * generated from the app, stage, and logical ID. |
| 62 | * @default ${app}-${stage}-${id} |
| 63 | */ |
| 64 | title?: string; |
| 65 | /** |
| 66 | * A description that gives more details than `title`. |
| 67 | * @default "" |
| 68 | */ |
| 69 | description?: string; |
| 70 | /** |
| 71 | * Toggle the rule on or off. |
| 72 | * @default true |
| 73 | */ |
| 74 | enabled?: boolean; |
| 75 | /** |
| 76 | * Action to take on requests that match the selector and fail the |
| 77 | * expression: `log` or `block`. |
| 78 | */ |
| 79 | action: RuleAction; |
| 80 | /** |
| 81 | * Rule expression — requests that fail it are subject to `action`, |
| 82 | * e.g. `is_jwt_valid("<configId>")`. Reference a |
| 83 | * {@link TokenConfiguration} by interpolating its `configId` output. |
| 84 | */ |
| 85 | expression: string; |
| 86 | /** |
| 87 | * Which operations the rule covers (include by host, exclude by API |
| 88 | * Shield operation ID). |
| 89 | */ |
| 90 | selector: RuleSelector; |
| 91 | /** |
| 92 | * Desired ordering among the zone's rules. Applied via PATCH on every |
| 93 | * deploy it is set; omit to leave ordering untouched (new rules append). |
| 94 | */ |
| 95 | position?: RulePosition; |
| 96 | } |
| 97 | |
| 98 | export interface RuleAttributes { |
| 99 | /** Cloudflare-assigned UUID of the rule. */ |
| 100 | ruleId: string; |
| 101 | /** Zone the rule belongs to. */ |
| 102 | zoneId: string; |
| 103 | /** Human-readable name of the rule. */ |
| 104 | title: string; |
| 105 | /** Description of the rule. */ |
| 106 | description: string; |
| 107 | /** Whether the rule is enabled. */ |
| 108 | enabled: boolean; |
| 109 | /** Action applied to matching requests that fail the expression. */ |
| 110 | action: RuleAction; |
| 111 | /** The rule's expression. */ |
| 112 | expression: string; |
| 113 | /** Which operations the rule covers. */ |
| 114 | selector: { |
| 115 | include?: { host?: string[] }[]; |
| 116 | exclude?: { operationIds?: string[] }[]; |
| 117 | }; |
| 118 | /** ISO8601 creation timestamp, when reported by the API. */ |
| 119 | createdAt: string | undefined; |
| 120 | /** ISO8601 last-modified timestamp, when reported by the API. */ |
| 121 | lastUpdated: string | undefined; |
| 122 | } |
| 123 | |
| 124 | export type Rule = Resource<TypeId, RuleProps, RuleAttributes, never, Providers>; |
| 125 | |
| 126 | /** |
| 127 | * An API Shield JWT validation rule — selects operations/hosts on a zone |
| 128 | * and enforces a token validation expression with a `log` or `block` |
| 129 | * action. |
| 130 | * |
| 131 | * A rule references a {@link TokenConfiguration} by UUID inside its |
| 132 | * `expression` (e.g. `is_jwt_valid("<configId>")`). Keep the rule |
| 133 | * depending on the configuration through its output so destroy order is |
| 134 | * rule first, configuration second. |
| 135 | * |
| 136 | * JWT validation is an API Shield feature (Enterprise add-on) — accounts |
| 137 | * without the entitlement receive the typed `TokenValidationNotEntitled` |
| 138 | * error (Cloudflare code 10403) on every call. |
| 139 | * |
| 140 | * All fields are patched in place; only `zoneId` forces a replacement. |
| 141 | * ### Creating a Rule |
| 142 | * **Example:** Log requests with invalid JWTs |
| 143 | * ```typescript |
| 144 | * const rule = yield* Cloudflare.TokenValidation.Rule("LogInvalidJwt", { |
| 145 | * zoneId: zone.zoneId, |
| 146 | * action: "log", |
| 147 | * expression: Output.interpolate`is_jwt_valid("${config.configId}")`, |
| 148 | * selector: { include: [{ host: ["api.example.com"] }] }, |
| 149 | * }); |
| 150 | * ``` |
| 151 | * |
| 152 | * **Example:** Block invalid JWTs, excluding a public operation |
| 153 | * ```typescript |
| 154 | * yield* Cloudflare.TokenValidation.Rule("BlockInvalidJwt", { |
| 155 | * zoneId: zone.zoneId, |
| 156 | * action: "block", |
| 157 | * expression: Output.interpolate`is_jwt_valid("${config.configId}")`, |
| 158 | * selector: { |
| 159 | * include: [{ host: ["api.example.com"] }], |
| 160 | * exclude: [{ operationIds: [healthCheck.operationId] }], |
| 161 | * }, |
| 162 | * }); |
| 163 | * ``` |
| 164 | * |
| 165 | * ### Updating a Rule |
| 166 | * **Example:** Disable a rule in place |
| 167 | * ```typescript |
| 168 | * yield* Cloudflare.TokenValidation.Rule("BlockInvalidJwt", { |
| 169 | * zoneId: zone.zoneId, |
| 170 | * enabled: false, |
| 171 | * action: "block", |
| 172 | * expression: Output.interpolate`is_jwt_valid("${config.configId}")`, |
| 173 | * selector: { include: [{ host: ["api.example.com"] }] }, |
| 174 | * }); |
| 175 | * ``` |
| 176 | * |
| 177 | * @see https://developers.cloudflare.com/api-shield/security/jwt-validation/ |
| 178 | * |
| 179 | * @resource |
| 180 | * @product Token Validation |
| 181 | * @category Application Security |
| 182 | */ |
| 183 | export const Rule = Resource<Rule>(TypeId); |
| 184 | |
| 185 | /** |
| 186 | * Returns true if the given value is a Rule resource. |
| 187 | */ |
| 188 | export const isRule = (value: unknown): value is Rule => |
| 189 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 190 | |
| 191 | export const RuleProvider = () => |
| 192 | Provider.succeed(Rule, { |
| 193 | stables: ["ruleId", "zoneId", "createdAt"], |
| 194 | |
| 195 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 196 | if (!isResolved(news)) return undefined; |
| 197 | // Moving between zones replaces the rule. |
| 198 | const oldZoneId = output?.zoneId ?? olds?.zoneId; |
| 199 | if (typeof oldZoneId === "string" && oldZoneId !== news.zoneId) { |
| 200 | return { action: "replace" } as const; |
| 201 | } |
| 202 | return undefined; |
| 203 | }), |
| 204 | |
| 205 | read: Effect.fn(function* ({ id, output, olds }) { |
| 206 | const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined); |
| 207 | if (zoneId === undefined) return undefined; |
| 208 | |
| 209 | // Owned path: refresh by our persisted UUID. |
| 210 | if (output?.ruleId) { |
| 211 | const observed = yield* getRule(zoneId, output.ruleId); |
| 212 | if (observed) return toAttributes(observed, zoneId); |
| 213 | } |
| 214 | |
| 215 | // Cold read — recover from lost state by matching the deterministic |
| 216 | // physical title (client-side; the list API cannot filter by title). |
| 217 | // Rules carry no ownership markers, so an existing match is reported |
| 218 | // as `Unowned` and the engine gates takeover behind the adopt policy. |
| 219 | const title = yield* createRuleTitle(id, olds?.title); |
| 220 | const match = yield* findByTitle(zoneId, title); |
| 221 | if (match?.id) { |
| 222 | const observed = yield* getRule(zoneId, match.id); |
| 223 | if (observed) return Unowned(toAttributes(observed, zoneId)); |
| 224 | } |
| 225 | return undefined; |
| 226 | }), |
| 227 | |
| 228 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 229 | // Inputs have been resolved to concrete values by Plan. |
| 230 | const zoneId = news.zoneId as string; |
| 231 | const expression = news.expression as string; |
| 232 | const title = yield* createRuleTitle(id, news.title); |
| 233 | const desired = { |
| 234 | title, |
| 235 | description: news.description ?? "", |
| 236 | enabled: news.enabled ?? true, |
| 237 | action: news.action, |
| 238 | expression, |
| 239 | selector: toApiSelector(news.selector), |
| 240 | }; |
| 241 | |
| 242 | // 1. Observe — the UUID cached on `output` is a hint, not a |
| 243 | // guarantee: a 404 falls through to "missing" and we recreate. |
| 244 | const observed = output?.ruleId ? yield* getRule(zoneId, output.ruleId) : undefined; |
| 245 | |
| 246 | // 2. Ensure — greenfield (or out-of-band delete): create with the |
| 247 | // full desired body. Titles are not unique on Cloudflare's side, |
| 248 | // so there is no AlreadyExists race to tolerate. |
| 249 | if (!observed) { |
| 250 | const created = yield* tokenValidation.createRule({ |
| 251 | zoneId, |
| 252 | ...desired, |
| 253 | }); |
| 254 | // Ordering is only expressible via PATCH; apply it when requested. |
| 255 | if (news.position !== undefined && created.id) { |
| 256 | const positioned = yield* tokenValidation.patchRule({ |
| 257 | zoneId, |
| 258 | ruleId: created.id, |
| 259 | position: news.position, |
| 260 | }); |
| 261 | return toAttributes(positioned, zoneId); |
| 262 | } |
| 263 | return toAttributes(created, zoneId); |
| 264 | } |
| 265 | |
| 266 | // 3. Sync — diff observed cloud state against desired field by |
| 267 | // field; PATCH only when something differs (or an explicit |
| 268 | // `position` must be enforced — ordering cannot be observed |
| 269 | // cheaply, so a set position is re-asserted on every deploy). |
| 270 | const dirty = |
| 271 | observed.title !== desired.title || |
| 272 | observed.description !== desired.description || |
| 273 | observed.enabled !== desired.enabled || |
| 274 | observed.action !== desired.action || |
| 275 | observed.expression !== desired.expression || |
| 276 | !sameSelector(observed.selector, desired.selector); |
| 277 | |
| 278 | if (!dirty && news.position === undefined) { |
| 279 | return toAttributes(observed, zoneId); |
| 280 | } |
| 281 | |
| 282 | const patched = yield* tokenValidation.patchRule({ |
| 283 | zoneId, |
| 284 | ruleId: observed.id ?? output!.ruleId, |
| 285 | ...desired, |
| 286 | ...(news.position !== undefined ? { position: news.position } : {}), |
| 287 | }); |
| 288 | return toAttributes(patched, zoneId); |
| 289 | }), |
| 290 | |
| 291 | delete: Effect.fn(function* ({ output }) { |
| 292 | yield* tokenValidation |
| 293 | .deleteRule({ zoneId: output.zoneId, ruleId: output.ruleId }) |
| 294 | .pipe(Effect.catchTag("TokenValidationRuleNotFound", () => Effect.void)); |
| 295 | }), |
| 296 | |
| 297 | list: Effect.fn(function* () { |
| 298 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 299 | // Token validation rules live inside a zone with no account-wide |
| 300 | // enumeration API — fan out across every zone and list rules per |
| 301 | // zone, paginating each zone exhaustively. |
| 302 | const zones = yield* listAllZones(accountId); |
| 303 | const rows = yield* Effect.forEach( |
| 304 | zones, |
| 305 | (zone) => |
| 306 | tokenValidation.listRules.pages({ zoneId: zone.id }).pipe( |
| 307 | Stream.runCollect, |
| 308 | Effect.map((chunk) => |
| 309 | Array.from(chunk).flatMap((page) => |
| 310 | (page.result ?? []).map((rule): RuleAttributes => toAttributes(rule, zone.id)), |
| 311 | ), |
| 312 | ), |
| 313 | // JWT validation is an API Shield (Enterprise) feature; zones |
| 314 | // without the entitlement, or with partial permissions, reject |
| 315 | // the route — skip them rather than failing the whole listing. |
| 316 | Effect.catchTag(["TokenValidationNotEntitled", "Forbidden"], () => |
| 317 | Effect.succeed([] as RuleAttributes[]), |
| 318 | ), |
| 319 | ), |
| 320 | { concurrency: 10 }, |
| 321 | ); |
| 322 | return rows.flat(); |
| 323 | }), |
| 324 | }); |
| 325 | |
| 326 | type ObservedRule = tokenValidation.GetRuleResponse; |
| 327 | type ApiSelector = tokenValidation.CreateRuleRequest["selector"]; |
| 328 | |
| 329 | /** |
| 330 | * Read a rule by UUID, mapping "gone" (`TokenValidationRuleNotFound`, |
| 331 | * HTTP 404) to `undefined`. |
| 332 | */ |
| 333 | const getRule = (zoneId: string, ruleId: string) => |
| 334 | tokenValidation.getRule({ zoneId, ruleId }).pipe( |
| 335 | Effect.map((r): ObservedRule | undefined => r), |
| 336 | Effect.catchTag("TokenValidationRuleNotFound", () => Effect.undefined), |
| 337 | ); |
| 338 | |
| 339 | /** |
| 340 | * Find a rule by exact title. The list API cannot filter by title, so |
| 341 | * match client-side; if several rules share the title, pick the oldest |
| 342 | * for determinism. |
| 343 | */ |
| 344 | const findByTitle = (zoneId: string, title: string) => |
| 345 | tokenValidation.listRules.items({ zoneId }).pipe( |
| 346 | Stream.runCollect, |
| 347 | Effect.map((chunk) => |
| 348 | Array.from(chunk) |
| 349 | .filter((r) => r.title === title) |
| 350 | .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")) |
| 351 | .at(0), |
| 352 | ), |
| 353 | ); |
| 354 | |
| 355 | const createRuleTitle = (id: string, title: string | undefined) => |
| 356 | Effect.gen(function* () { |
| 357 | return title ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 358 | }); |
| 359 | |
| 360 | /** |
| 361 | * Convert resolved props' selector to the API request shape (the |
| 362 | * `Input<string>` operation IDs have been resolved by Plan). |
| 363 | */ |
| 364 | const toApiSelector = (selector: RuleSelector): ApiSelector => ({ |
| 365 | ...(selector.include !== undefined |
| 366 | ? { include: selector.include.map((entry) => ({ host: entry.host })) } |
| 367 | : {}), |
| 368 | ...(selector.exclude !== undefined |
| 369 | ? { |
| 370 | exclude: selector.exclude.map((entry) => ({ |
| 371 | operationIds: entry.operationIds as string[] | undefined, |
| 372 | })), |
| 373 | } |
| 374 | : {}), |
| 375 | }); |
| 376 | |
| 377 | const compareStrings = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); |
| 378 | const compareJoined = (a: ReadonlyArray<string>, b: ReadonlyArray<string>) => |
| 379 | compareStrings(a.join(","), b.join(",")); |
| 380 | |
| 381 | /** Canonical, order-insensitive form of a selector for diffing. */ |
| 382 | const canonicalSelector = (selector: ObservedRule["selector"] | ApiSelector) => |
| 383 | JSON.stringify({ |
| 384 | include: (selector.include ?? []) |
| 385 | .map((entry) => [...(entry.host ?? [])].sort(compareStrings)) |
| 386 | .sort(compareJoined), |
| 387 | exclude: (selector.exclude ?? []) |
| 388 | .map((entry) => [...(entry.operationIds ?? [])].sort(compareStrings)) |
| 389 | .sort(compareJoined), |
| 390 | }); |
| 391 | |
| 392 | const sameSelector = (observed: ObservedRule["selector"], desired: ApiSelector) => |
| 393 | canonicalSelector(observed) === canonicalSelector(desired); |
| 394 | |
| 395 | const toAttributes = ( |
| 396 | rule: |
| 397 | | ObservedRule |
| 398 | | tokenValidation.CreateRuleResponse |
| 399 | | tokenValidation.PatchRuleResponse |
| 400 | | tokenValidation.ListRulesResponse["result"][number], |
| 401 | zoneId: string, |
| 402 | ): RuleAttributes => ({ |
| 403 | ruleId: rule.id ?? "", |
| 404 | zoneId, |
| 405 | title: rule.title, |
| 406 | description: rule.description, |
| 407 | enabled: rule.enabled, |
| 408 | // Distilled widens the action enum to an open union (`string & {}`). |
| 409 | action: rule.action as RuleAction, |
| 410 | expression: rule.expression, |
| 411 | selector: { |
| 412 | ...(rule.selector.include != null |
| 413 | ? { |
| 414 | include: rule.selector.include.map((entry) => |
| 415 | entry.host != null ? { host: [...entry.host] } : {}, |
| 416 | ), |
| 417 | } |
| 418 | : {}), |
| 419 | ...(rule.selector.exclude != null |
| 420 | ? { |
| 421 | exclude: rule.selector.exclude.map((entry) => |
| 422 | entry.operationIds != null ? { operationIds: [...entry.operationIds] } : {}, |
| 423 | ), |
| 424 | } |
| 425 | : {}), |
| 426 | }, |
| 427 | createdAt: rule.createdAt ?? undefined, |
| 428 | lastUpdated: rule.lastUpdated ?? undefined, |
| 429 | }); |