@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 223 lines 8.62 KB
Raw
1 import * as contentScanning from "@distilled.cloud/cloudflare/content-scanning";
2 import { 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.ContentScanning.ContentScanning" as const;
12 type TypeId = typeof TypeId;
13
14 /** The wire status values Cloudflare uses for Content Scanning. */
15 type ContentScanningStatus = "enabled" | "disabled";
16
17 export interface Props {
18 /**
19 * Zone to manage WAF Content Scanning on. Stable — changing the zone
20 * triggers a replacement (the old zone's status is restored to the
21 * value it had before Alchemy managed it).
22 */
23 zoneId: string;
24 /**
25 * Whether Content Scanning is enabled on the zone. Mutable — toggled
26 * in place via the settings endpoint.
27 *
28 * Enabling requires the WAF Content Scanning Enterprise add-on;
29 * without it Cloudflare rejects the call with the typed
30 * `ContentScanningNotEntitled` error.
31 *
32 * @default true
33 */
34 enabled?: boolean;
35 }
36
37 export interface Attributes {
38 /** Zone the setting belongs to. */
39 zoneId: string;
40 /** Whether Content Scanning is currently enabled. */
41 enabled: boolean;
42 /** ISO 8601 timestamp of the last status modification, if reported. */
43 modified: string | undefined;
44 /**
45 * The status (`enabled`/`disabled`) the zone had before Alchemy first
46 * managed it. Restored on destroy, so deleting the resource puts the
47 * zone back the way it was found.
48 */
49 initialValue: ContentScanningStatus;
50 }
51
52 export type ContentScanning = Resource<TypeId, Props, Attributes, never, Providers>;
53
54 /**
55 * WAF Content Scanning (malicious uploads detection) on a Cloudflare zone —
56 * the `/zones/{zone_id}/content-upload-scan/settings` singleton toggle.
57 *
58 * Content Scanning is a zone singleton: the setting always exists (default
59 * `disabled`), so this resource never creates or deletes anything physical.
60 * Reconcile PUTs the status only when the observed value differs from the
61 * desired one; destroy restores the status the zone had before Alchemy
62 * first managed it (captured as `initialValue`).
63 *
64 * Content Scanning is an Enterprise paid add-on. Reading the status works
65 * on every plan, but enabling it on a zone without the add-on fails with
66 * the typed `ContentScanningNotEntitled` error.
67 * ### Enabling Content Scanning
68 * **Example:** Turn on malicious-upload scanning for a zone
69 * ```typescript
70 * const zone = yield* Cloudflare.Zone.Zone("Site", { name: "example.com" });
71 *
72 * yield* Cloudflare.ContentScanning.ContentScanning("UploadScanning", {
73 * zoneId: zone.zoneId,
74 * });
75 * ```
76 *
77 * **Example:** Pin Content Scanning off
78 * ```typescript
79 * yield* Cloudflare.ContentScanning.ContentScanning("UploadScanning", {
80 * zoneId: zone.zoneId,
81 * enabled: false,
82 * });
83 * ```
84 *
85 * ### Custom scan expressions
86 * **Example:** Scan a JSON-embedded file field
87 * ```typescript
88 * const scanning = yield* Cloudflare.ContentScanning.ContentScanning("UploadScanning", {
89 * zoneId: zone.zoneId,
90 * });
91 *
92 * yield* Cloudflare.ContentScanning.Expression("ScanJsonFile", {
93 * zoneId: scanning.zoneId,
94 * payload: 'lookup_json_string(http.request.body.raw, "file")',
95 * });
96 * ```
97 *
98 * @see https://developers.cloudflare.com/waf/detections/malicious-uploads/
99 *
100 * @resource
101 * @product Content Scanning
102 * @category Application Security
103 */
104 export const ContentScanning = Resource<ContentScanning>(TypeId, {
105 aliases: ["Cloudflare.ContentScanning"],
106 });
107
108 /**
109 * Returns true if the given value is a ContentScanning resource.
110 */
111 export const isContentScanning = (value: unknown): value is ContentScanning =>
112 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
113
114 export const ContentScanningProvider = () =>
115 Provider.succeed(ContentScanning, {
116 nuke: { singleton: true },
117 stables: ["zoneId", "initialValue"],
118
119 list: Effect.fn(function* () {
120 const { accountId } = yield* yield* CloudflareEnvironment;
121 // No account-wide API for this zone singleton — enumerate every
122 // zone in the account and read its status (every zone has one).
123 const allZones = yield* listAllZones(accountId);
124 const rows = yield* Effect.forEach(
125 allZones.map((zone) => zone.id),
126 (zoneId) =>
127 contentScanning.getContentScanning({ zoneId }).pipe(
128 Effect.map((observed) => toAttributes(zoneId, observed, statusOf(observed))),
129 // Plan-gated or partial zones reject the route; skip them.
130 Effect.catchTag("InvalidRoute", () => Effect.undefined),
131 ),
132 { concurrency: 10 },
133 );
134 return rows.filter((row): row is Attributes => row !== undefined);
135 }),
136
137 diff: Effect.fn(function* ({ olds, news, output }) {
138 // zoneId is Input<string>; compare only once both sides are concrete.
139 if (!isResolved(news)) return undefined;
140 const oldZoneId =
141 output?.zoneId ?? (olds !== undefined && isResolved(olds) ? olds.zoneId : undefined);
142 if (oldZoneId !== undefined && oldZoneId !== news.zoneId) {
143 return { action: "replace" } as const;
144 }
145 return undefined;
146 }),
147
148 read: Effect.fn(function* ({ output, olds }) {
149 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
150 if (!zoneId) return undefined;
151 const observed = yield* contentScanning.getContentScanning({ zoneId }).pipe(
152 // Zone deleted out-of-band — the setting is gone with it.
153 Effect.catchTag("InvalidRoute", () => Effect.undefined),
154 );
155 if (observed === undefined) return undefined;
156 // The setting is a singleton that always exists with a Cloudflare
157 // default — there is nothing to "own", so a cold read adopts freely
158 // (never `Unowned`). The observed status at adoption time becomes
159 // the `initialValue` restored on destroy.
160 const initialValue = output !== undefined ? output.initialValue : statusOf(observed);
161 return toAttributes(zoneId, observed, initialValue);
162 }),
163
164 reconcile: Effect.fn(function* ({ news, output }) {
165 // Inputs have been resolved to concrete strings by Plan.
166 const zoneId = news.zoneId as string;
167
168 // 1. Observe — the setting always exists; read its live status.
169 const observed = yield* contentScanning.getContentScanning({ zoneId });
170
171 // 2. Capture — the pre-management status, restored on destroy.
172 // `output` (including an adoption read) already carries it;
173 // otherwise this is our first touch and the observed status is
174 // the zone's original.
175 const initialValue = output !== undefined ? output.initialValue : statusOf(observed);
176
177 // 3. Sync — PUT only when the observed status differs.
178 const desired: ContentScanningStatus = news.enabled === false ? "disabled" : "enabled";
179 if (statusOf(observed) === desired) {
180 return toAttributes(zoneId, observed, initialValue);
181 }
182 const updated = yield* contentScanning.putContentScanning({
183 zoneId,
184 value: desired,
185 });
186 return toAttributes(zoneId, updated, initialValue);
187 }),
188
189 delete: Effect.fn(function* ({ output }) {
190 const { zoneId, initialValue } = output;
191 // Observe — if the zone itself is gone, so is the setting.
192 const observed = yield* contentScanning
193 .getContentScanning({ zoneId })
194 .pipe(Effect.catchTag("InvalidRoute", () => Effect.undefined));
195 if (observed === undefined) return;
196 // Restore the pre-management status; skip the call when it already
197 // matches (idempotent re-delete after a crashed run).
198 if (statusOf(observed) === initialValue) return;
199 yield* contentScanning
200 .putContentScanning({ zoneId, value: initialValue })
201 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
202 }),
203 });
204
205 /**
206 * Normalize the (nullable, open-typed) wire `value` to a concrete status.
207 * Cloudflare's default for zones that have never touched the setting is
208 * `disabled`.
209 */
210 const statusOf = (
211 setting: contentScanning.GetContentScanningResponse | contentScanning.PutContentScanningResponse,
212 ): ContentScanningStatus => (setting.value === "enabled" ? "enabled" : "disabled");
213
214 const toAttributes = (
215 zoneId: string,
216 setting: contentScanning.GetContentScanningResponse | contentScanning.PutContentScanningResponse,
217 initialValue: ContentScanningStatus,
218 ): Attributes => ({
219 zoneId,
220 enabled: statusOf(setting) === "enabled",
221 modified: setting.modified ?? undefined,
222 initialValue,
223 });