@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 372 lines 13.5 KB
Raw
1 import * as fraud from "@distilled.cloud/cloudflare/fraud";
2 import { deepEqual, isResolved } from "alchemy/Diff";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.Fraud.DetectionSettings" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * Criterion for classifying a login authentication outcome from the origin
16 * response. Currently only status-code matching is supported.
17 */
18 export interface AuthenticationCriteria {
19 /**
20 * How the origin response is matched. Only `"status_code"` is supported.
21 */
22 kind: "status_code";
23 /**
24 * HTTP status codes from the origin that satisfy this criterion
25 * (e.g. `[200]` for success, `[401, 403]` for failure).
26 */
27 statusCodes?: number[];
28 }
29
30 /**
31 * Configuration for classifying login authentication outcomes based on the
32 * origin response. Requires `userProfiles` to be `"enabled"`.
33 */
34 export interface AuthenticationSettings {
35 /**
36 * Origin responses that count as a successful authentication.
37 */
38 successCriteria?: AuthenticationCriteria;
39 /**
40 * Origin responses that count as a failed authentication.
41 */
42 failureCriteria?: AuthenticationCriteria;
43 }
44
45 /**
46 * The writable fraud-detection settings of a zone. Only fields you
47 * explicitly set are ever sent to Cloudflare — unset fields are left
48 * untouched on the zone.
49 */
50 export interface DetectionSettingsValues {
51 /**
52 * Whether Fraud User Profiles is enabled for the zone.
53 *
54 * Writing this field (even `"disabled"`) requires a fraud detection
55 * subscription on the zone.
56 * @default "disabled"
57 */
58 userProfiles?: "enabled" | "disabled";
59 /**
60 * Wirefilter expressions used to detect usernames in write HTTP
61 * requests (maximum of 10). The full desired list is always sent, so
62 * setting `[]` clears all expressions.
63 */
64 usernameExpressions?: string[];
65 /**
66 * Configuration for classifying login authentication outcomes based on
67 * the origin response. Requires `userProfiles` to be `"enabled"`.
68 */
69 authenticationSettings?: AuthenticationSettings;
70 }
71
72 export interface DetectionSettingsProps extends DetectionSettingsValues {
73 /**
74 * Zone whose fraud-detection settings are managed. Stable — changing
75 * the zone triggers a replacement (which re-adopts the new zone's
76 * singleton and restores the old zone's snapshot).
77 */
78 zoneId: string;
79 }
80
81 export interface DetectionSettingsAttributes extends DetectionSettingsValues {
82 /**
83 * Zone that owns this fraud-detection configuration.
84 */
85 zoneId: string;
86 /**
87 * Snapshot of the writable settings observed **before** this resource
88 * first wrote to the zone. `delete` restores these values for the
89 * fields this resource managed.
90 */
91 initialSettings: DetectionSettingsValues;
92 }
93
94 export type DetectionSettings = Resource<
95 TypeId,
96 DetectionSettingsProps,
97 DetectionSettingsAttributes,
98 never,
99 Providers
100 >;
101
102 /**
103 * The fraud-detection (Fraud User Profiles) settings of a Cloudflare zone
104 * (`/zones/{zone_id}/fraud_detection/settings`) — a zone-scoped
105 * **singleton**: every zone always has exactly one fraud-detection
106 * settings object, so there is no create or delete on the Cloudflare
107 * side. Reconciling this resource adopts the singleton and PUTs only the
108 * fields you explicitly set, leaving every other field untouched.
109 *
110 * Fraud Detection is a beta, subscription-gated product: writing
111 * `userProfiles`, non-empty `usernameExpressions`, or
112 * `authenticationSettings` fails with `FraudDetectionNotEntitled` unless
113 * the zone has a fraud detection subscription.
114 *
115 * On destroy, the resource restores the fields it managed to the values
116 * observed before its first write (the `initialSettings` snapshot).
117 * Fields that were never set by this resource are not touched.
118 * `authenticationSettings` that did not exist before the first write
119 * cannot be cleared and are left as-is.
120 * ### Fraud User Profiles
121 * **Example:** Enable user profiles with a username expression
122 * ```typescript
123 * yield* Cloudflare.Fraud.DetectionSettings("Fraud", {
124 * zoneId: zone.zoneId,
125 * userProfiles: "enabled",
126 * usernameExpressions: [
127 * 'lookup_json_string(http.request.body.raw, "username")',
128 * ],
129 * });
130 * ```
131 *
132 * ### Authentication outcome classification
133 * **Example:** Classify login success and failure by origin status code
134 * ```typescript
135 * yield* Cloudflare.Fraud.DetectionSettings("Fraud", {
136 * zoneId: zone.zoneId,
137 * userProfiles: "enabled",
138 * authenticationSettings: {
139 * successCriteria: { kind: "status_code", statusCodes: [200] },
140 * failureCriteria: { kind: "status_code", statusCodes: [401, 403] },
141 * },
142 * });
143 * ```
144 *
145 * ### Username expressions only
146 * **Example:** Clear all username expressions
147 * ```typescript
148 * yield* Cloudflare.Fraud.DetectionSettings("Fraud", {
149 * zoneId: zone.zoneId,
150 * usernameExpressions: [],
151 * });
152 * ```
153 *
154 * @see https://developers.cloudflare.com/bots/additional-configurations/fraud-detection/
155 *
156 * @resource
157 * @product Fraud Detection
158 * @category Application Security
159 */
160 export const DetectionSettings = Resource<DetectionSettings>(TypeId, {
161 aliases: ["Cloudflare.FraudDetectionSettings"],
162 });
163
164 /**
165 * Returns true if the given value is a DetectionSettings resource.
166 */
167 export const isDetectionSettings = (value: unknown): value is DetectionSettings =>
168 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
169
170 /**
171 * Every writable settings key, used to project observed cloud state and
172 * user props into the only-send-what-is-set PUT body.
173 */
174 const SETTINGS_KEYS = ["userProfiles", "usernameExpressions", "authenticationSettings"] as const;
175
176 type SettingsKey = (typeof SETTINGS_KEYS)[number];
177
178 export const DetectionSettingsProvider = () =>
179 Provider.succeed(DetectionSettings, {
180 nuke: { singleton: true },
181 stables: ["zoneId", "initialSettings"],
182
183 list: Effect.fn(function* () {
184 const { accountId } = yield* yield* CloudflareEnvironment;
185 // No account-wide API for this zone singleton — enumerate every
186 // zone in the account and read its settings (every live zone has
187 // exactly one). `getFraud` only reads, so the entitlement gate
188 // (which is on `putFraud`) never trips here.
189 const allZones = yield* listAllZones(accountId);
190 const rows = yield* Effect.forEach(
191 allZones.map((zone) => zone.id),
192 (zoneId) =>
193 observe(zoneId).pipe(
194 Effect.map((observed) =>
195 observed === undefined
196 ? undefined
197 : toAttributes(zoneId, observed, pickSettings(observed)),
198 ),
199 ),
200 { concurrency: 10 },
201 );
202 return rows.filter((row): row is DetectionSettingsAttributes => row !== undefined);
203 }),
204
205 diff: Effect.fn(function* ({ olds, news, output }) {
206 if (!isResolved(news)) return undefined;
207 // zoneId is Input<string>; compare only when both sides are concrete.
208 const oldZone =
209 output?.zoneId ??
210 (olds !== undefined && typeof olds.zoneId === "string" ? olds.zoneId : undefined);
211 if (oldZone !== undefined && oldZone !== news.zoneId) {
212 return { action: "replace" } as const;
213 }
214 }),
215
216 read: Effect.fn(function* ({ output, olds }) {
217 // The settings object is a singleton — it exists iff the zone exists.
218 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
219 if (!zoneId) return undefined;
220 const observed = yield* observe(zoneId);
221 if (!observed) return undefined;
222 // Singletons always exist with a Cloudflare default — there is
223 // nothing to "own", so a cold read adopts freely (never `Unowned`).
224 // The observed values at adoption time become the snapshot restored
225 // on destroy.
226 return toAttributes(zoneId, observed, output?.initialSettings ?? pickSettings(observed));
227 }),
228
229 reconcile: Effect.fn(function* ({ news, output }) {
230 // Inputs are resolved to concrete strings by Plan.
231 const zoneId = (output?.zoneId ?? news.zoneId) as string;
232
233 // 1. Observe — the singleton always exists for a live zone.
234 let observed: ObservedFraudSettings = yield* fraud.getFraud({ zoneId });
235
236 // 2. Snapshot — capture pre-management values once; `output` acts
237 // as the cache that keeps the very first observation sticky.
238 const initialSettings = output?.initialSettings ?? pickSettings(observed);
239
240 // 3. Sync — diff observed against the fields the user set and PUT
241 // only when something actually differs. Unset fields are never
242 // sent (omit-means-unchanged on Cloudflare's side), and set
243 // fields are always sent in full (the API treats the expression
244 // list and each criteria object as whole values).
245 const desired = pickSettings(news);
246 if (!settingsEqual(desired, pickSettings(observed))) {
247 observed = yield* fraud.putFraud({ zoneId, ...desired });
248 }
249
250 // 4. Return fresh attributes.
251 return toAttributes(zoneId, observed, initialSettings);
252 }),
253
254 delete: Effect.fn(function* ({ output, olds }) {
255 // Singleton — nothing to delete on the Cloudflare side. Restore the
256 // fields this resource managed (i.e. the props that were set) to
257 // their pre-management snapshot values. Fields whose snapshot value
258 // is absent (e.g. authenticationSettings that never existed before
259 // our first write) cannot be restored and are left as-is.
260 const observed = yield* observe(output.zoneId);
261 if (!observed) return; // zone is gone — nothing to restore
262 const managed = pickSettings(olds ?? {});
263 const current = pickSettings(observed);
264 const restore: DetectionSettingsValues = {};
265 for (const key of SETTINGS_KEYS) {
266 const snapshot = output.initialSettings?.[key];
267 if (
268 managed[key] !== undefined &&
269 snapshot !== undefined &&
270 !deepEqual(current[key], snapshot)
271 ) {
272 (restore as Record<SettingsKey, unknown>)[key] = snapshot;
273 }
274 }
275 if (Object.keys(restore).length > 0) {
276 yield* fraud.putFraud({ zoneId: output.zoneId, ...restore }).pipe(
277 // The zone lost its fraud detection subscription out-of-band —
278 // the snapshot cannot be restored, but delete stays idempotent.
279 Effect.catchTag("FraudDetectionNotEntitled", () => Effect.void),
280 );
281 }
282 }),
283 });
284
285 /**
286 * The distilled responses type nested fields as nullable; widen to a flat
287 * bag so observation code can normalize without per-field narrowing.
288 */
289 type ObservedFraudSettings = fraud.GetFraudResponse | fraud.PutFraudResponse;
290
291 /**
292 * Read the zone's fraud-detection settings, mapping a dead zone
293 * (`InvalidRoute`, Cloudflare code 7003) to `undefined`.
294 */
295 const observe = (zoneId: string) =>
296 fraud.getFraud({ zoneId }).pipe(Effect.catchTag("InvalidRoute", () => Effect.undefined));
297
298 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
299
300 const normalizeCriteria = (
301 criteria: { kind: "status_code"; statusCodes?: readonly number[] | null } | null | undefined,
302 ): AuthenticationCriteria | undefined => {
303 if (criteria == null) return undefined;
304 const statusCodes = undef(criteria.statusCodes);
305 return {
306 kind: criteria.kind,
307 ...(statusCodes !== undefined ? { statusCodes: [...statusCodes] } : {}),
308 };
309 };
310
311 const normalizeAuthenticationSettings = (
312 settings: ObservedFraudSettings["authenticationSettings"],
313 ): AuthenticationSettings | undefined => {
314 if (settings == null) return undefined;
315 const successCriteria = normalizeCriteria(settings.successCriteria);
316 const failureCriteria = normalizeCriteria(settings.failureCriteria);
317 if (successCriteria === undefined && failureCriteria === undefined) {
318 return undefined;
319 }
320 return {
321 ...(successCriteria !== undefined ? { successCriteria } : {}),
322 ...(failureCriteria !== undefined ? { failureCriteria } : {}),
323 };
324 };
325
326 /**
327 * Project any source (observed response, props, attrs) onto the writable
328 * settings keys, dropping `null`/`undefined` values and normalizing
329 * nested nullable fields.
330 */
331 const pickSettings = (
332 source: ObservedFraudSettings | DetectionSettingsValues,
333 ): DetectionSettingsValues => {
334 const out: DetectionSettingsValues = {};
335 const userProfiles = undef(source.userProfiles);
336 if (userProfiles === "enabled") {
337 out.userProfiles = "enabled";
338 } else if (userProfiles === "disabled") {
339 out.userProfiles = "disabled";
340 }
341 const usernameExpressions = undef(source.usernameExpressions);
342 if (usernameExpressions !== undefined) {
343 out.usernameExpressions = [...usernameExpressions];
344 }
345 const authenticationSettings = normalizeAuthenticationSettings(source.authenticationSettings);
346 if (authenticationSettings !== undefined) {
347 out.authenticationSettings = authenticationSettings;
348 }
349 return out;
350 };
351
352 /**
353 * True when every field set in `desired` matches `observed`. Unset
354 * desired fields are ignored — they are dashboard-managed.
355 */
356 const settingsEqual = (
357 desired: DetectionSettingsValues,
358 observed: DetectionSettingsValues,
359 ): boolean =>
360 SETTINGS_KEYS.every(
361 (key) => desired[key] === undefined || deepEqual(desired[key], observed[key]),
362 );
363
364 const toAttributes = (
365 zoneId: string,
366 observed: ObservedFraudSettings,
367 initialSettings: DetectionSettingsValues,
368 ): DetectionSettingsAttributes => ({
369 zoneId,
370 ...pickSettings(observed),
371 initialSettings,
372 });