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

main
ts 298 lines 10.8 KB
Raw
1 import * as ddos from "@distilled.cloud/cloudflare/ddos-protection";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
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
12 const TypeId = "Cloudflare.DdosProtection.TcpFlowProtectionRule" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Operating mode of a TCP Flow Protection rule: actively mitigate
17 * (`enabled`), observe only (`monitoring`), or stand down (`disabled`).
18 */
19 export type TcpFlowProtectionRuleMode = "enabled" | "disabled" | "monitoring";
20
21 /**
22 * Where a TCP Flow Protection rule applies: every prefix (`global`), one
23 * Cloudflare region (`region`), or one data center (`datacenter`).
24 */
25 export type TcpFlowProtectionRuleScope = "global" | "region" | "datacenter";
26
27 /**
28 * Sensitivity of the TCP Flow Protection thresholds.
29 */
30 export type TcpFlowProtectionRuleSensitivity = "low" | "medium" | "high";
31
32 export interface TcpFlowProtectionRuleProps {
33 /**
34 * The scope of the rule: `global`, `region`, or `datacenter`.
35 *
36 * Immutable — the API only patches mode/sensitivities, so changing the
37 * scope triggers a replacement.
38 */
39 scope: TcpFlowProtectionRuleScope;
40 /**
41 * The name of the rule, relative to `scope`: for `global` scope the name
42 * is `global`; for `region`/`datacenter` scope it is the region or data
43 * center name (e.g. `WEUR`, `SJC`).
44 *
45 * Immutable — changing the name triggers a replacement.
46 * @default "global"
47 */
48 name?: string;
49 /**
50 * Operating mode of the rule. Mutable — patched in place.
51 */
52 mode: TcpFlowProtectionRuleMode;
53 /**
54 * The burst sensitivity. Mutable — patched in place.
55 */
56 burstSensitivity: TcpFlowProtectionRuleSensitivity;
57 /**
58 * The rate sensitivity. Mutable — patched in place.
59 */
60 rateSensitivity: TcpFlowProtectionRuleSensitivity;
61 }
62
63 export interface TcpFlowProtectionRuleAttributes {
64 /** Cloudflare-assigned identifier of the TCP Flow Protection rule. */
65 ruleId: string;
66 /** The Cloudflare account the rule belongs to. */
67 accountId: string;
68 /** The scope of the rule. */
69 scope: TcpFlowProtectionRuleScope;
70 /** The name of the rule, relative to its scope. */
71 name: string;
72 /** Operating mode of the rule. */
73 mode: TcpFlowProtectionRuleMode;
74 /** The burst sensitivity. */
75 burstSensitivity: TcpFlowProtectionRuleSensitivity;
76 /** The rate sensitivity. */
77 rateSensitivity: TcpFlowProtectionRuleSensitivity;
78 /** ISO8601 creation timestamp. */
79 createdOn: string;
80 /** ISO8601 last-modified timestamp. */
81 modifiedOn: string;
82 }
83
84 export type TcpFlowProtectionRule = Resource<
85 TypeId,
86 TcpFlowProtectionRuleProps,
87 TcpFlowProtectionRuleAttributes,
88 never,
89 Providers
90 >;
91
92 /**
93 * An Advanced TCP Protection out-of-state TCP flow rule (Magic Transit).
94 *
95 * Rules tune how Cloudflare mitigates out-of-state TCP packet floods (ACK,
96 * RST, …) on Magic Transit prefixes, per scope (`global`, a region, or a
97 * data center). The rule's identity is its `scope` + `name` pair — only
98 * `mode` and the sensitivities are mutable in place.
99 *
100 * Requires the **Magic Transit / Advanced TCP Protection** entitlement; on
101 * accounts without it every API call fails with the typed
102 * `AdvancedTcpProtectionNotEntitled` error.
103 *
104 * Safety: rules carry no ownership markers. When there is no prior state,
105 * `read` scans for an existing rule with the same scope + name and reports
106 * it as `Unowned`, so the engine refuses to take it over unless `--adopt`
107 * (or `adopt(true)`) is set.
108 * ### Creating a rule
109 * **Example:** Global TCP flow protection in monitoring mode
110 * ```typescript
111 * const rule = yield* Cloudflare.DdosProtection.TcpFlowProtectionRule("GlobalFlow", {
112 * scope: "global",
113 * mode: "monitoring",
114 * burstSensitivity: "medium",
115 * rateSensitivity: "medium",
116 * });
117 * ```
118 *
119 * **Example:** Region-scoped rule
120 * ```typescript
121 * yield* Cloudflare.DdosProtection.TcpFlowProtectionRule("WeurFlow", {
122 * scope: "region",
123 * name: "WEUR",
124 * mode: "enabled",
125 * burstSensitivity: "high",
126 * rateSensitivity: "low",
127 * });
128 * ```
129 *
130 * @see https://developers.cloudflare.com/ddos-protection/advanced-ddos-systems/overview/advanced-tcp-protection/
131 *
132 * @resource
133 * @product DDoS Protection
134 * @category Network
135 */
136 export const TcpFlowProtectionRule = Resource<TcpFlowProtectionRule>(TypeId);
137
138 /**
139 * Returns true if the given value is a TcpFlowProtectionRule resource.
140 */
141 export const isTcpFlowProtectionRule = (value: unknown): value is TcpFlowProtectionRule =>
142 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
143
144 export const TcpFlowProtectionRuleProvider = () =>
145 Provider.succeed(TcpFlowProtectionRule, {
146 stables: ["ruleId", "accountId", "scope", "name", "createdOn"],
147
148 diff: Effect.fn(function* ({ olds, news }) {
149 if (olds === undefined) return undefined;
150 // `news` runs at plan time and may still carry unresolved
151 // expressions — bail out and let the engine apply default logic.
152 if (!isResolved(news)) return undefined;
153 // The API only patches mode/sensitivities — the scope + name pair is
154 // the rule's identity and cannot change.
155 if (olds.scope !== news.scope || ruleName(olds) !== ruleName(news)) {
156 return { action: "replace" } as const;
157 }
158 return undefined;
159 }),
160
161 list: Effect.fn(function* () {
162 const { accountId } = yield* yield* CloudflareEnvironment;
163 return yield* ddos.listAdvancedTcpProtectionTcpFlowProtectionRules.pages({ accountId }).pipe(
164 Stream.runCollect,
165 Effect.map((chunk) =>
166 Array.from(chunk).flatMap((page) =>
167 (page.result ?? []).map((rule) => toAttributes(rule, accountId)),
168 ),
169 ),
170 // Accounts lacking the Advanced TCP Protection entitlement (or a
171 // token without access) can't enumerate rules — there is nothing
172 // to nuke, so report an empty set rather than failing.
173 Effect.catchTags({
174 AdvancedTcpProtectionNotEntitled: () =>
175 Effect.succeed<TcpFlowProtectionRuleAttributes[]>([]),
176 Forbidden: () => Effect.succeed<TcpFlowProtectionRuleAttributes[]>([]),
177 }),
178 );
179 }),
180
181 read: Effect.fn(function* ({ output, olds }) {
182 const { accountId } = yield* yield* CloudflareEnvironment;
183 const acct = output?.accountId ?? accountId;
184
185 // Owned path: refresh by our persisted rule id.
186 if (output?.ruleId) {
187 const observed = yield* getRule(acct, output.ruleId);
188 if (observed) return toAttributes(observed, acct);
189 }
190
191 // Adoption path: a rule for this scope + name may already exist.
192 // Rules carry no ownership markers, so brand the match `Unowned` —
193 // the engine refuses to take over unless `adopt` is set.
194 const identity = output ?? olds;
195 if (identity?.scope) {
196 const observed = yield* findByScopeAndName(acct, identity.scope, ruleName(identity));
197 if (observed) return Unowned(toAttributes(observed, acct));
198 }
199 return undefined;
200 }),
201
202 reconcile: Effect.fn(function* ({ news, output }) {
203 const { accountId } = yield* yield* CloudflareEnvironment;
204 const name = ruleName(news);
205
206 // 1. Observe — the rule id cached on `output` is a hint, not a
207 // guarantee: a missing rule falls through to the scope + name
208 // scan and then to create.
209 let observed = output?.ruleId ? yield* getRule(accountId, output.ruleId) : undefined;
210
211 // 2. Fall back to scanning for the scope + name match (ownership was
212 // already gated by `read` reporting existing rules as Unowned).
213 if (!observed) {
214 observed = yield* findByScopeAndName(accountId, news.scope, name);
215 }
216
217 // 3. Ensure — create when missing.
218 if (!observed) {
219 observed = yield* ddos.createAdvancedTcpProtectionTcpFlowProtectionRule({
220 accountId,
221 scope: news.scope,
222 name,
223 mode: news.mode,
224 burstSensitivity: news.burstSensitivity,
225 rateSensitivity: news.rateSensitivity,
226 });
227 }
228
229 // 4. Sync — diff observed mutable aspects against desired; skip the
230 // patch entirely on a no-op.
231 const dirty =
232 observed.mode !== news.mode ||
233 observed.burstSensitivity !== news.burstSensitivity ||
234 observed.rateSensitivity !== news.rateSensitivity;
235 if (dirty) {
236 observed = yield* ddos.patchAdvancedTcpProtectionTcpFlowProtectionRuleItem({
237 accountId,
238 ruleId: observed.id,
239 mode: news.mode,
240 burstSensitivity: news.burstSensitivity,
241 rateSensitivity: news.rateSensitivity,
242 });
243 }
244
245 return toAttributes(observed, accountId);
246 }),
247
248 delete: Effect.fn(function* ({ output }) {
249 yield* ddos
250 .deleteAdvancedTcpProtectionTcpFlowProtectionRuleItem({
251 accountId: output.accountId,
252 ruleId: output.ruleId,
253 })
254 .pipe(Effect.catchTag("TcpFlowProtectionRuleNotFound", () => Effect.void));
255 }),
256 });
257
258 type ObservedRule = ddos.GetAdvancedTcpProtectionTcpFlowProtectionRuleItemResponse;
259
260 const ruleName = (props: { scope: string; name?: string }) => props.name ?? "global";
261
262 /**
263 * Read a rule by id, mapping "gone" (`TcpFlowProtectionRuleNotFound`,
264 * HTTP 404) to `undefined`.
265 */
266 const getRule = (accountId: string, ruleId: string) =>
267 ddos.getAdvancedTcpProtectionTcpFlowProtectionRuleItem({ accountId, ruleId }).pipe(
268 Effect.map((rule): ObservedRule | undefined => rule),
269 Effect.catchTag("TcpFlowProtectionRuleNotFound", () => Effect.undefined),
270 );
271
272 /**
273 * Find a rule by its scope + name identity. If several rules carry the same
274 * pair, pick the oldest for determinism.
275 */
276 const findByScopeAndName = (accountId: string, scope: string, name: string) =>
277 ddos.listAdvancedTcpProtectionTcpFlowProtectionRules.items({ accountId }).pipe(
278 Stream.runCollect,
279 Effect.map((chunk) =>
280 Array.from(chunk)
281 .filter((rule) => rule.scope === scope && rule.name === name)
282 .sort((a, b) => a.createdOn.localeCompare(b.createdOn))
283 .at(0),
284 ),
285 );
286
287 const toAttributes = (rule: ObservedRule, accountId: string): TcpFlowProtectionRuleAttributes => ({
288 ruleId: rule.id,
289 accountId,
290 // Distilled widens generated string enums to plain strings.
291 scope: rule.scope as TcpFlowProtectionRuleScope,
292 name: rule.name,
293 mode: rule.mode as TcpFlowProtectionRuleMode,
294 burstSensitivity: rule.burstSensitivity as TcpFlowProtectionRuleSensitivity,
295 rateSensitivity: rule.rateSensitivity as TcpFlowProtectionRuleSensitivity,
296 createdOn: rule.createdOn,
297 modifiedOn: rule.modifiedOn,
298 });