@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 290 lines 10.4 KB
Raw
1 import * as rulesets from "@distilled.cloud/cloudflare/rulesets";
2 import { deepEqual, 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 Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { Attributes, Zone } from "../Zone/index.ts";
12 import { listAllZones } from "../Zone/lookup.ts";
13
14 export class RulesetInvalidProps extends Data.TaggedError("RulesetInvalidProps")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export type Phase = NonNullable<rulesets.CreateRulesetForZoneRequest["phase"]>;
20 export type Rule = NonNullable<rulesets.PutPhasForZoneRequest["rules"]>[number];
21 export type OutputRule = Omit<
22 NonNullable<rulesets.GetPhasResponse["rules"]>[number],
23 "lastUpdated" | "version"
24 >;
25
26 export type RulesetProps = {
27 /**
28 * Zone to apply the ruleset to. Pass a `Cloudflare.Zone.Zone`.
29 */
30 zone: Zone;
31 /**
32 * Ruleset phase entrypoint to own.
33 */
34 phase: Phase;
35 /**
36 * Rules to apply to the phase entrypoint.
37 */
38 rules: Rule[];
39 /**
40 * Human-readable name for the ruleset.
41 * @default ${app}-${stage}-${id}
42 */
43 name?: string;
44 /**
45 * Description for the ruleset.
46 */
47 description?: string;
48 };
49
50 export type Kind = "managed" | "custom" | "root" | "zone" | (string & {});
51
52 export type Ruleset = Resource<
53 "Cloudflare.Ruleset.Ruleset",
54 RulesetProps,
55 {
56 /** The unique ID of the ruleset (Cloudflare `id`). */
57 rulesetId: string;
58 /**
59 * Zone the ruleset phase entrypoint belongs to. Alchemy-flattened
60 * identifier — not part of Cloudflare's phase-entrypoint response.
61 */
62 zoneId: string;
63 /** The kind of the ruleset. */
64 kind: Kind;
65 /** The human-readable name of the ruleset. */
66 name: string;
67 /** The phase of the ruleset. */
68 phase: Phase;
69 /** An informative description of the ruleset. */
70 description: string | undefined;
71 /** The list of rules in the ruleset. */
72 rules: OutputRule[];
73 /** The timestamp of when the ruleset was last modified. */
74 lastUpdated: string;
75 /** The version of the ruleset. */
76 version: string;
77 },
78 never,
79 Providers
80 >;
81
82 /**
83 * A Cloudflare Ruleset phase entrypoint for a zone.
84 *
85 * This resource owns the entire ruleset for a phase entrypoint. Rules managed
86 * elsewhere in the same phase can be overwritten on deploy. Destroying it
87 * removes only the rules it deployed; the entrypoint and any rules added
88 * since stay in place.
89 * ### WAF Rules
90 * **Example:** Block probes in the custom firewall phase
91 * ```typescript
92 * const zone = yield* Cloudflare.Zone.Zone("MyZone", { name: "example.com" });
93 * const waf = yield* Cloudflare.Ruleset.Ruleset("WafRules", {
94 * zone,
95 * phase: "http_request_firewall_custom",
96 * rules: [
97 * {
98 * description: "Block exploit probes",
99 * expression: `lower(http.request.uri.path) contains "/.env"`,
100 * action: "block",
101 * },
102 * ],
103 * });
104 * ```
105 *
106 * @resource
107 * @product Rulesets
108 * @category Rules & Configuration
109 */
110 export const Ruleset = Resource<Ruleset>("Cloudflare.Ruleset.Ruleset", {
111 aliases: ["Cloudflare.Ruleset"],
112 })({});
113
114 export const RulesetProvider = () =>
115 Provider.succeed(Ruleset, {
116 stables: ["zoneId", "phase"],
117 diff: Effect.fn(function* ({ id, olds, news, output }) {
118 if (!isResolved(news)) return undefined;
119 const desiredZoneId = zoneIdOf(news.zone);
120
121 // The desired zone id may still be an unresolved Output (e.g. the
122 // zone is being created in the same deploy). Only make a zone-change
123 // replacement decision once we have a concrete id.
124 if (desiredZoneId !== undefined) {
125 if (output?.zoneId && desiredZoneId !== output.zoneId) {
126 return { action: "replace" } as const;
127 }
128 const oldZoneId = olds.zone ? zoneIdOf(olds.zone) : undefined;
129 if (oldZoneId !== undefined && oldZoneId !== desiredZoneId) {
130 return { action: "replace" } as const;
131 }
132 }
133 if (olds.phase !== news.phase) {
134 return { action: "replace" } as const;
135 }
136
137 const oldName = output?.name ?? (yield* createRulesetName(id, olds.name));
138 // Auto-generated names are engine-owned: the deployed name stays
139 // authoritative even if the generator would name this id differently
140 // today. Only an explicit user-provided name can force a rename.
141 const name = news.name ?? oldName;
142 if (
143 oldName !== name ||
144 olds.description !== news.description ||
145 !deepEqual(olds.rules, news.rules)
146 ) {
147 return { action: "update" } as const;
148 }
149 }),
150 reconcile: Effect.fn(function* ({ id, news, output }) {
151 const zoneId = output?.zoneId ?? zoneIdOf(news.zone);
152 if (zoneId === undefined) {
153 return yield* new RulesetInvalidProps({
154 message: "Cloudflare Ruleset: zone id is not resolved",
155 });
156 }
157 const name = yield* createRulesetName(id, news.name ?? output?.name);
158 const ruleset = yield* rulesets.putPhasForZone({
159 zoneId,
160 rulesetPhase: news.phase,
161 name,
162 description: news.description,
163 rules: news.rules,
164 });
165 return toRulesetAttributes(zoneId, ruleset);
166 }),
167 delete: Effect.fn(function* ({ olds, output }) {
168 // Remove only the rules this resource deployed. The entrypoint is the
169 // zone's shared WAF phase — rules added elsewhere must survive.
170 const entrypoint = yield* rulesets
171 .getPhasForZone({
172 zoneId: output.zoneId,
173 rulesetPhase: output.phase ?? olds.phase,
174 })
175 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.undefined));
176 if (entrypoint === undefined) return;
177 const owned = new Set(output.rules.map((rule) => rule.id));
178 yield* Effect.forEach(
179 (entrypoint.rules ?? []).filter((rule) => rule.id != null && owned.has(rule.id)),
180 (rule) =>
181 rulesets.deleteRuleForZone({
182 zoneId: output.zoneId,
183 rulesetId: entrypoint.id,
184 ruleId: rule.id!,
185 }),
186 { discard: true },
187 );
188 }),
189 read: Effect.fn(function* ({ olds, output }) {
190 const zoneId = output?.zoneId ?? zoneIdOf(olds.zone);
191 if (zoneId === undefined) return undefined;
192 return yield* rulesets
193 .getPhasForZone({
194 zoneId,
195 rulesetPhase: output?.phase ?? olds.phase,
196 })
197 .pipe(
198 Effect.map((ruleset) => toRulesetAttributes(zoneId, ruleset)),
199 Effect.catchTag("RulesetNotFound", () => Effect.undefined),
200 );
201 }),
202 // A `Ruleset` is a zone phase entrypoint (kind: "zone"). There is no
203 // account-wide enumeration for entrypoints, so fan out over every zone
204 // via `listAllZones`, list that zone's rulesets, keep the entrypoints,
205 // and hydrate each into the full Attributes shape (the list response
206 // omits `rules`) via `getPhasForZone`.
207 list: Effect.fn(function* () {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209 const zones = yield* listAllZones(accountId);
210 const rows = yield* Effect.forEach(
211 zones,
212 (zone) =>
213 rulesets.listRulesetsForZone.pages({ zoneId: zone.id }).pipe(
214 Stream.runCollect,
215 Effect.map((chunk) =>
216 Array.from(chunk).flatMap((page) =>
217 (page.result ?? []).filter((r) => r.kind === "zone"),
218 ),
219 ),
220 Effect.flatMap((entrypoints) =>
221 Effect.forEach(
222 entrypoints,
223 (entry) =>
224 rulesets
225 .getPhasForZone({
226 zoneId: zone.id,
227 rulesetPhase: entry.phase,
228 })
229 .pipe(
230 Effect.map((ruleset) => toRulesetAttributes(zone.id, ruleset)),
231 // Per-item not-found / plan-gated entrypoints are
232 // skipped rather than failing the whole enumeration.
233 Effect.catchTag(["RulesetNotFound", "Forbidden"], () => Effect.undefined),
234 ),
235 { concurrency: 10 },
236 ),
237 ),
238 Effect.map((items) =>
239 items.filter(
240 (item): item is Ruleset["Attributes"] =>
241 // An entrypoint with zero rules is inert — it's what other
242 // owners (e.g. Worker redirect cleanup) leave behind after
243 // removing their rules. Don't surface it as a resource.
244 item !== undefined && item.rules.length > 0,
245 ),
246 ),
247 // Plan-gated / partially-provisioned zones reject the route.
248 Effect.catchTag("InvalidRoute", () => Effect.succeed([])),
249 ),
250 { concurrency: 10 },
251 );
252 return rows.flat();
253 }),
254 });
255
256 const createRulesetName = (id: string, name: string | undefined) =>
257 Effect.gen(function* () {
258 return name ?? (yield* createPhysicalName({ id }));
259 });
260
261 export const toRulesetAttributes = (
262 zoneId: string,
263 ruleset: rulesets.GetPhasResponse | rulesets.PutPhasResponse,
264 ): Ruleset["Attributes"] => ({
265 rulesetId: ruleset.id,
266 zoneId,
267 kind: ruleset.kind,
268 name: ruleset.name,
269 phase: ruleset.phase,
270 description: ruleset.description ?? undefined,
271 rules: (ruleset.rules ?? []).map(
272 ({ lastUpdated: _lastUpdated, version: _version, ...rule }) => rule,
273 ),
274 lastUpdated: ruleset.lastUpdated,
275 version: ruleset.version,
276 });
277
278 // A `Zone` prop is resolved to its attributes before a lifecycle op runs, so
279 // `zone.zoneId` is normally a plain string even though the `Zone` resource
280 // type statically exposes it as an `Output`. During `diff` (plan time) the
281 // zone can still be unresolved — e.g. when it's being created in the same
282 // deploy — in which case `zoneId` is not yet a string. Callers must treat a
283 // non-string result as "not resolved yet". May also receive `undefined`:
284 // an Output-valued `zone` doesn't survive a `creating`-state round-trip
285 // (it deserializes as `undefined`), and recovery paths hand those props
286 // back as `olds`.
287 const zoneIdOf = (zone: Zone | undefined): string | undefined => {
288 const zoneId = (zone as unknown as Partial<Attributes> | undefined)?.zoneId;
289 return typeof zoneId === "string" ? zoneId : undefined;
290 };