The best way to control Claude Code, Codex and more from any computer or phone

main
ts 429 lines 15.2 KB
Raw
1 import * as firewall from "@distilled.cloud/cloudflare/firewall";
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 Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAllZones } from "../Zone/lookup.ts";
11
12 const FirewallAccessRuleTypeId = "Cloudflare.Firewall.AccessRule" as const;
13 type FirewallAccessRuleTypeId = typeof FirewallAccessRuleTypeId;
14
15 /**
16 * The action an IP Access rule applies to a matched request.
17 *
18 * Note: `block` for `country`/`asn` targets requires an Enterprise plan;
19 * `challenge` and `managed_challenge` work on all plans.
20 */
21 export type AccessRuleMode =
22 | "block"
23 | "challenge"
24 | "whitelist"
25 | "js_challenge"
26 | "managed_challenge";
27
28 /**
29 * What a rule's configuration matches on: a single IPv4 (`ip`), a single
30 * IPv6 (`ip6`), a CIDR range (`ip_range`), an AS number (`asn`), or a
31 * two-letter ISO-3166-1 alpha-2 country code (`country`).
32 */
33 export type AccessRuleTarget = "ip" | "ip6" | "ip_range" | "asn" | "country";
34
35 /**
36 * The match configuration of an IP Access rule. Immutable — the Cloudflare
37 * API only allows `mode`/`notes` to be patched, so changing the
38 * configuration replaces the rule.
39 */
40 export interface AccessRuleConfiguration {
41 /**
42 * What the rule matches on.
43 */
44 target: AccessRuleTarget;
45 /**
46 * The value to match — e.g. `198.51.100.4` (`ip`), `2001:db8::/64`
47 * (`ip_range`), `AS13335` (`asn`), or `US` (`country`).
48 */
49 value: string;
50 }
51
52 export interface AccessRuleProps {
53 /**
54 * Zone the rule applies to. When omitted, the rule is created at the
55 * account level and applies to every zone in the account.
56 *
57 * Stable — moving a rule between scopes triggers a replacement.
58 */
59 zoneId?: string;
60 /**
61 * The rule's match configuration (target + value).
62 *
63 * Immutable — the API has no way to change a rule's configuration
64 * (only `mode`/`notes` are patchable), so changing it triggers a
65 * replacement.
66 */
67 configuration: AccessRuleConfiguration;
68 /**
69 * The action to apply to a matched request. Mutable — patched in place.
70 */
71 mode: AccessRuleMode;
72 /**
73 * An informative summary of the rule, typically used as a reminder or
74 * explanation. Mutable — patched in place.
75 */
76 notes?: string;
77 }
78
79 export interface AccessRuleAttributes {
80 /** Cloudflare-assigned identifier of the IP Access rule. */
81 ruleId: string;
82 /** Zone the rule belongs to, or `undefined` for account-scoped rules. */
83 zoneId: string | undefined;
84 /** Account the rule was created under. */
85 accountId: string;
86 /** The rule's match configuration. */
87 configuration: AccessRuleConfiguration;
88 /** The action applied to matched requests. */
89 mode: AccessRuleMode;
90 /** The actions available for this rule. */
91 allowedModes: AccessRuleMode[];
92 /** The rule's informative summary, if set. */
93 notes: string | undefined;
94 /** ISO8601 creation timestamp. */
95 createdOn: string | undefined;
96 /** ISO8601 last-modified timestamp. */
97 modifiedOn: string | undefined;
98 }
99
100 export type AccessRule = Resource<
101 FirewallAccessRuleTypeId,
102 AccessRuleProps,
103 AccessRuleAttributes,
104 never,
105 Providers
106 >;
107
108 /**
109 * A Cloudflare IP Access rule — block, challenge, or whitelist requests by
110 * IP, CIDR range, ASN, or country, either on a single zone or across the
111 * whole account.
112 *
113 * A rule's identity is its `configuration` (target + value) within a scope:
114 * Cloudflare rejects a second rule for the same configuration with a
115 * duplicate error, and the configuration cannot be changed after creation —
116 * only `mode` and `notes` are mutable. Changing `configuration` or moving
117 * the rule between zone and account scope triggers a replacement.
118 *
119 * Safety: IP Access rules carry no ownership markers. When there is no
120 * prior state, `read` scans the scope for an existing rule with the same
121 * configuration and reports it as `Unowned`, so the engine refuses to take
122 * it over unless `--adopt` (or `adopt(true)`) is set.
123 * ### Blocking an IP
124 * **Example:** Block a single IPv4 address on a zone
125 * ```typescript
126 * yield* Cloudflare.Firewall.AccessRule("BlockBadActor", {
127 * zoneId: zone.zoneId,
128 * configuration: { target: "ip", value: "198.51.100.4" },
129 * mode: "block",
130 * notes: "repeated credential stuffing",
131 * });
132 * ```
133 *
134 * **Example:** Block a CIDR range account-wide
135 * ```typescript
136 * // No zoneId — the rule applies to every zone in the account.
137 * yield* Cloudflare.Firewall.AccessRule("BlockScannerRange", {
138 * configuration: { target: "ip_range", value: "203.0.113.0/24" },
139 * mode: "block",
140 * });
141 * ```
142 *
143 * ### Challenging traffic
144 * **Example:** Managed challenge for a country
145 * ```typescript
146 * // `block` for country targets is Enterprise-only; challenges work on
147 * // all plans.
148 * yield* Cloudflare.Firewall.AccessRule("ChallengeCountry", {
149 * zoneId: zone.zoneId,
150 * configuration: { target: "country", value: "KP" },
151 * mode: "managed_challenge",
152 * });
153 * ```
154 *
155 * ### Whitelisting
156 * **Example:** Always allow an office IP
157 * ```typescript
158 * yield* Cloudflare.Firewall.AccessRule("AllowOffice", {
159 * zoneId: zone.zoneId,
160 * configuration: { target: "ip", value: "192.0.2.10" },
161 * mode: "whitelist",
162 * notes: "office egress IP",
163 * });
164 * ```
165 *
166 * @see https://developers.cloudflare.com/waf/tools/ip-access-rules/
167 *
168 * @resource
169 * @product Firewall
170 * @category Application Security
171 */
172 export const AccessRule = Resource<AccessRule>(FirewallAccessRuleTypeId);
173
174 /**
175 * Returns true if the given value is a AccessRule resource.
176 */
177 export const isAccessRule = (value: unknown): value is AccessRule =>
178 Predicate.hasProperty(value, "Type") && value.Type === FirewallAccessRuleTypeId;
179
180 export const AccessRuleProvider = () =>
181 Provider.succeed(AccessRule, {
182 stables: ["ruleId", "zoneId", "accountId", "allowedModes", "createdOn"],
183
184 diff: Effect.fn(function* ({ olds = {}, news }) {
185 const o = olds as AccessRuleProps;
186 const n = news as AccessRuleProps;
187 // No prior props to compare against — let the engine decide.
188 if (o.configuration === undefined) return undefined;
189 // The API can only patch mode/notes — configuration is immutable.
190 if (
191 o.configuration.target !== n.configuration.target ||
192 o.configuration.value !== n.configuration.value
193 ) {
194 return { action: "replace" } as const;
195 }
196 // Scope change (zone <-> account, or a different zone) replaces.
197 if ((o.zoneId === undefined) !== (n.zoneId === undefined)) {
198 return { action: "replace" } as const;
199 }
200 // zoneId is Input<string>; compare only once both are concrete.
201 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
202 return { action: "replace" } as const;
203 }
204 return undefined;
205 }),
206
207 read: Effect.fn(function* ({ output, olds }) {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
210 const acct = output?.accountId ?? accountId;
211
212 // Owned path: refresh by our persisted rule id.
213 if (output?.ruleId) {
214 const observed = yield* getRule(zoneId, acct, output.ruleId);
215 if (observed) return toAttributes(observed, zoneId, acct);
216 }
217
218 // Adoption path: a rule with this configuration may already exist in
219 // the scope. Access rules carry no ownership markers, so we cannot
220 // prove we created it — brand it `Unowned` so the engine refuses to
221 // take over unless `adopt` is set.
222 const configuration = output?.configuration ?? olds?.configuration;
223 if (configuration) {
224 const observed = yield* findByConfiguration(zoneId, acct, configuration);
225 if (observed) return Unowned(toAttributes(observed, zoneId, acct));
226 }
227 return undefined;
228 }),
229
230 reconcile: Effect.fn(function* ({ news, output }) {
231 const { accountId } = yield* yield* CloudflareEnvironment;
232 // Inputs have been resolved to concrete strings by Plan.
233 const zoneId = news.zoneId as string | undefined;
234
235 // 1. Observe — the rule id cached on `output` is a hint, not a
236 // guarantee: a missing rule falls through to the configuration
237 // scan and then to create.
238 let observed = output?.ruleId ? yield* getRule(zoneId, accountId, output.ruleId) : undefined;
239
240 // 2. Fall back to scanning the scope for a configuration match.
241 // Ownership has already been verified upstream — `read` reports
242 // existing rules as `Unowned` and the engine gates takeover
243 // behind the adopt policy before reconcile ever runs.
244 if (!observed) {
245 observed = yield* findByConfiguration(zoneId, accountId, news.configuration);
246 }
247
248 // 3. Ensure — create when missing. A concurrent create surfaces as
249 // `DuplicateAccessRule` (Cloudflare code 10009): converge by
250 // re-scanning for the rule that won the race.
251 if (!observed) {
252 observed = yield* createRule(zoneId, accountId, news).pipe(
253 Effect.catchTag("DuplicateAccessRule", (error) =>
254 findByConfiguration(zoneId, accountId, news.configuration).pipe(
255 Effect.flatMap((existing) =>
256 existing ? Effect.succeed(existing) : Effect.fail(error),
257 ),
258 ),
259 ),
260 );
261 }
262
263 // 4. Sync — diff observed mode/notes against desired; skip the
264 // patch call entirely on a no-op.
265 const dirty =
266 observed.mode !== news.mode ||
267 (news.notes !== undefined && (observed.notes ?? "") !== news.notes);
268 if (dirty) {
269 observed = yield* patchRule(zoneId, accountId, observed.id, news);
270 }
271
272 return toAttributes(observed, zoneId, accountId);
273 }),
274
275 // IP Access rules are hybrid-scoped: account-level rules (zoneId
276 // undefined) plus per-zone rules. Enumerate both — the account
277 // collection, then fan out across every zone — and tag each item with
278 // its scope so the result matches the exact `read` Attributes shape.
279 list: Effect.fn(function* () {
280 const { accountId } = yield* yield* CloudflareEnvironment;
281
282 const accountRules = yield* firewall.listAccessRulesForAccount.pages({ accountId }).pipe(
283 Stream.runCollect,
284 Effect.map((chunk) =>
285 Array.from(chunk).flatMap((page) =>
286 (page.result ?? []).map((rule) => toAttributes(rule, undefined, accountId)),
287 ),
288 ),
289 // No permission to read account-level rules — skip them.
290 Effect.catchTag("Forbidden", () => Effect.succeed([])),
291 );
292
293 const zones = yield* listAllZones(accountId);
294 const zoneRuleGroups = yield* Effect.forEach(
295 zones,
296 (zone) =>
297 firewall.listAccessRulesForZone.pages({ zoneId: zone.id }).pipe(
298 Stream.runCollect,
299 Effect.map((chunk) =>
300 Array.from(chunk).flatMap((page) =>
301 (page.result ?? []).map((rule) => toAttributes(rule, zone.id, accountId)),
302 ),
303 ),
304 // Plan-gated / partial zones reject the route; skip them.
305 Effect.catchTag("Forbidden", () => Effect.succeed([])),
306 ),
307 { concurrency: 10 },
308 );
309
310 return [...accountRules, ...zoneRuleGroups.flat()];
311 }),
312
313 delete: Effect.fn(function* ({ output }) {
314 // Cloudflare answers DELETE for an already-gone rule with HTTP 200
315 // and `result: null` (not an error envelope), which the typed
316 // response decode rejects — observe first and treat missing as done.
317 const observed = yield* getRule(output.zoneId, output.accountId, output.ruleId);
318 if (!observed) return;
319 yield* deleteRule(output.zoneId, output.accountId, output.ruleId).pipe(
320 Effect.catchTag("AccessRuleNotFound", () => Effect.void),
321 );
322 }),
323 });
324
325 // ---------------------------------------------------------------------------
326 // Scoped API helpers (zone-level when zoneId is set, account-level otherwise)
327 // ---------------------------------------------------------------------------
328
329 type ObservedRule = firewall.GetAccessRuleResponse;
330
331 /**
332 * Read a rule by id, mapping "gone" (`AccessRuleNotFound`, Cloudflare error
333 * code 10001 `firewallaccessrules.api.not_found`) to `undefined`.
334 */
335 const getRule = (zoneId: string | undefined, accountId: string, ruleId: string) =>
336 (zoneId !== undefined
337 ? firewall.getAccessRuleForZone({ zoneId, ruleId })
338 : firewall.getAccessRuleForAccount({ accountId, ruleId })
339 ).pipe(
340 Effect.map((rule): ObservedRule | undefined => rule),
341 Effect.catchTag("AccessRuleNotFound", () => Effect.undefined),
342 );
343
344 /**
345 * Find a rule by exact configuration (target + value) within the scope.
346 * The configuration is a rule's identity — Cloudflare rejects duplicates —
347 * so at most one rule can match.
348 */
349 const findByConfiguration = (
350 zoneId: string | undefined,
351 accountId: string,
352 configuration: AccessRuleConfiguration,
353 ) =>
354 (zoneId !== undefined
355 ? firewall.listAccessRulesForZone.items({ zoneId })
356 : firewall.listAccessRulesForAccount.items({ accountId })
357 ).pipe(
358 Stream.runCollect,
359 Effect.map((chunk) =>
360 Array.from(chunk).find(
361 (rule): rule is ObservedRule =>
362 rule.configuration.target === configuration.target &&
363 rule.configuration.value === configuration.value,
364 ),
365 ),
366 );
367
368 const createRule = (zoneId: string | undefined, accountId: string, news: AccessRuleProps) =>
369 zoneId !== undefined
370 ? firewall.createAccessRuleForZone({
371 zoneId,
372 configuration: news.configuration,
373 mode: news.mode,
374 notes: news.notes,
375 })
376 : firewall.createAccessRuleForAccount({
377 accountId,
378 configuration: news.configuration,
379 mode: news.mode,
380 notes: news.notes,
381 });
382
383 const patchRule = (
384 zoneId: string | undefined,
385 accountId: string,
386 ruleId: string,
387 news: AccessRuleProps,
388 ) =>
389 zoneId !== undefined
390 ? firewall.patchAccessRuleForZone({
391 zoneId,
392 ruleId,
393 configuration: news.configuration,
394 mode: news.mode,
395 notes: news.notes,
396 })
397 : firewall.patchAccessRuleForAccount({
398 accountId,
399 ruleId,
400 configuration: news.configuration,
401 mode: news.mode,
402 notes: news.notes,
403 });
404
405 const deleteRule = (zoneId: string | undefined, accountId: string, ruleId: string) =>
406 zoneId !== undefined
407 ? firewall.deleteAccessRuleForZone({ zoneId, ruleId })
408 : firewall.deleteAccessRuleForAccount({ accountId, ruleId });
409
410 const toAttributes = (
411 rule: ObservedRule,
412 zoneId: string | undefined,
413 accountId: string,
414 ): AccessRuleAttributes => ({
415 ruleId: rule.id,
416 zoneId,
417 accountId,
418 configuration: {
419 // Distilled types each union variant's target/value as optional —
420 // Cloudflare always echoes both for a persisted rule.
421 target: (rule.configuration.target ?? "ip") as AccessRuleTarget,
422 value: rule.configuration.value ?? "",
423 },
424 mode: rule.mode as AccessRuleMode,
425 allowedModes: [...rule.allowedModes] as AccessRuleMode[],
426 notes: rule.notes ?? undefined,
427 createdOn: rule.createdOn ?? undefined,
428 modifiedOn: rule.modifiedOn ?? undefined,
429 });