@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 288 lines 10.3 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 Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { OutputRule, Phase } from "./Ruleset.ts";
12
13 const TypeId = "Cloudflare.Rulesets.AccountEntrypoint" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * A rule inside an account phase entrypoint — same shape Cloudflare accepts
18 * on the entrypoint PUT endpoint.
19 */
20 export type AccountEntrypointRule = NonNullable<rulesets.PutPhasForAccountRequest["rules"]>[number];
21
22 export type AccountEntrypointProps = {
23 /**
24 * Ruleset phase entrypoint to own (e.g. `http_request_firewall_custom`,
25 * `ddos_l4`, `magic_transit`). Changing the phase triggers a
26 * replacement. Most account-level phases are Enterprise-gated — on lower
27 * plans, deploys fail with the typed `PhaseNotEntitled` error.
28 * `http_request_redirect` (Bulk Redirects) is available on every plan.
29 */
30 phase: Phase;
31 /**
32 * The full list of rules in the phase entrypoint. This resource owns the
33 * entire entrypoint — rules managed elsewhere in the same phase are
34 * overwritten on deploy. For the Enterprise WAF deployment workflow, use
35 * `execute` rules referencing `Cloudflare.Ruleset.CustomRuleset` ids.
36 */
37 rules: AccountEntrypointRule[];
38 /**
39 * Human-readable name for the entrypoint ruleset.
40 * @default ${app}-${stage}-${id}
41 */
42 name?: string;
43 /**
44 * An informative description of the ruleset.
45 */
46 description?: string;
47 };
48
49 export type AccountEntrypointAttributes = {
50 /** The unique ID of the entrypoint ruleset (Cloudflare `id`). */
51 rulesetId: string;
52 /**
53 * Account the phase entrypoint belongs to. Alchemy-flattened identifier —
54 * not part of Cloudflare's phase-entrypoint response.
55 */
56 accountId: string;
57 /** The kind of the ruleset (`root` for account entrypoints). */
58 kind: string;
59 /** The human-readable name of the ruleset. */
60 name: string;
61 /** The phase of the ruleset. */
62 phase: Phase;
63 /** An informative description of the ruleset. */
64 description: string | undefined;
65 /** The list of rules in the entrypoint. */
66 rules: OutputRule[];
67 /** The timestamp of when the ruleset was last modified. */
68 lastUpdated: string;
69 /** The version of the ruleset. */
70 version: string;
71 };
72
73 export type AccountEntrypoint = Resource<
74 TypeId,
75 AccountEntrypointProps,
76 AccountEntrypointAttributes,
77 never,
78 Providers
79 >;
80
81 /**
82 * A Cloudflare Ruleset phase entrypoint for an account.
83 *
84 * The account-level counterpart of `Cloudflare.Ruleset.Ruleset`: it owns the entire
85 * ruleset for an account phase entrypoint (e.g. deploying custom WAF
86 * rulesets across zones with `execute` rules, or configuring `ddos_l4` /
87 * `magic_transit` rules). The entrypoint is a per-phase singleton — destroy
88 * empties its rules rather than deleting the phase.
89 *
90 * Most account-level phases require an Enterprise plan; on lower plans
91 * deploys fail with the typed `PhaseNotEntitled` error. The
92 * `http_request_redirect` phase (Bulk Redirects) is available on every plan.
93 * ### Account WAF Deployment
94 * **Example:** Deploy a custom ruleset across all zones
95 * ```typescript
96 * const ruleset = yield* Cloudflare.Ruleset.CustomRuleset("SharedWafRules", {
97 * phase: "http_request_firewall_custom",
98 * rules: [
99 * {
100 * description: "Block exploit probes",
101 * expression: `lower(http.request.uri.path) contains "/.env"`,
102 * action: "block",
103 * },
104 * ],
105 * });
106 *
107 * yield* Cloudflare.Ruleset.AccountEntrypoint("WafDeployment", {
108 * phase: "http_request_firewall_custom",
109 * rules: [
110 * {
111 * description: "Deploy shared WAF rules",
112 * expression: "true",
113 * action: "execute",
114 * actionParameters: { id: ruleset.rulesetId },
115 * },
116 * ],
117 * });
118 * ```
119 *
120 * ### Bulk Redirects
121 * **Example:** Redirect every mapping in a list with one rule
122 * ```typescript
123 * const redirects = yield* Cloudflare.Rules.List("Redirects", {
124 * kind: "redirect",
125 * items: [
126 * {
127 * redirect: {
128 * sourceUrl: "example.com/old",
129 * targetUrl: "https://example.com/new",
130 * statusCode: 301,
131 * },
132 * },
133 * ],
134 * });
135 *
136 * yield* Cloudflare.Ruleset.AccountEntrypoint("BulkRedirects", {
137 * phase: "http_request_redirect",
138 * rules: [
139 * {
140 * ref: "redirects",
141 * expression: Output.interpolate`http.request.full_uri in $${redirects.name}`,
142 * action: "redirect",
143 * actionParameters: {
144 * fromList: { name: redirects.name, key: "http.request.full_uri" },
145 * },
146 * },
147 * ],
148 * });
149 * ```
150 *
151 * @see https://developers.cloudflare.com/waf/account/
152 * @see https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/
153 *
154 * @resource
155 * @product Rulesets
156 * @category Rules & Configuration
157 */
158 export const AccountEntrypoint = Resource<AccountEntrypoint>(TypeId);
159
160 /**
161 * Returns true if the given value is a AccountEntrypoint resource.
162 */
163 export const isAccountEntrypoint = (value: unknown): value is AccountEntrypoint =>
164 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
165
166 export const AccountEntrypointProvider = () =>
167 Provider.succeed(AccountEntrypoint, {
168 stables: ["rulesetId", "accountId", "kind", "phase"],
169
170 diff: Effect.fn(function* ({ id, olds, news, output }) {
171 if (!isResolved(news)) return undefined;
172 // The phase is the entrypoint's identity.
173 if (olds.phase !== news.phase) {
174 return { action: "replace" } as const;
175 }
176 const { accountId } = yield* yield* CloudflareEnvironment;
177 if (output !== undefined && output.accountId !== accountId) {
178 return { action: "replace" } as const;
179 }
180 const oldName = output?.name ?? olds.name ?? (yield* createPhysicalName({ id }));
181 // Auto-generated names are engine-owned: the deployed name stays
182 // authoritative even if the generator would name this id differently
183 // today. Only an explicit user-provided name can force a rename.
184 const name = news.name ?? oldName;
185 if (
186 oldName !== name ||
187 olds.description !== news.description ||
188 !deepEqual(olds.rules, news.rules)
189 ) {
190 return { action: "update" } as const;
191 }
192 }),
193
194 list: Effect.fn(function* () {
195 const { accountId } = yield* yield* CloudflareEnvironment;
196 // Account phase entrypoints are the `root`-kind rulesets in the
197 // account's ruleset list. The list response omits the rules, so
198 // hydrate each entrypoint via `getPhasForAccount` (the same call
199 // `read` uses) to produce the exact `read` Attributes shape.
200 const entrypoints = yield* rulesets.listRulesetsForAccount.pages({ accountId }).pipe(
201 Stream.runCollect,
202 Effect.map((chunk) =>
203 Array.from(chunk).flatMap((page) => (page.result ?? []).filter((r) => r.kind === "root")),
204 ),
205 );
206 const rows = yield* Effect.forEach(
207 entrypoints,
208 (entry) =>
209 rulesets.getPhasForAccount({ accountId, rulesetPhase: entry.phase }).pipe(
210 Effect.map((ruleset) => toAttributes(accountId, ruleset)),
211 // Removed/empty out-of-band or plan-gated phases are skipped.
212 Effect.catchTags({
213 RulesetNotFound: () => Effect.undefined,
214 Forbidden: () => Effect.undefined,
215 }),
216 ),
217 { concurrency: 10 },
218 );
219 return rows.filter(
220 (row): row is AccountEntrypointAttributes =>
221 // An entrypoint with zero rules is inert — it's what destroy
222 // leaves behind after emptying the rules we own. Don't surface
223 // it as a resource.
224 row !== undefined && row.rules.length > 0,
225 );
226 }),
227
228 read: Effect.fn(function* ({ olds, output }) {
229 const accountId = output?.accountId ?? (yield* yield* CloudflareEnvironment).accountId;
230 const phase = output?.phase ?? olds?.phase;
231 if (phase === undefined) return undefined;
232 // The entrypoint is a per-phase singleton that Cloudflare creates
233 // lazily — there is nothing to "own", so a cold read adopts freely
234 // (mirrors the zone-level `Cloudflare.Ruleset.Ruleset`).
235 return yield* rulesets.getPhasForAccount({ accountId, rulesetPhase: phase }).pipe(
236 Effect.map((ruleset) => toAttributes(accountId, ruleset)),
237 Effect.catchTag("RulesetNotFound", () => Effect.undefined),
238 );
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output }) {
242 const { accountId } = yield* yield* CloudflareEnvironment;
243 const name = news.name ?? output?.name ?? (yield* createPhysicalName({ id }));
244 // PUT is a true upsert on the phase entrypoint — one call observes
245 // nothing and converges everything, whether the entrypoint exists yet
246 // or not.
247 const ruleset = yield* rulesets.putPhasForAccount({
248 accountId,
249 rulesetPhase: news.phase,
250 name,
251 description: news.description,
252 rules: news.rules,
253 });
254 return toAttributes(accountId, ruleset);
255 }),
256
257 delete: Effect.fn(function* ({ olds, output }) {
258 // The entrypoint itself is a singleton — "delete" means emptying the
259 // rules we own. Idempotent: an entrypoint that never materialized (or
260 // was removed out-of-band) is not an error.
261 yield* rulesets
262 .putPhasForAccount({
263 accountId: output.accountId,
264 rulesetPhase: olds.phase,
265 name: output.name,
266 description: output.description,
267 rules: [],
268 })
269 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.void));
270 }),
271 });
272
273 const toAttributes = (
274 accountId: string,
275 ruleset: rulesets.GetPhasResponse | rulesets.PutPhasResponse,
276 ): AccountEntrypointAttributes => ({
277 rulesetId: ruleset.id,
278 accountId,
279 kind: ruleset.kind,
280 name: ruleset.name,
281 phase: ruleset.phase,
282 description: ruleset.description ?? undefined,
283 rules: (ruleset.rules ?? []).map(
284 ({ lastUpdated: _lastUpdated, version: _version, ...rule }) => rule,
285 ),
286 lastUpdated: ruleset.lastUpdated,
287 version: ruleset.version,
288 });