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

main
ts 369 lines 13.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 LockdownTypeId = "Cloudflare.Firewall.Lockdown" as const;
13 type LockdownTypeId = typeof LockdownTypeId;
14
15 /**
16 * A single allow-list entry of a Zone Lockdown rule: a single IP address
17 * (`ip`) or a CIDR range (`ip_range`) that is allowed to access the
18 * locked-down URLs.
19 */
20 export interface LockdownConfiguration {
21 /**
22 * Whether `value` is a single IP address (`ip`) or a CIDR range
23 * (`ip_range`).
24 */
25 target: "ip" | "ip_range";
26 /**
27 * The IP address (e.g. `198.51.100.4`) or CIDR range
28 * (e.g. `203.0.113.0/24`) to allow.
29 */
30 value: string;
31 }
32
33 export interface LockdownProps {
34 /**
35 * Zone the lockdown rule applies to.
36 *
37 * Stable — moving a rule between zones triggers a replacement.
38 */
39 zoneId: string;
40 /**
41 * The URLs to lock down. Each entry is escaped before use, so only simple
42 * wildcard patterns are supported (e.g. `shop.example.com/admin*`).
43 *
44 * Mutable — updated in place via PUT.
45 */
46 urls: string[];
47 /**
48 * The IP addresses and CIDR ranges that are allowed to access the URLs.
49 * Everyone else is blocked.
50 *
51 * Mutable — updated in place via PUT.
52 */
53 configurations: LockdownConfiguration[];
54 /**
55 * An informative summary of the rule. Sanitized server-side (HTML tags
56 * are removed).
57 *
58 * Mutable — updated in place via PUT.
59 */
60 description?: string;
61 /**
62 * When true, the rule is disabled without being deleted.
63 *
64 * Mutable — updated in place via PUT.
65 *
66 * @default false
67 */
68 paused?: boolean;
69 /**
70 * Processing order — a lower number indicates higher priority. Rules
71 * without a priority are processed before rules with one.
72 *
73 * Mutable — updated in place via PUT.
74 */
75 priority?: number;
76 }
77
78 export interface LockdownAttributes {
79 /** Cloudflare-assigned identifier of the Zone Lockdown rule. */
80 lockdownId: string;
81 /** Zone the rule belongs to. */
82 zoneId: string;
83 /** The locked-down URL patterns. */
84 urls: string[];
85 /** The allowed IP addresses and CIDR ranges. */
86 configurations: LockdownConfiguration[];
87 /** The rule's informative summary, if set. */
88 description: string | undefined;
89 /** Whether the rule is currently paused. */
90 paused: boolean;
91 /** The rule's processing priority, if set. */
92 priority: number | undefined;
93 /** ISO8601 creation timestamp. */
94 createdOn: string;
95 /** ISO8601 last-modified timestamp. */
96 modifiedOn: string;
97 }
98
99 export type Lockdown = Resource<
100 LockdownTypeId,
101 LockdownProps,
102 LockdownAttributes,
103 never,
104 Providers
105 >;
106
107 /**
108 * A Cloudflare Zone Lockdown rule — restrict one or more URL patterns on a
109 * zone so that only an allow-list of IP addresses and CIDR ranges can access
110 * them. Every other visitor receives an "Access Denied" page.
111 *
112 * Everything about a lockdown rule is mutable in place: `urls`,
113 * `configurations`, `description`, `paused`, and `priority` are all updated
114 * via PUT without replacing the rule. Only moving the rule to a different
115 * zone triggers a replacement.
116 *
117 * Zone Lockdown is available on Pro plans and above, with per-plan rule
118 * quotas (Pro: 3, Business: 10, Enterprise: 200). Cloudflare rejects a
119 * second rule covering the same URLs with a duplicate error, so a rule's
120 * URL set acts as its identity within a zone.
121 *
122 * Safety: lockdown rules carry no ownership markers. When there is no prior
123 * state, `read` scans the zone for an existing rule with the same URL set
124 * and reports it as `Unowned`, so the engine refuses to take it over unless
125 * `--adopt` (or `adopt(true)`) is set.
126 * ### Locking down a URL
127 * **Example:** Allow a single office IP to reach an admin panel
128 * ```typescript
129 * yield* Cloudflare.Firewall.Lockdown("AdminLockdown", {
130 * zoneId: zone.zoneId,
131 * urls: ["shop.example.com/admin*"],
132 * configurations: [{ target: "ip", value: "198.51.100.4" }],
133 * description: "only the office can reach /admin",
134 * });
135 * ```
136 *
137 * **Example:** Allow a CIDR range across multiple URLs
138 * ```typescript
139 * yield* Cloudflare.Firewall.Lockdown("StaffOnly", {
140 * zoneId: zone.zoneId,
141 * urls: ["example.com/internal*", "example.com/staging*"],
142 * configurations: [
143 * { target: "ip_range", value: "203.0.113.0/24" },
144 * { target: "ip", value: "198.51.100.4" },
145 * ],
146 * });
147 * ```
148 *
149 * ### Pausing a rule
150 * **Example:** Temporarily disable a lockdown without deleting it
151 * ```typescript
152 * yield* Cloudflare.Firewall.Lockdown("AdminLockdown", {
153 * zoneId: zone.zoneId,
154 * urls: ["shop.example.com/admin*"],
155 * configurations: [{ target: "ip", value: "198.51.100.4" }],
156 * paused: true,
157 * });
158 * ```
159 *
160 * @see https://developers.cloudflare.com/waf/tools/zone-lockdown/
161 *
162 * @resource
163 * @product Firewall
164 * @category Application Security
165 */
166 export const Lockdown = Resource<Lockdown>(LockdownTypeId);
167
168 /**
169 * Returns true if the given value is a Lockdown resource.
170 */
171 export const isLockdown = (value: unknown): value is Lockdown =>
172 Predicate.hasProperty(value, "Type") && value.Type === LockdownTypeId;
173
174 export const LockdownProvider = () =>
175 Provider.succeed(Lockdown, {
176 stables: ["lockdownId", "zoneId", "createdOn"],
177
178 diff: Effect.fn(function* ({ olds = {}, news }) {
179 const o = olds as LockdownProps;
180 const n = news as LockdownProps;
181 // No prior props to compare against — let the engine decide.
182 if (o.zoneId === undefined) return undefined;
183 // zoneId is Input<string>; compare only once both are concrete.
184 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
185 return { action: "replace" } as const;
186 }
187 return undefined;
188 }),
189
190 read: Effect.fn(function* ({ output, olds }) {
191 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
192 if (zoneId === undefined) return undefined;
193
194 // Owned path: refresh by our persisted lockdown id.
195 if (output?.lockdownId) {
196 const observed = yield* getLockdown(zoneId, output.lockdownId);
197 if (observed) return toAttributes(observed, zoneId);
198 }
199
200 // Adoption path: a rule covering the same URLs may already exist —
201 // Cloudflare rejects overlapping duplicates, so the URL set is the
202 // rule's identity within the zone. Lockdown rules carry no ownership
203 // markers, so brand a match `Unowned` and let the engine gate
204 // takeover behind the adopt policy.
205 const urls = output?.urls ?? olds?.urls;
206 if (urls) {
207 const observed = yield* findByUrls(zoneId, urls);
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 lockdown id cached on `output` is a hint, not a
218 // guarantee: a missing rule falls through to the URL scan and
219 // then to create.
220 let observed = output?.lockdownId ? yield* getLockdown(zoneId, output.lockdownId) : undefined;
221
222 // 2. Fall back to scanning the zone for a rule with the same URL
223 // set. Ownership has already been verified upstream — `read`
224 // reports existing rules as `Unowned` and the engine gates
225 // takeover behind the adopt policy before reconcile ever runs.
226 if (!observed) {
227 observed = yield* findByUrls(zoneId, news.urls);
228 }
229
230 // 3. Ensure — create when missing. A concurrent create surfaces as
231 // `DuplicateLockdown` (Cloudflare code 10009): converge by
232 // re-scanning for the rule that won the race.
233 if (!observed) {
234 observed = yield* firewall
235 .createLockdown({
236 zoneId,
237 urls: news.urls,
238 configurations: news.configurations,
239 description: news.description,
240 paused: news.paused,
241 priority: news.priority,
242 })
243 .pipe(
244 Effect.catchTag("DuplicateLockdown", (error) =>
245 findByUrls(zoneId, news.urls).pipe(
246 Effect.flatMap((existing) =>
247 existing ? Effect.succeed(existing) : Effect.fail(error),
248 ),
249 ),
250 ),
251 );
252 }
253
254 // 4. Sync — diff observed cloud state against desired; skip the PUT
255 // entirely on a no-op. Undefined optional props are treated as
256 // "no constraint" so adoption doesn't clobber foreign settings.
257 const dirty =
258 !sameStringSet(observed.urls, news.urls) ||
259 !sameConfigurationSet(observed.configurations, news.configurations) ||
260 (news.description !== undefined && (observed.description ?? "") !== news.description) ||
261 (news.paused !== undefined && observed.paused !== news.paused) ||
262 (news.priority !== undefined && (observed.priority ?? undefined) !== news.priority);
263 if (dirty) {
264 observed = yield* firewall.updateLockdown({
265 zoneId,
266 lockDownsId: observed.id,
267 urls: news.urls,
268 configurations: news.configurations,
269 description: news.description,
270 paused: news.paused,
271 priority: news.priority,
272 });
273 }
274
275 return toAttributes(observed, zoneId);
276 }),
277
278 // Zone Lockdown rules are zone-scoped: there is no account-wide list, so
279 // enumerate every zone and exhaustively paginate its lockdown rules,
280 // hydrating each into the same Attributes shape `read` returns. Zone
281 // Lockdown is a Pro+ feature, so plan-gated zones reject the route with a
282 // typed `Forbidden` — skip those rather than failing the whole list.
283 list: Effect.fn(function* () {
284 const { accountId } = yield* yield* CloudflareEnvironment;
285 const zones = yield* listAllZones(accountId);
286 const rows = yield* Effect.forEach(
287 zones,
288 (zone) =>
289 firewall.listLockdowns.items({ zoneId: zone.id }).pipe(
290 Stream.runCollect,
291 Effect.map((chunk) => Array.from(chunk).map((rule) => toAttributes(rule, zone.id))),
292 Effect.catchTag("Forbidden", () => Effect.succeed([])),
293 ),
294 { concurrency: 10 },
295 );
296 return rows.flat();
297 }),
298
299 delete: Effect.fn(function* ({ output }) {
300 // Cloudflare's DELETE is naturally idempotent (an already-gone rule
301 // answers HTTP 200 echoing the id) — the typed catch covers the rare
302 // not-found envelope race.
303 yield* firewall
304 .deleteLockdown({
305 zoneId: output.zoneId,
306 lockDownsId: output.lockdownId,
307 })
308 .pipe(Effect.catchTag("LockdownNotFound", () => Effect.void));
309 }),
310 });
311
312 // ---------------------------------------------------------------------------
313 // API helpers
314 // ---------------------------------------------------------------------------
315
316 type ObservedLockdown = firewall.GetLockdownResponse;
317
318 /**
319 * Read a lockdown rule by id, mapping "gone" (`LockdownNotFound`, Cloudflare
320 * error code 10001 `zonelockdown.api.not_found`) to `undefined`.
321 */
322 const getLockdown = (zoneId: string, lockdownId: string) =>
323 firewall.getLockdown({ zoneId, lockDownsId: lockdownId }).pipe(
324 Effect.map((rule): ObservedLockdown | undefined => rule),
325 Effect.catchTag("LockdownNotFound", () => Effect.undefined),
326 );
327
328 /**
329 * Find a lockdown rule by exact URL set within the zone. Cloudflare rejects
330 * a second rule covering the same URLs as `zonelockdown.api.duplicate_of_existing`,
331 * so the URL set acts as a rule's identity.
332 */
333 const findByUrls = (zoneId: string, urls: readonly string[]) =>
334 firewall.listLockdowns.items({ zoneId }).pipe(
335 Stream.runCollect,
336 Effect.map((chunk) =>
337 Array.from(chunk).find((rule): rule is ObservedLockdown => sameStringSet(rule.urls, urls)),
338 ),
339 );
340
341 const sameStringSet = (a: readonly string[], b: readonly string[]) =>
342 a.length === b.length && [...a].sort().join("\n") === [...b].sort().join("\n");
343
344 const configurationKey = (c: { target?: string | null; value?: string | null }) =>
345 `${c.target ?? ""}=${c.value ?? ""}`;
346
347 const sameConfigurationSet = (
348 a: readonly { target?: string | null; value?: string | null }[],
349 b: readonly LockdownConfiguration[],
350 ) =>
351 a.length === b.length &&
352 a.map(configurationKey).sort().join("\n") === b.map(configurationKey).sort().join("\n");
353
354 const toAttributes = (rule: ObservedLockdown, zoneId: string): LockdownAttributes => ({
355 lockdownId: rule.id,
356 zoneId,
357 urls: [...rule.urls],
358 configurations: rule.configurations.map((c) => ({
359 // Distilled types each union variant's target/value as optional —
360 // Cloudflare always echoes both for a persisted rule.
361 target: (c.target ?? "ip") as LockdownConfiguration["target"],
362 value: c.value ?? "",
363 })),
364 description: rule.description ?? undefined,
365 paused: rule.paused,
366 priority: rule.priority ?? undefined,
367 createdOn: rule.createdOn,
368 modifiedOn: rule.modifiedOn,
369 });