The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as pageShield from "@distilled.cloud/cloudflare/page-shield"; |
| 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.PageShield.Policy" as const; |
| 15 | type TypeId = typeof TypeId; |
| 16 | |
| 17 | /** |
| 18 | * Action a Page Shield policy takes when its expression matches: |
| 19 | * `allow` blocks everything not covered by the CSP, `log` only reports |
| 20 | * violations, and `add_reporting_directives` injects report-to / |
| 21 | * report-uri directives. |
| 22 | */ |
| 23 | export type PolicyAction = "allow" | "log" | "add_reporting_directives"; |
| 24 | |
| 25 | export interface PolicyProps { |
| 26 | /** |
| 27 | * Zone the policy belongs to. Stable — changing the zone triggers a |
| 28 | * replacement. |
| 29 | */ |
| 30 | zoneId: string; |
| 31 | /** |
| 32 | * Human readable description of the policy. Page Shield policies have |
| 33 | * no `name` field, so the description doubles as the resource's |
| 34 | * identity for cold-state recovery. If omitted, a deterministic name |
| 35 | * is generated from the app, stage, and logical ID. Mutable. |
| 36 | * @default ${app}-${stage}-${id} |
| 37 | */ |
| 38 | description?: string; |
| 39 | /** |
| 40 | * The action to take when `expression` matches: `allow` (enforce the |
| 41 | * CSP), `log` (report only), or `add_reporting_directives`. Mutable. |
| 42 | */ |
| 43 | action: PolicyAction; |
| 44 | /** |
| 45 | * Whether the policy is enabled. Mutable. |
| 46 | * @default true |
| 47 | */ |
| 48 | enabled?: boolean; |
| 49 | /** |
| 50 | * The expression that must match for the policy to be applied, in |
| 51 | * Cloudflare's Firewall rule expression syntax (e.g. |
| 52 | * `http.host eq "example.com"`). Mutable. |
| 53 | */ |
| 54 | expression: string; |
| 55 | /** |
| 56 | * The Content Security Policy to apply (e.g. `script-src 'self'`). |
| 57 | * Mutable. |
| 58 | */ |
| 59 | value: string; |
| 60 | } |
| 61 | |
| 62 | export interface PolicyAttributes { |
| 63 | /** Auto-assigned identifier of the policy. */ |
| 64 | policyId: string; |
| 65 | /** Zone the policy belongs to. */ |
| 66 | zoneId: string; |
| 67 | /** The action taken when the expression matches. */ |
| 68 | action: PolicyAction; |
| 69 | /** Human readable description of the policy. */ |
| 70 | description: string; |
| 71 | /** Whether the policy is enabled. */ |
| 72 | enabled: boolean; |
| 73 | /** The expression that must match for the policy to be applied. */ |
| 74 | expression: string; |
| 75 | /** The Content Security Policy applied by this policy. */ |
| 76 | value: string; |
| 77 | } |
| 78 | |
| 79 | export type Policy = Resource<TypeId, PolicyProps, PolicyAttributes, never, Providers>; |
| 80 | |
| 81 | /** |
| 82 | * A Page Shield policy — a Content Security Policy rule |
| 83 | * (`/zones/{zone_id}/page_shield/policies`) that is applied when its |
| 84 | * expression matches a request. |
| 85 | * |
| 86 | * Policies let you enforce (or log violations of) a CSP at the edge, |
| 87 | * positively blocking resources Page Shield hasn't approved. All fields |
| 88 | * are mutable in place; only the zone forces a replacement. |
| 89 | * |
| 90 | * **Entitlement-gated**: CSP policies are an Enterprise add-on. On |
| 91 | * non-entitled zones, creation fails with the typed `PolicyQuotaExceeded` |
| 92 | * error ("exceeded the maximum number of rules in the phase |
| 93 | * http_response_page_shield: 1 out of 0"). Page Shield itself should be |
| 94 | * enabled on the zone first — see `Cloudflare.PageShield.Settings`. |
| 95 | * ### Creating a Policy |
| 96 | * **Example:** Log-only CSP policy |
| 97 | * ```typescript |
| 98 | * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" }); |
| 99 | * |
| 100 | * yield* Cloudflare.PageShield.Settings("PageShield", { |
| 101 | * zoneId: zone.zoneId, |
| 102 | * }); |
| 103 | * |
| 104 | * yield* Cloudflare.PageShield.Policy("LogScripts", { |
| 105 | * zoneId: zone.zoneId, |
| 106 | * action: "log", |
| 107 | * expression: 'http.host eq "example.com"', |
| 108 | * value: "script-src 'self'", |
| 109 | * }); |
| 110 | * ``` |
| 111 | * |
| 112 | * **Example:** Enforcing CSP policy with a description |
| 113 | * ```typescript |
| 114 | * yield* Cloudflare.PageShield.Policy("EnforceScripts", { |
| 115 | * zoneId: zone.zoneId, |
| 116 | * description: "block third-party scripts on checkout", |
| 117 | * action: "allow", |
| 118 | * expression: 'starts_with(http.request.uri.path, "/checkout")', |
| 119 | * value: "script-src 'self' https://js.stripe.com", |
| 120 | * }); |
| 121 | * ``` |
| 122 | * |
| 123 | * @see https://developers.cloudflare.com/page-shield/policies/ |
| 124 | * |
| 125 | * @resource |
| 126 | * @product Page Shield |
| 127 | * @category Application Security |
| 128 | */ |
| 129 | export const Policy = Resource<Policy>(TypeId); |
| 130 | |
| 131 | /** |
| 132 | * Returns true if the given value is a Policy resource. |
| 133 | */ |
| 134 | export const isPolicy = (value: unknown): value is Policy => |
| 135 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 136 | |
| 137 | export const PolicyProvider = () => |
| 138 | Provider.succeed(Policy, { |
| 139 | stables: ["policyId", "zoneId"], |
| 140 | |
| 141 | diff: Effect.fn(function* ({ news, output }) { |
| 142 | if (!isResolved(news)) return undefined; |
| 143 | if (output !== undefined && output.zoneId !== news.zoneId) { |
| 144 | return { action: "replace" } as const; |
| 145 | } |
| 146 | return undefined; |
| 147 | }), |
| 148 | |
| 149 | read: Effect.fn(function* ({ id, output, olds }) { |
| 150 | const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined); |
| 151 | if (!zoneId) return undefined; |
| 152 | |
| 153 | if (output?.policyId) { |
| 154 | const observed = yield* getPolicy(zoneId, output.policyId); |
| 155 | return observed ? toAttributes(zoneId, observed) : undefined; |
| 156 | } |
| 157 | // Cold read — recover from lost state by matching the deterministic |
| 158 | // description (policies have no name and carry no tags, so the |
| 159 | // description is the best identity we have). A match is branded |
| 160 | // `Unowned` so the engine gates takeover behind `--adopt`. |
| 161 | const description = yield* createDescription(id, olds?.description); |
| 162 | const list = yield* pageShield.listPolicies({ zoneId }); |
| 163 | const match = list.result.find((p) => p.description === description); |
| 164 | return match ? Unowned(toAttributes(zoneId, match)) : undefined; |
| 165 | }), |
| 166 | |
| 167 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 168 | // Inputs have been resolved to concrete strings by Plan. |
| 169 | const zoneId = news.zoneId as string; |
| 170 | const description = yield* createDescription(id, news.description); |
| 171 | |
| 172 | // 1. Observe — the policyId cached on `output` is a hint, not a |
| 173 | // guarantee: a PolicyNotFound falls through to "missing". |
| 174 | const observed = output?.policyId ? yield* getPolicy(zoneId, output.policyId) : undefined; |
| 175 | |
| 176 | const desired = { |
| 177 | action: news.action, |
| 178 | description, |
| 179 | enabled: news.enabled ?? true, |
| 180 | expression: news.expression, |
| 181 | value: news.value, |
| 182 | }; |
| 183 | |
| 184 | // 2. Ensure — greenfield (or out-of-band delete): create with the |
| 185 | // full desired body. Descriptions are not unique on Cloudflare's |
| 186 | // side, so there is no AlreadyExists race to tolerate. |
| 187 | if (!observed) { |
| 188 | const created = yield* pageShield.createPolicy({ zoneId, ...desired }); |
| 189 | return toAttributes(zoneId, created); |
| 190 | } |
| 191 | |
| 192 | // 3. Sync — diff observed cloud state against desired; the update |
| 193 | // API is a PUT, so send the full body, but skip the call |
| 194 | // entirely on a no-op. |
| 195 | const dirty = |
| 196 | observed.action !== desired.action || |
| 197 | observed.description !== desired.description || |
| 198 | observed.enabled !== desired.enabled || |
| 199 | observed.expression !== desired.expression || |
| 200 | observed.value !== desired.value; |
| 201 | if (!dirty) { |
| 202 | return toAttributes(zoneId, observed); |
| 203 | } |
| 204 | const updated = yield* pageShield.updatePolicy({ |
| 205 | zoneId, |
| 206 | policyId: observed.id, |
| 207 | ...desired, |
| 208 | }); |
| 209 | return toAttributes(zoneId, updated); |
| 210 | }), |
| 211 | |
| 212 | list: Effect.fn(function* () { |
| 213 | // Page Shield policies are zone-scoped |
| 214 | // (`/zones/{zone_id}/page_shield/policies`). Fan out across every |
| 215 | // zone in the account, exhaustively paginate each, and hydrate into |
| 216 | // the same Attributes shape `read` produces. Zones without Page |
| 217 | // Shield entitlement reject with the typed `Forbidden` tag — skip |
| 218 | // them rather than failing the whole enumeration. |
| 219 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 220 | const zones = yield* listAllZones(accountId); |
| 221 | const rows = yield* Effect.forEach( |
| 222 | zones, |
| 223 | (zone) => |
| 224 | pageShield.listPolicies.pages({ zoneId: zone.id }).pipe( |
| 225 | Stream.runCollect, |
| 226 | Effect.map((chunk) => |
| 227 | Array.from(chunk).flatMap((page) => |
| 228 | (page.result ?? []).map((policy) => toAttributes(zone.id, policy)), |
| 229 | ), |
| 230 | ), |
| 231 | Effect.catchTag("Forbidden", () => Effect.succeed([])), |
| 232 | ), |
| 233 | { concurrency: 10 }, |
| 234 | ); |
| 235 | return rows.flat(); |
| 236 | }), |
| 237 | |
| 238 | delete: Effect.fn(function* ({ output }) { |
| 239 | // Cloudflare returns 204 even for missing policies, but ride out a |
| 240 | // racing delete via the typed tag anyway. |
| 241 | yield* pageShield |
| 242 | .deletePolicy({ zoneId: output.zoneId, policyId: output.policyId }) |
| 243 | .pipe(Effect.catchTag("PolicyNotFound", () => Effect.void)); |
| 244 | }), |
| 245 | }); |
| 246 | |
| 247 | /** |
| 248 | * Read a policy by id, mapping "gone" (`PolicyNotFound`, HTTP 404) to |
| 249 | * `undefined`. |
| 250 | */ |
| 251 | const getPolicy = (zoneId: string, policyId: string) => |
| 252 | pageShield |
| 253 | .getPolicy({ zoneId, policyId }) |
| 254 | .pipe(Effect.catchTag("PolicyNotFound", () => Effect.undefined)); |
| 255 | |
| 256 | const createDescription = (id: string, description: string | undefined) => |
| 257 | Effect.gen(function* () { |
| 258 | return description ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 259 | }); |
| 260 | |
| 261 | type ObservedPolicy = |
| 262 | | pageShield.GetPolicyResponse |
| 263 | | pageShield.CreatePolicyResponse |
| 264 | | pageShield.UpdatePolicyResponse |
| 265 | | pageShield.ListPoliciesResponse["result"][number]; |
| 266 | |
| 267 | const toAttributes = (zoneId: string, policy: ObservedPolicy): PolicyAttributes => ({ |
| 268 | policyId: policy.id, |
| 269 | zoneId, |
| 270 | // Distilled widens generated string enums to open unions (`string & {}`). |
| 271 | action: policy.action as PolicyAction, |
| 272 | description: policy.description, |
| 273 | enabled: policy.enabled, |
| 274 | expression: policy.expression, |
| 275 | value: policy.value, |
| 276 | }); |