The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as apiGateway from "@distilled.cloud/cloudflare/api-gateway"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Predicate from "effect/Predicate"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { listAllZones } from "../Zone/lookup.ts"; |
| 12 | |
| 13 | const TypeId = "Cloudflare.ApiShield.Operation" as const; |
| 14 | type TypeId = typeof TypeId; |
| 15 | |
| 16 | /** |
| 17 | * HTTP method of an API Shield operation. |
| 18 | */ |
| 19 | export type OperationMethod = |
| 20 | | "GET" |
| 21 | | "POST" |
| 22 | | "HEAD" |
| 23 | | "OPTIONS" |
| 24 | | "PUT" |
| 25 | | "DELETE" |
| 26 | | "CONNECT" |
| 27 | | "PATCH" |
| 28 | | "TRACE"; |
| 29 | |
| 30 | export interface OperationProps { |
| 31 | /** |
| 32 | * Zone the operation is registered on. |
| 33 | * |
| 34 | * Immutable — moving an operation between zones triggers a replacement. |
| 35 | */ |
| 36 | zoneId: string; |
| 37 | /** |
| 38 | * The HTTP method used to access the endpoint. |
| 39 | * |
| 40 | * Immutable — an operation is the `(method, host, endpoint)` tuple, so |
| 41 | * changing the method triggers a replacement. |
| 42 | */ |
| 43 | method: OperationMethod; |
| 44 | /** |
| 45 | * RFC3986-compliant host the endpoint lives on (e.g. `api.example.com`). |
| 46 | * Must belong to the zone. |
| 47 | * |
| 48 | * Immutable — changing the host triggers a replacement. |
| 49 | */ |
| 50 | host: string; |
| 51 | /** |
| 52 | * The endpoint path, which may contain path-parameter templates in curly |
| 53 | * braces (e.g. `/api/v1/users/{id}`). Cloudflare normalizes variable |
| 54 | * names left-to-right to `{var1}`, `{var2}`, … on insertion. |
| 55 | * |
| 56 | * Immutable — changing the (normalized) endpoint triggers a replacement. |
| 57 | */ |
| 58 | endpoint: string; |
| 59 | } |
| 60 | |
| 61 | export interface OperationAttributes { |
| 62 | /** Cloudflare-assigned UUID of the operation. */ |
| 63 | operationId: string; |
| 64 | /** Zone the operation is registered on. */ |
| 65 | zoneId: string; |
| 66 | /** The HTTP method used to access the endpoint. */ |
| 67 | method: OperationMethod; |
| 68 | /** RFC3986-compliant host the endpoint lives on. */ |
| 69 | host: string; |
| 70 | /** |
| 71 | * The endpoint path as stored by Cloudflare — variable names are |
| 72 | * normalized left-to-right to `{var1}`, `{var2}`, … |
| 73 | */ |
| 74 | endpoint: string; |
| 75 | /** ISO8601 timestamp of the last update. */ |
| 76 | lastUpdated: string; |
| 77 | } |
| 78 | |
| 79 | export type Operation = Resource<TypeId, OperationProps, OperationAttributes, never, Providers>; |
| 80 | |
| 81 | /** |
| 82 | * A Cloudflare API Shield operation — a registered API endpoint on a zone, |
| 83 | * identified by the `(method, host, endpoint)` tuple. Registered operations |
| 84 | * are the unit other API Shield features (schema validation, rate limiting |
| 85 | * recommendations, API Discovery) attach to. |
| 86 | * |
| 87 | * An operation is pure identity: there is no update API, so changing any |
| 88 | * property triggers a replacement. Cloudflare upserts by identity — creating |
| 89 | * an already-registered tuple returns the existing operation — which makes |
| 90 | * reconciliation race-free. |
| 91 | * |
| 92 | * Endpoint paths may contain `{placeholder}` templates; Cloudflare |
| 93 | * normalizes the variable names left-to-right to `{var1}`, `{var2}`, … and |
| 94 | * the normalized form is what is stored and diffed. |
| 95 | * ### Registering an Operation |
| 96 | * **Example:** Register a GET endpoint |
| 97 | * ```typescript |
| 98 | * const op = yield* Cloudflare.ApiShield.Operation("GetUser", { |
| 99 | * zoneId: zone.zoneId, |
| 100 | * method: "GET", |
| 101 | * host: "api.example.com", |
| 102 | * endpoint: "/api/v1/users/{id}", |
| 103 | * }); |
| 104 | * // op.endpoint === "/api/v1/users/{var1}" |
| 105 | * ``` |
| 106 | * |
| 107 | * **Example:** Register a POST endpoint |
| 108 | * ```typescript |
| 109 | * yield* Cloudflare.ApiShield.Operation("CreateUser", { |
| 110 | * zoneId: zone.zoneId, |
| 111 | * method: "POST", |
| 112 | * host: "api.example.com", |
| 113 | * endpoint: "/api/v1/users", |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * @see https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/ |
| 118 | * |
| 119 | * @resource |
| 120 | * @product API Shield |
| 121 | * @category Application Security |
| 122 | */ |
| 123 | export const Operation = Resource<Operation>(TypeId); |
| 124 | |
| 125 | /** |
| 126 | * Returns true if the given value is an Operation resource. |
| 127 | */ |
| 128 | export const isOperation = (value: unknown): value is Operation => |
| 129 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 130 | |
| 131 | export const OperationProvider = () => |
| 132 | Provider.succeed(Operation, { |
| 133 | // An operation has no mutable aspect — every attribute except the |
| 134 | // last-updated timestamp survives any non-replacing deploy. |
| 135 | stables: ["operationId", "zoneId", "method", "host", "endpoint"], |
| 136 | |
| 137 | list: Effect.fn(function* () { |
| 138 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 139 | // Operations live inside a zone (`/zones/{id}/api_gateway/operations`) |
| 140 | // with no account-wide enumeration API — fan out over every zone and |
| 141 | // exhaustively paginate each zone's operations. |
| 142 | const zones = yield* listAllZones(accountId); |
| 143 | const rows = yield* Effect.forEach( |
| 144 | zones, |
| 145 | (zone) => |
| 146 | apiGateway.listOperations.pages({ zoneId: zone.id }).pipe( |
| 147 | Stream.runCollect, |
| 148 | Effect.map((chunk) => |
| 149 | Array.from(chunk).flatMap((page) => |
| 150 | (page.result ?? []).map((op) => toAttributes(op, zone.id)), |
| 151 | ), |
| 152 | ), |
| 153 | // A freshly-minted scoped token can transiently 403; ride out |
| 154 | // the blip, then skip zones the token genuinely can't read. |
| 155 | Effect.retry({ |
| 156 | while: (e) => e._tag === "Forbidden", |
| 157 | schedule: Schedule.exponential("500 millis"), |
| 158 | times: 5, |
| 159 | }), |
| 160 | Effect.catchTag("Forbidden", () => Effect.succeed([] as OperationAttributes[])), |
| 161 | ), |
| 162 | { concurrency: 10 }, |
| 163 | ); |
| 164 | return rows.flat(); |
| 165 | }), |
| 166 | |
| 167 | diff: Effect.fn(function* ({ olds, news }) { |
| 168 | const o = olds as OperationProps | undefined; |
| 169 | const n = news as OperationProps; |
| 170 | if (o?.endpoint === undefined) return undefined; |
| 171 | // The tuple is the operation's identity — any change replaces. |
| 172 | if (o.method !== n.method || o.host !== n.host) { |
| 173 | return { action: "replace" } as const; |
| 174 | } |
| 175 | // Cloudflare normalizes `{name}` templates to `{varN}`; compare |
| 176 | // normalized forms so `/users/{id}` -> `/users/{userId}` is a no-op. |
| 177 | if (normalizeEndpoint(o.endpoint) !== normalizeEndpoint(n.endpoint)) { |
| 178 | return { action: "replace" } as const; |
| 179 | } |
| 180 | // zoneId is Input<string>; compare only once both are concrete. |
| 181 | if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) { |
| 182 | return { action: "replace" } as const; |
| 183 | } |
| 184 | return undefined; |
| 185 | }), |
| 186 | |
| 187 | read: Effect.fn(function* ({ output, olds }) { |
| 188 | const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined); |
| 189 | if (zoneId === undefined) return undefined; |
| 190 | |
| 191 | // Owned path: refresh by our persisted operation id. |
| 192 | if (output?.operationId) { |
| 193 | const observed = yield* getOperation(zoneId, output.operationId); |
| 194 | if (observed) return toAttributes(observed, zoneId); |
| 195 | } |
| 196 | |
| 197 | // Cold path: an operation with this tuple may already exist on the |
| 198 | // zone (state was lost, or it was registered out-of-band). The tuple |
| 199 | // is pure identity and carries no ownership markers, so report it as |
| 200 | // `Unowned` and let the adopt policy gate the takeover. |
| 201 | const tuple = output ?? (olds as OperationProps | undefined); |
| 202 | if (tuple?.endpoint !== undefined && typeof tuple.host === "string") { |
| 203 | const observed = yield* findByTuple(zoneId, { |
| 204 | method: tuple.method, |
| 205 | host: tuple.host, |
| 206 | endpoint: tuple.endpoint, |
| 207 | }); |
| 208 | if (observed) return Unowned(toAttributes(observed, zoneId)); |
| 209 | } |
| 210 | return undefined; |
| 211 | }), |
| 212 | |
| 213 | reconcile: Effect.fn(function* ({ news, output }) { |
| 214 | // Inputs have been resolved to concrete strings by Plan. |
| 215 | const zoneId = news.zoneId as string; |
| 216 | |
| 217 | // 1. Observe — the operation id cached on `output` is a hint, not a |
| 218 | // guarantee: a missing operation falls through to ensure. |
| 219 | const observed = output?.operationId |
| 220 | ? yield* getOperation(zoneId, output.operationId) |
| 221 | : undefined; |
| 222 | if (observed) return toAttributes(observed, zoneId); |
| 223 | |
| 224 | // 2. Ensure — Cloudflare upserts by identity: registering an existing |
| 225 | // `(method, host, endpoint)` tuple returns the existing operation, |
| 226 | // so there is no AlreadyExists race to tolerate. |
| 227 | const created = yield* apiGateway.createOperation({ |
| 228 | zoneId, |
| 229 | method: news.method, |
| 230 | host: news.host, |
| 231 | endpoint: news.endpoint, |
| 232 | }); |
| 233 | return toAttributes(created, zoneId); |
| 234 | // 3. Sync — nothing to do: an operation is existence-only. |
| 235 | }), |
| 236 | |
| 237 | delete: Effect.fn(function* ({ output }) { |
| 238 | yield* apiGateway |
| 239 | .deleteOperation({ |
| 240 | zoneId: output.zoneId, |
| 241 | operationId: output.operationId, |
| 242 | }) |
| 243 | .pipe(Effect.catchTag("OperationNotFound", () => Effect.void)); |
| 244 | }), |
| 245 | }); |
| 246 | |
| 247 | type ObservedOperation = Pick< |
| 248 | apiGateway.GetOperationResponse, |
| 249 | "operationId" | "method" | "host" | "endpoint" | "lastUpdated" |
| 250 | >; |
| 251 | |
| 252 | /** |
| 253 | * Normalize an endpoint path the way Cloudflare does on insertion: each |
| 254 | * `{placeholder}` is replaced left-to-right with `{var1}`, `{var2}`, … |
| 255 | */ |
| 256 | export const normalizeEndpoint = (endpoint: string): string => { |
| 257 | let n = 0; |
| 258 | return endpoint.replace(/\{[^}]*\}/g, () => { |
| 259 | n += 1; |
| 260 | return `{var${n}}`; |
| 261 | }); |
| 262 | }; |
| 263 | |
| 264 | /** |
| 265 | * Read an operation by id, mapping "gone" (`OperationNotFound`, Cloudflare |
| 266 | * error code 10404) to `undefined`. |
| 267 | */ |
| 268 | const getOperation = (zoneId: string, operationId: string) => |
| 269 | apiGateway.getOperation({ zoneId, operationId }).pipe( |
| 270 | Effect.map((op): ObservedOperation | undefined => op), |
| 271 | Effect.catchTag("OperationNotFound", () => Effect.undefined), |
| 272 | ); |
| 273 | |
| 274 | /** |
| 275 | * Find an operation by its exact `(method, host, endpoint)` tuple. The |
| 276 | * tuple is the operation's identity, so at most one can match. Endpoint |
| 277 | * comparison uses Cloudflare's normalized form. |
| 278 | */ |
| 279 | const findByTuple = (zoneId: string, tuple: { method: string; host: string; endpoint: string }) => |
| 280 | apiGateway.listOperations.items({ zoneId, host: [tuple.host], method: [tuple.method] }).pipe( |
| 281 | Stream.runCollect, |
| 282 | Effect.map((chunk) => |
| 283 | Array.from(chunk).find( |
| 284 | (op): op is ObservedOperation & typeof op => |
| 285 | op.method === tuple.method && |
| 286 | op.host === tuple.host && |
| 287 | op.endpoint === normalizeEndpoint(tuple.endpoint), |
| 288 | ), |
| 289 | ), |
| 290 | ); |
| 291 | |
| 292 | const toAttributes = (op: ObservedOperation, zoneId: string): OperationAttributes => ({ |
| 293 | operationId: op.operationId, |
| 294 | zoneId, |
| 295 | // Distilled widens generated string enums to open unions (`string & {}`). |
| 296 | method: op.method as OperationMethod, |
| 297 | host: op.host, |
| 298 | endpoint: op.endpoint, |
| 299 | lastUpdated: op.lastUpdated, |
| 300 | }); |