@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, 04:45 UTC

main
ts 332 lines 11.7 KB
Raw
1 import * as rulesets from "@distilled.cloud/cloudflare/rulesets";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { deepEqual, 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 type { OutputRule, Phase } from "./Ruleset.ts";
13
14 const TypeId = "Cloudflare.Rulesets.CustomRuleset" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * Kind of a standalone account-level ruleset. `custom` rulesets are deployed
19 * into a phase by an `execute` rule in the account's phase entrypoint;
20 * `root` rulesets are account entrypoint rulesets themselves.
21 */
22 export type CustomRulesetKind = "custom" | "root";
23
24 /**
25 * A rule inside an account custom ruleset — same shape Cloudflare accepts
26 * on the update (PUT) endpoint.
27 */
28 export type CustomRulesetRule = NonNullable<
29 rulesets.UpdateRulesetForAccountRequest["rules"]
30 >[number];
31
32 export type CustomRulesetProps = {
33 /**
34 * Human-readable name of the ruleset.
35 * @default ${app}-${stage}-${id}
36 */
37 name?: string;
38 /**
39 * The kind of the ruleset. `custom` rulesets are deployed by an `execute`
40 * rule in a phase entrypoint. Changing the kind triggers a replacement.
41 * @default "custom"
42 */
43 kind?: CustomRulesetKind;
44 /**
45 * The phase the ruleset belongs to (e.g. `http_request_firewall_custom`).
46 * Changing the phase triggers a replacement.
47 */
48 phase: Phase;
49 /**
50 * The full list of rules in the ruleset. This resource owns every rule —
51 * rules added out-of-band are overwritten on the next deploy.
52 */
53 rules: CustomRulesetRule[];
54 /**
55 * An informative description of the ruleset.
56 */
57 description?: string;
58 };
59
60 export type CustomRulesetAttributes = {
61 /** The unique ID of the ruleset (Cloudflare `id`). */
62 rulesetId: string;
63 /**
64 * Account the ruleset belongs to. Alchemy-flattened identifier — not part
65 * of Cloudflare's ruleset response.
66 */
67 accountId: string;
68 /** The kind of the ruleset. */
69 kind: string;
70 /** The human-readable name of the ruleset. */
71 name: string;
72 /** The phase of the ruleset. */
73 phase: Phase;
74 /** An informative description of the ruleset. */
75 description: string | undefined;
76 /** The list of rules in the ruleset. */
77 rules: OutputRule[];
78 /** The timestamp of when the ruleset was last modified. */
79 lastUpdated: string;
80 /** The version of the ruleset. */
81 version: string;
82 };
83
84 export type CustomRuleset = Resource<
85 TypeId,
86 CustomRulesetProps,
87 CustomRulesetAttributes,
88 never,
89 Providers
90 >;
91
92 /**
93 * A standalone account-level Cloudflare ruleset (`kind: "custom"`).
94 *
95 * Custom rulesets are the Enterprise WAF deployment workflow: define a
96 * reusable ruleset once at the account level, then deploy it across zones
97 * with an `execute` rule in a phase entrypoint (see
98 * `Cloudflare.Ruleset.AccountEntrypoint`). Account-level WAF phases require
99 * an Enterprise plan — on lower plans, creation fails with the typed
100 * `PhaseNotEntitled` error.
101 *
102 * For zone-level rules, use `Cloudflare.Ruleset.Ruleset` (the zone phase
103 * entrypoint) instead.
104 * ### Custom Rulesets
105 * **Example:** Define an account custom WAF ruleset
106 * ```typescript
107 * const ruleset = yield* Cloudflare.Ruleset.CustomRuleset("SharedWafRules", {
108 * phase: "http_request_firewall_custom",
109 * description: "Org-wide exploit probes",
110 * rules: [
111 * {
112 * description: "Block .env probes",
113 * expression: `lower(http.request.uri.path) contains "/.env"`,
114 * action: "block",
115 * },
116 * ],
117 * });
118 * ```
119 *
120 * **Example:** Deploy the custom ruleset via the account entrypoint
121 * ```typescript
122 * yield* Cloudflare.Ruleset.AccountEntrypoint("WafDeployment", {
123 * phase: "http_request_firewall_custom",
124 * rules: [
125 * {
126 * description: "Deploy shared WAF rules everywhere",
127 * expression: "true",
128 * action: "execute",
129 * actionParameters: { id: ruleset.rulesetId },
130 * },
131 * ],
132 * });
133 * ```
134 *
135 * @see https://developers.cloudflare.com/waf/account/custom-rulesets/
136 *
137 * @resource
138 * @product Rulesets
139 * @category Rules & Configuration
140 */
141 export const CustomRuleset = Resource<CustomRuleset>(TypeId);
142
143 /**
144 * Returns true if the given value is a CustomRuleset resource.
145 */
146 export const isCustomRuleset = (value: unknown): value is CustomRuleset =>
147 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
148
149 export const CustomRulesetProvider = () =>
150 Provider.succeed(CustomRuleset, {
151 stables: ["rulesetId", "accountId", "kind", "phase"],
152
153 diff: Effect.fn(function* ({ id, olds, news, output }) {
154 if (!isResolved(news)) return undefined;
155 // kind and phase are immutable on Cloudflare's API.
156 if ((olds.kind ?? "custom") !== (news.kind ?? "custom")) {
157 return { action: "replace" } as const;
158 }
159 if (olds.phase !== news.phase) {
160 return { action: "replace" } as const;
161 }
162 const { accountId } = yield* yield* CloudflareEnvironment;
163 if (output !== undefined && output.accountId !== accountId) {
164 return { action: "replace" } as const;
165 }
166 const oldName = output?.name ?? olds.name ?? (yield* createPhysicalName({ id }));
167 // Auto-generated names are engine-owned: the deployed name stays
168 // authoritative even if the generator would name this id differently
169 // today. Only an explicit user-provided name can force a rename.
170 const name = news.name ?? oldName;
171 if (
172 oldName !== name ||
173 olds.description !== news.description ||
174 !deepEqual(olds.rules, news.rules)
175 ) {
176 return { action: "update" } as const;
177 }
178 }),
179
180 read: Effect.fn(function* ({ id, olds, output }) {
181 const { accountId } = yield* yield* CloudflareEnvironment;
182 if (output !== undefined) {
183 return yield* rulesets
184 .getRulesetForAccount({
185 accountId: output.accountId,
186 rulesetId: output.rulesetId,
187 })
188 .pipe(
189 Effect.map((ruleset) => toCustomRulesetAttributes(output.accountId, ruleset)),
190 Effect.catchTag("RulesetNotFound", () => Effect.undefined),
191 );
192 }
193 // Cold lookup — no persisted state. Find the ruleset by its
194 // deterministic name + phase + kind. Rulesets carry no tags, so we
195 // cannot prove we created a match — report it `Unowned` and let the
196 // engine gate takeover behind `--adopt`.
197 const name = olds?.name ?? (yield* createPhysicalName({ id }));
198 const kind = olds?.kind ?? "custom";
199 const match = yield* rulesets.listRulesetsForAccount.items({ accountId }).pipe(
200 Stream.runCollect,
201 Effect.map((chunk) =>
202 Array.from(chunk).find(
203 (r) => r.name === name && r.phase === olds?.phase && r.kind === kind,
204 ),
205 ),
206 );
207 if (match === undefined) return undefined;
208 const ruleset = yield* rulesets
209 .getRulesetForAccount({ accountId, rulesetId: match.id })
210 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.undefined));
211 if (ruleset === undefined) return undefined;
212 return Unowned(toCustomRulesetAttributes(accountId, ruleset));
213 }),
214
215 reconcile: Effect.fn(function* ({ id, news, output }) {
216 const { accountId } = yield* yield* CloudflareEnvironment;
217 // Prefer the deployed name: regenerating would target a different
218 // resource if the generator's output for this id ever drifts.
219 const name = news.name ?? output?.name ?? (yield* createPhysicalName({ id }));
220 const kind = news.kind ?? "custom";
221
222 // 1. Observe — the persisted rulesetId is a cache, not a guarantee.
223 const observed =
224 output !== undefined
225 ? yield* rulesets
226 .getRulesetForAccount({
227 accountId,
228 rulesetId: output.rulesetId,
229 })
230 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.undefined))
231 : undefined;
232
233 // 2. Ensure — create when missing.
234 if (observed === undefined) {
235 const created = yield* rulesets.createRulesetForAccount({
236 accountId,
237 kind,
238 name,
239 phase: news.phase,
240 description: news.description,
241 rules: news.rules,
242 });
243 return toCustomRulesetAttributes(accountId, created);
244 }
245
246 // 3. Sync — PUT the full desired state only when it differs from the
247 // observed cloud state.
248 const observedAttributes = toCustomRulesetAttributes(accountId, observed);
249 const desiredRules = normalizeDesiredRules(news.rules);
250 if (
251 observedAttributes.name === name &&
252 observedAttributes.description === news.description &&
253 deepEqual(normalizeObservedRules(observedAttributes.rules), desiredRules)
254 ) {
255 return observedAttributes;
256 }
257 const updated = yield* rulesets.updateRulesetForAccount({
258 accountId,
259 rulesetId: observedAttributes.rulesetId,
260 name,
261 description: news.description,
262 rules: news.rules,
263 });
264 return toCustomRulesetAttributes(accountId, updated);
265 }),
266
267 delete: Effect.fn(function* ({ output }) {
268 // Idempotent — a ruleset already deleted out-of-band is not an error.
269 yield* rulesets
270 .deleteRulesetForAccount({
271 accountId: output.accountId,
272 rulesetId: output.rulesetId,
273 })
274 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.void));
275 }),
276
277 // Account-scoped enumeration. `listRulesetsForAccount` returns every
278 // ruleset kind (managed/root/custom/zone) but omits each ruleset's rules,
279 // so filter to `custom` and hydrate each via `getRulesetForAccount` to
280 // produce the full `read` Attributes shape. Per-item not-found / Forbidden
281 // blips skip that ruleset rather than failing the whole enumeration.
282 list: Effect.fn(function* () {
283 const { accountId } = yield* yield* CloudflareEnvironment;
284 const summaries = yield* rulesets.listRulesetsForAccount.pages({ accountId }).pipe(
285 Stream.runCollect,
286 Effect.map((chunk) =>
287 Array.from(chunk).flatMap((page) =>
288 (page.result ?? []).filter((r) => r.kind === "custom"),
289 ),
290 ),
291 );
292 const hydrated = yield* Effect.forEach(
293 summaries,
294 (summary) =>
295 rulesets.getRulesetForAccount({ accountId, rulesetId: summary.id }).pipe(
296 Effect.map((ruleset) => toCustomRulesetAttributes(accountId, ruleset)),
297 Effect.catchTag(["RulesetNotFound", "Forbidden"], () => Effect.undefined),
298 ),
299 { concurrency: 10 },
300 );
301 return hydrated.filter((row): row is CustomRulesetAttributes => row !== undefined);
302 }),
303 });
304
305 const toCustomRulesetAttributes = (
306 accountId: string,
307 ruleset:
308 | rulesets.GetRulesetResponse
309 | rulesets.CreateRulesetResponse
310 | rulesets.UpdateRulesetResponse,
311 ): CustomRulesetAttributes => ({
312 rulesetId: ruleset.id,
313 accountId,
314 kind: ruleset.kind,
315 name: ruleset.name,
316 phase: ruleset.phase,
317 description: ruleset.description ?? undefined,
318 rules: (ruleset.rules ?? []).map(
319 ({ lastUpdated: _lastUpdated, version: _version, ...rule }) => rule,
320 ),
321 lastUpdated: ruleset.lastUpdated,
322 version: ruleset.version,
323 });
324
325 /**
326 * Strip server-assigned per-rule fields so observed rules can be compared
327 * structurally against the desired props.
328 */
329 const normalizeObservedRules = (rules: OutputRule[]) => rules.map(({ id: _id, ...rule }) => rule);
330
331 const normalizeDesiredRules = (rules: CustomRulesetRule[]) =>
332 rules.map(({ id: _id, ...rule }) => rule);