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

main
ts 574 lines 18.7 KB
Raw
1 import * as rules from "@distilled.cloud/cloudflare/rules";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Predicate from "effect/Predicate";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
13 import type { Providers } from "../Providers.ts";
14
15 const TypeId = "Cloudflare.Rules.List" as const;
16 type TypeId = typeof TypeId;
17
18 /**
19 * The type of a list. Each kind supports specific list items: IP addresses,
20 * ASNs, hostnames, or URL redirects. Cannot be changed after creation.
21 */
22 export type ListKind = "ip" | "asn" | "hostname" | "redirect";
23
24 /**
25 * An item in an `ip` list — an IPv4/IPv6 address or CIDR range
26 * (IPv4 prefixes /8–/32, IPv6 prefixes /4–/64).
27 */
28 export type ListIpItem = {
29 /**
30 * An IPv4 address, IPv4 CIDR, IPv6 address, or IPv6 CIDR.
31 */
32 ip: string;
33 /**
34 * An informative summary of the item.
35 */
36 comment?: string;
37 };
38
39 /**
40 * An item in an `asn` list — an autonomous system number.
41 */
42 export type ListAsnItem = {
43 /**
44 * A non-negative 32 bit integer.
45 */
46 asn: number;
47 /**
48 * An informative summary of the item.
49 */
50 comment?: string;
51 };
52
53 /**
54 * An item in a `hostname` list.
55 */
56 export type ListHostnameItem = {
57 /**
58 * Valid characters for hostnames are ASCII(7) letters from a to z, the
59 * digits from 0 to 9, wildcards (*), and the hyphen (-).
60 */
61 hostname: {
62 /**
63 * The hostname to match, e.g. `example.com` or `*.example.com`.
64 */
65 urlHostname: string;
66 /**
67 * Only applies to wildcard hostnames (e.g., *.example.com). When `true`,
68 * only subdomains are blocked. When `false`, both the root domain and
69 * subdomains are blocked.
70 * @default false
71 */
72 excludeExactHostname?: boolean;
73 };
74 /**
75 * An informative summary of the item.
76 */
77 comment?: string;
78 };
79
80 /**
81 * An item in a `redirect` list — a source/target URL pair used by Bulk
82 * Redirect rules.
83 */
84 export type ListRedirectItem = {
85 /**
86 * The definition of the redirect.
87 */
88 redirect: {
89 /**
90 * The source URL to match, e.g. `example.com/old-path`.
91 */
92 sourceUrl: string;
93 /**
94 * The URL to redirect to.
95 */
96 targetUrl: string;
97 /**
98 * Whether the redirect also matches subdomains of the source URL.
99 * @default false
100 */
101 includeSubdomains?: boolean;
102 /**
103 * Whether the redirect target URL keeps the path suffix of the request.
104 * @default false
105 */
106 preservePathSuffix?: boolean;
107 /**
108 * Whether the redirect target URL keeps the query string of the request.
109 * @default false
110 */
111 preserveQueryString?: boolean;
112 /**
113 * The HTTP status code used for the redirect.
114 * @default 301
115 */
116 statusCode?: 301 | 302 | 307 | 308;
117 /**
118 * Whether the redirect also matches subpaths of the source URL.
119 * @default false
120 */
121 subpathMatching?: boolean;
122 };
123 /**
124 * An informative summary of the item.
125 */
126 comment?: string;
127 };
128
129 /**
130 * An item in an account list. The shape must match the list `kind`:
131 * `{ ip }` for `ip` lists, `{ asn }` for `asn` lists, `{ hostname }` for
132 * `hostname` lists, and `{ redirect }` for `redirect` lists.
133 */
134 export type ListItem = ListIpItem | ListAsnItem | ListHostnameItem | ListRedirectItem;
135
136 export type ListProps = {
137 /**
138 * An informative name for the list, used in filter and rule expressions
139 * (e.g. `ip.src in $my_list`). Must contain only letters, numbers, and
140 * underscores (max 50 characters). If omitted, a unique name is generated
141 * from the app, stage, and logical ID. Cannot be changed after creation —
142 * updating this property triggers a replacement.
143 * @default ${app}_${stage}_${id}
144 */
145 name?: string;
146 /**
147 * The type of the list. Each kind supports specific list items
148 * (IP addresses, ASNs, hostnames, or redirects). Cannot be changed after
149 * creation — updating this property triggers a replacement.
150 */
151 kind: ListKind;
152 /**
153 * An informative summary of the list.
154 */
155 description?: string;
156 /**
157 * The full contents of the list. Items are replaced idempotently via the
158 * bulk items operation: the provider diffs the observed items against this
159 * desired set and, on any delta, replaces the entire list contents and
160 * polls the asynchronous bulk operation to completion.
161 * @default []
162 */
163 items?: ListItem[];
164 };
165
166 export type ListAttributes = {
167 /**
168 * The unique ID of the list.
169 */
170 listId: string;
171 /**
172 * The Cloudflare account the list belongs to.
173 */
174 accountId: string;
175 /**
176 * The name of the list, usable in rule expressions as `$name`.
177 */
178 name: string;
179 /**
180 * The type of the list.
181 */
182 kind: ListKind;
183 /**
184 * An informative summary of the list.
185 */
186 description: string | undefined;
187 /**
188 * The number of items in the list.
189 */
190 numItems: number;
191 /**
192 * The number of filters referencing the list.
193 */
194 numReferencingFilters: number;
195 /**
196 * The RFC 3339 timestamp of when the list was created.
197 */
198 createdOn: string;
199 /**
200 * The RFC 3339 timestamp of when the list was last modified.
201 */
202 modifiedOn: string;
203 };
204
205 export type List = Resource<TypeId, ListProps, ListAttributes, never, Providers>;
206
207 /**
208 * A Cloudflare account-level List (Lists API) — a named collection of IP
209 * addresses, ASNs, hostnames, or URL redirects referenced from ruleset
210 * expressions (`ip.src in $my_list`) and Bulk Redirect rules.
211 *
212 * `name` and `kind` are immutable and changing either triggers a
213 * replacement. The list's items are managed as part of the resource: on any
214 * change the full contents are replaced via the asynchronous bulk items
215 * operation, which the provider polls to completion.
216 * ### Creating a List
217 * **Example:** IP list with items
218 * ```typescript
219 * const blocklist = yield* Cloudflare.Rules.List("blocklist", {
220 * kind: "ip",
221 * description: "Known bad actors",
222 * items: [
223 * { ip: "203.0.113.7", comment: "scanner" },
224 * { ip: "198.51.100.0/24" },
225 * ],
226 * });
227 * ```
228 *
229 * **Example:** ASN list with an explicit name
230 * ```typescript
231 * const asns = yield* Cloudflare.Rules.List("bad-asns", {
232 * name: "bad_asns",
233 * kind: "asn",
234 * items: [{ asn: 64496 }, { asn: 64511, comment: "spam network" }],
235 * });
236 * ```
237 *
238 * ### Bulk Redirects
239 * A zone's `http_request_dynamic_redirect` phase caps the number of rules
240 * (10 on most plans). Bulk Redirects scale past that: put every mapping in a
241 * `redirect` list and reference it from a single rule in the account's
242 * `http_request_redirect` phase.
243 *
244 * **Example:** Redirect retired paths with one rule
245 * ```typescript
246 * const retired = yield* Cloudflare.Rules.List("RetiredSlugs", {
247 * kind: "redirect",
248 * items: [
249 * {
250 * redirect: {
251 * sourceUrl: "example.com/services/old-slug",
252 * targetUrl: "https://example.com/services/new-slug",
253 * statusCode: 301,
254 * preserveQueryString: true,
255 * },
256 * },
257 * ],
258 * });
259 *
260 * yield* Cloudflare.Ruleset.AccountEntrypoint("BulkRedirects", {
261 * phase: "http_request_redirect",
262 * rules: [
263 * {
264 * ref: "retired_slugs",
265 * expression: Output.interpolate`http.request.full_uri in $${retired.name}`,
266 * action: "redirect",
267 * actionParameters: {
268 * fromList: { name: retired.name, key: "http.request.full_uri" },
269 * },
270 * },
271 * ],
272 * });
273 * ```
274 *
275 * ### Referencing a List from rules
276 * **Example:** Use the list name in a Ruleset expression
277 * ```typescript
278 * const list = yield* Cloudflare.Rules.List("blocklist", { kind: "ip" });
279 *
280 * // The stable `name` attribute interpolates into rule expressions:
281 * // `ip.src in $<name>`
282 * const expression = list.name.apply((name) => `ip.src in $${name}`);
283 * ```
284 *
285 * @see https://developers.cloudflare.com/waf/tools/lists/
286 *
287 * @resource
288 * @product Rules
289 * @category Rules & Configuration
290 */
291 export const List = Resource<List>(TypeId);
292
293 /**
294 * Returns true if the given value is a List resource.
295 */
296 export const isList = (value: unknown): value is List =>
297 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
298
299 /**
300 * The asynchronous bulk items operation finished in a non-`completed`
301 * state (or never completed within the polling budget).
302 */
303 export class ListBulkOperationError extends Data.TaggedError("ListBulkOperationError")<{
304 readonly operationId: string;
305 readonly status: string;
306 readonly message?: string;
307 }> {}
308
309 export const ListProvider = () =>
310 Provider.succeed(List, {
311 stables: ["listId", "accountId", "name", "kind", "createdOn"],
312 list: Effect.fn(function* () {
313 const { accountId } = yield* yield* CloudflareEnvironment;
314 return yield* rules.listLists.items({ accountId }).pipe(
315 Stream.map((list) => toAttributes(list, accountId)),
316 Stream.runCollect,
317 Effect.map((chunk) => Array.from(chunk)),
318 );
319 }),
320 diff: Effect.fn(function* ({ olds, news, output }) {
321 const { accountId } = yield* yield* CloudflareEnvironment;
322 if (!isResolved(news)) return undefined;
323 if ((output?.accountId ?? accountId) !== accountId) {
324 return { action: "replace" } as const;
325 }
326 // Lists cannot be renamed and the kind is immutable.
327 const oldName = output?.name ?? olds?.name;
328 // Auto-generated names are engine-owned: the deployed name stays
329 // authoritative even if the generator would name this id differently
330 // today. Only an explicit user-provided name can force a replace.
331 const desiredName = news.name ?? oldName;
332 if (oldName !== undefined && desiredName !== oldName) {
333 return { action: "replace" } as const;
334 }
335 const oldKind = output?.kind ?? olds?.kind;
336 if (oldKind !== undefined && news.kind !== oldKind) {
337 // List names are unique per account. When the name is unchanged the
338 // replacement cannot be create-first (the create would collide with
339 // the old list), so delete the old list before creating the new one.
340 return { action: "replace", deleteFirst: true } as const;
341 }
342 return undefined;
343 }),
344 read: Effect.fn(function* ({ id, output, olds }) {
345 const { accountId } = yield* yield* CloudflareEnvironment;
346 const acct = output?.accountId ?? accountId;
347
348 if (output?.listId) {
349 const observed = yield* getListById(acct, output.listId);
350 return observed ? toAttributes(observed, acct) : undefined;
351 }
352 // Cold read — recover from lost state by matching the deterministic
353 // physical name. List names are unique per account, so an exact match
354 // is authoritative.
355 const name = yield* createListName(id, olds?.name);
356 const match = yield* findByName(acct, name);
357 return match ? toAttributes(match, acct) : undefined;
358 }),
359 reconcile: Effect.fn(function* ({ id, news, output }) {
360 const { accountId } = yield* yield* CloudflareEnvironment;
361 // Prefer the deployed name: regenerating would target a different
362 // resource if the generator's output for this id ever drifts.
363 const name = yield* createListName(id, news.name ?? output?.name);
364
365 // Observe — the listId cached on `output` is a hint, not a guarantee:
366 // a missing list falls through to "missing" and ensure recreates.
367 let observed = output?.listId
368 ? yield* getListById(output.accountId ?? accountId, output.listId)
369 : undefined;
370 const acct = observed ? (output?.accountId ?? accountId) : accountId;
371
372 // Ensure — create when missing. A duplicate-name conflict is a race
373 // (or an out-of-band create): adopt the existing list with that name
374 // when its kind matches. When the kind differs the list cannot be
375 // converged in place (kind is immutable and names are unique), so the
376 // stale list is deleted and recreated — this is how a replacement of
377 // an explicitly-named list lands, since a create-first replacement
378 // would always collide on the name.
379 if (!observed) {
380 const create = rules.createList({
381 accountId: acct,
382 name,
383 kind: news.kind,
384 description: news.description,
385 });
386 observed = yield* create.pipe(
387 Effect.catchTag("ListAlreadyExists", (error) =>
388 findByName(acct, name).pipe(
389 Effect.flatMap((match) => {
390 if (!match) return Effect.fail(error);
391 if (match.kind === news.kind) return Effect.succeed(match);
392 return rules.deleteList({ accountId: acct, listId: match.id }).pipe(
393 Effect.catchTag("ListNotFound", () => Effect.void),
394 Effect.andThen(create),
395 );
396 }),
397 ),
398 ),
399 );
400 }
401
402 // Sync description — diff observed cloud state against desired and
403 // skip the API call entirely on a no-op.
404 if ((observed.description ?? undefined) !== news.description) {
405 observed = yield* rules.updateList({
406 accountId: acct,
407 listId: observed.id,
408 description: news.description,
409 });
410 }
411
412 // Sync items — read the observed items fresh from the cloud, compare
413 // against the desired set (keyed on value fields + comment, ignoring
414 // server-assigned ids/timestamps), and on any delta replace the full
415 // contents via the asynchronous bulk PUT, polling it to completion.
416 const desiredItems = news.items ?? [];
417 const observedItems = yield* listAllItems(acct, observed.id);
418 if (!sameItems(observedItems, desiredItems)) {
419 const { operationId } = yield* rules.updateListItem({
420 accountId: acct,
421 listId: observed.id,
422 body: desiredItems,
423 });
424 yield* awaitBulkOperation(acct, operationId);
425 }
426
427 // Return — re-read so eventually-consistent counters (numItems) and
428 // timestamps are as fresh as possible.
429 const final = yield* getListById(acct, observed.id);
430 return toAttributes(final ?? observed, acct);
431 }),
432 delete: Effect.fn(function* ({ output }) {
433 // Cloudflare's delete is itself idempotent (deleting a missing list
434 // succeeds), but tolerate a typed not-found anyway.
435 yield* rules
436 .deleteList({
437 accountId: output.accountId,
438 listId: output.listId,
439 })
440 .pipe(Effect.catchTag("ListNotFound", () => Effect.void));
441 }),
442 });
443
444 type ObservedList = rules.GetListResponse;
445
446 /**
447 * List names only allow letters, numbers, and underscores (max 50 chars), so
448 * the generated physical name swaps the default hyphen delimiter for an
449 * underscore.
450 */
451 const createListName = (id: string, name: string | undefined) =>
452 Effect.gen(function* () {
453 if (name !== undefined) return name;
454 const generated = yield* createPhysicalName({
455 id,
456 lowercase: true,
457 delimiter: "_",
458 maxLength: 50,
459 });
460 return generated.replaceAll("-", "_");
461 });
462
463 /**
464 * Read a list by id, mapping "gone" (`ListNotFound`, Cloudflare error code
465 * 10001) to `undefined`.
466 */
467 const getListById = (accountId: string, listId: string) =>
468 rules
469 .getList({ accountId, listId })
470 .pipe(Effect.catchTag("ListNotFound", () => Effect.undefined));
471
472 /**
473 * Find a list by exact name. List names are unique per account.
474 */
475 const findByName = (accountId: string, name: string) =>
476 rules.listLists.items({ accountId }).pipe(
477 Stream.filter((list) => list.name === name),
478 Stream.runHead,
479 Effect.map(Option.getOrUndefined),
480 );
481
482 /**
483 * Read the full observed contents of a list (all pages).
484 */
485 const listAllItems = (accountId: string, listId: string) =>
486 rules.listListItems.items({ accountId, listId }).pipe(
487 Stream.runCollect,
488 Effect.map((chunk) => Array.from(chunk)),
489 );
490
491 type ComparableItem = ListItem | rules.GetListItemResponse;
492
493 /**
494 * Canonicalize an item (desired prop or observed response) into a stable
495 * string key: server-assigned ids/timestamps are ignored and optional fields
496 * are normalized to their API defaults so omitted props compare equal to the
497 * defaults the API materializes.
498 */
499 const canonicalItem = (item: ComparableItem): string => {
500 const comment =
501 "comment" in item && item.comment != null && item.comment !== "" ? item.comment : undefined;
502 if ("ip" in item) {
503 return JSON.stringify({ ip: item.ip, comment });
504 }
505 if ("asn" in item) {
506 return JSON.stringify({ asn: item.asn, comment });
507 }
508 if ("hostname" in item) {
509 return JSON.stringify({
510 hostname: {
511 urlHostname: item.hostname.urlHostname,
512 excludeExactHostname: item.hostname.excludeExactHostname ?? false,
513 },
514 comment,
515 });
516 }
517 return JSON.stringify({
518 redirect: {
519 sourceUrl: item.redirect.sourceUrl,
520 targetUrl: item.redirect.targetUrl,
521 includeSubdomains: item.redirect.includeSubdomains ?? false,
522 preservePathSuffix: item.redirect.preservePathSuffix ?? false,
523 preserveQueryString: item.redirect.preserveQueryString ?? false,
524 statusCode: item.redirect.statusCode ?? 301,
525 subpathMatching: item.redirect.subpathMatching ?? false,
526 },
527 comment,
528 });
529 };
530
531 /**
532 * Compare observed and desired items as multisets of canonical keys.
533 */
534 const sameItems = (observed: readonly ComparableItem[], desired: readonly ComparableItem[]) => {
535 if (observed.length !== desired.length) return false;
536 const a = observed.map(canonicalItem).sort();
537 const b = desired.map(canonicalItem).sort();
538 return a.every((key, i) => key === b[i]);
539 };
540
541 /**
542 * Poll an asynchronous bulk items operation until it reaches a terminal
543 * state, failing with a typed error when it does not complete successfully.
544 */
545 const awaitBulkOperation = (accountId: string, operationId: string) =>
546 Effect.gen(function* () {
547 const operation = yield* rules.getListBulkOperation({ accountId, operationId }).pipe(
548 Effect.repeat({
549 schedule: Schedule.spaced("2 seconds"),
550 until: (op) => op.status === "completed" || op.status === "failed",
551 times: 90,
552 }),
553 );
554 if (operation.status !== "completed") {
555 return yield* new ListBulkOperationError({
556 operationId,
557 status: operation.status,
558 message: "error" in operation ? operation.error : undefined,
559 });
560 }
561 });
562
563 const toAttributes = (list: ObservedList, accountId: string): ListAttributes => ({
564 listId: list.id,
565 accountId,
566 name: list.name,
567 // Distilled widens generated string enums to open unions (`string & {}`).
568 kind: list.kind as ListKind,
569 description: list.description ?? undefined,
570 numItems: list.numItems,
571 numReferencingFilters: list.numReferencingFilters,
572 createdOn: list.createdOn,
573 modifiedOn: list.modifiedOn,
574 });