@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 261 lines 9.51 KB
Raw
1 import * as schemaValidation from "@distilled.cloud/cloudflare/schema-validation";
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 import { listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.SchemaValidation.OperationSetting" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Per-operation mitigation action for schema validation: `log` records
18 * non-conforming requests, `block` denies them, `none` does nothing.
19 */
20 export type OperationMitigationAction = "log" | "block" | "none";
21
22 export interface OperationSettingProps {
23 /**
24 * Zone the operation belongs to.
25 *
26 * Immutable — changing the zone triggers a replacement.
27 */
28 zoneId: string;
29 /**
30 * UUID of the API Shield operation the override applies to (cross-resource
31 * reference to `Cloudflare.ApiShield.Operation`).
32 *
33 * Immutable — the operation is the override's identity, so changing it
34 * triggers a replacement.
35 */
36 operationId: string;
37 /**
38 * The mitigation action applied to this operation, superseding the zone
39 * default just for this operation: `log` records non-conforming requests,
40 * `block` denies them, `none` disables validation for the operation.
41 * Mutable in place (the PUT is a true upsert). `log` may be plan-gated
42 * (API Shield entitlement).
43 */
44 mitigationAction: OperationMitigationAction;
45 }
46
47 export interface OperationSettingAttributes {
48 /** Zone the operation belongs to. */
49 zoneId: string;
50 /** UUID of the API Shield operation the override applies to. */
51 operationId: string;
52 /** The mitigation action applied to this operation. */
53 mitigationAction: OperationMitigationAction;
54 }
55
56 export type OperationSetting = Resource<
57 TypeId,
58 OperationSettingProps,
59 OperationSettingAttributes,
60 never,
61 Providers
62 >;
63
64 /**
65 * A per-operation schema validation override
66 * (`/zones/{zone_id}/schema_validation/settings/operations/{operation_id}`)
67 * — pins a mitigation action for a single API Shield operation, superseding
68 * the zone-level default just for that operation.
69 *
70 * The override is keyed by the operation's UUID; deleting the resource
71 * clears the override so the operation falls back to the zone default.
72 * Deleting the underlying API Shield operation cascades the override away.
73 * ### Overriding an operation
74 * **Example:** Block non-conforming requests on one operation
75 * ```typescript
76 * const op = yield* Cloudflare.ApiShield.Operation("GetUser", {
77 * zoneId: zone.zoneId,
78 * method: "GET",
79 * host: "api.example.com",
80 * endpoint: "/users/{id}",
81 * });
82 *
83 * yield* Cloudflare.SchemaValidation.OperationSetting("BlockGetUser", {
84 * zoneId: zone.zoneId,
85 * operationId: op.operationId,
86 * mitigationAction: "block",
87 * });
88 * ```
89 *
90 * **Example:** Exempt an operation from validation
91 * ```typescript
92 * yield* Cloudflare.SchemaValidation.OperationSetting("SkipWebhook", {
93 * zoneId: zone.zoneId,
94 * operationId: webhookOp.operationId,
95 * mitigationAction: "none",
96 * });
97 * ```
98 *
99 * @see https://developers.cloudflare.com/api-shield/security/schema-validation/
100 *
101 * @resource
102 * @product Schema Validation
103 * @category Application Security
104 */
105 export const OperationSetting = Resource<OperationSetting>(TypeId);
106
107 /**
108 * Returns true if the given value is a OperationSetting
109 * resource.
110 */
111 export const isOperationSetting = (value: unknown): value is OperationSetting =>
112 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
113
114 export const OperationSettingProvider = () =>
115 Provider.succeed(OperationSetting, {
116 stables: ["zoneId", "operationId"],
117
118 list: Effect.fn(function* () {
119 const { accountId } = yield* yield* CloudflareEnvironment;
120 // Per-operation overrides live inside a zone with no account-wide
121 // enumeration API — fan out over every zone and list its operation
122 // settings, exhaustively paginated.
123 const zones = yield* listAllZones(accountId);
124 const rows = yield* Effect.forEach(
125 zones,
126 (zone) =>
127 schemaValidation.listSettingOperations.pages({ zoneId: zone.id }).pipe(
128 Stream.runCollect,
129 Effect.map((chunk) =>
130 Array.from(chunk).flatMap((page) =>
131 (page.result ?? [])
132 // An operation with no override reports a nullish action;
133 // skip it so the result mirrors what `read` returns.
134 .filter((op) => op.mitigationAction != null)
135 .map((op) =>
136 toAttributes(zone.id, {
137 operationId: op.operationId,
138 // Distilled widens the generated enum to an open union.
139 mitigationAction: op.mitigationAction as OperationMitigationAction,
140 }),
141 ),
142 ),
143 ),
144 // A zone with no API Shield / schema-validation entitlement
145 // rejects the route — skip it, keep the rest. (Transient
146 // code-10000 "Authentication error" blips under concurrency are
147 // retried globally by the Cloudflare retry policy, so they never
148 // reach here as a real failure.)
149 Effect.catchTag("InvalidRoute", () => Effect.succeed([])),
150 ),
151 { concurrency: 10 },
152 );
153 return rows.flat();
154 }),
155
156 diff: Effect.fn(function* ({ news, output }) {
157 if (!isResolved(news)) return undefined;
158 // The (zoneId, operationId) pair is the override's identity.
159 if (
160 output?.zoneId !== undefined &&
161 typeof news.zoneId === "string" &&
162 news.zoneId !== output.zoneId
163 ) {
164 return { action: "replace" } as const;
165 }
166 if (
167 output?.operationId !== undefined &&
168 typeof news.operationId === "string" &&
169 news.operationId !== output.operationId
170 ) {
171 return { action: "replace" } as const;
172 }
173 return undefined;
174 }),
175
176 read: Effect.fn(function* ({ output, olds }) {
177 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
178 const operationId =
179 output?.operationId ??
180 (typeof olds?.operationId === "string" ? olds.operationId : undefined);
181 if (zoneId === undefined || operationId === undefined) return undefined;
182
183 const observed = yield* getOperationSetting(zoneId, operationId);
184 if (observed === undefined) return undefined;
185 const attrs = toAttributes(zoneId, observed);
186 // An override carries no ownership marker. When we have no prior
187 // output (cold read), an existing override was set out-of-band —
188 // brand it `Unowned` so the engine gates takeover behind adoption.
189 return output !== undefined ? attrs : Unowned(attrs);
190 }),
191
192 reconcile: Effect.fn(function* ({ news }) {
193 // Inputs have been resolved to concrete strings by Plan.
194 const zoneId = news.zoneId as string;
195 const operationId = news.operationId as string;
196
197 // 1. Observe — an absent override (`OperationNotFound` on an
198 // operation with no override) simply means "not set yet".
199 const observed = yield* getOperationSetting(zoneId, operationId);
200
201 // 2/3. Ensure + Sync — the PUT is a true upsert, so a single call
202 // converges both the greenfield and the drifted case. Skip it
203 // entirely on a no-op.
204 if (observed?.mitigationAction === news.mitigationAction) {
205 return toAttributes(zoneId, observed);
206 }
207 const updated = yield* schemaValidation.putSettingOperation({
208 zoneId,
209 operationId,
210 mitigationAction: news.mitigationAction,
211 });
212 return toAttributes(zoneId, {
213 operationId: updated.operationId,
214 // Distilled widens the generated enum to an open union.
215 mitigationAction: updated.mitigationAction as OperationMitigationAction,
216 });
217 }),
218
219 delete: Effect.fn(function* ({ output }) {
220 // Idempotent — clearing an already-cleared override (or one that
221 // cascaded away with its operation) is success.
222 yield* schemaValidation
223 .deleteSettingOperation({
224 zoneId: output.zoneId,
225 operationId: output.operationId,
226 })
227 .pipe(Effect.catchTag("OperationNotFound", () => Effect.void));
228 }),
229 });
230
231 /**
232 * Read an operation override, mapping both "gone" shapes to `undefined`:
233 * `OperationNotFound` (code 10404) when the operation itself does not
234 * exist, and a 200 response without `mitigation_action` when the operation
235 * exists but carries no override.
236 */
237 const getOperationSetting = (zoneId: string, operationId: string) =>
238 schemaValidation.getSettingOperation({ zoneId, operationId }).pipe(
239 Effect.map((setting) =>
240 setting.mitigationAction == null
241 ? undefined
242 : {
243 operationId: setting.operationId,
244 // Distilled widens the generated enum to an open union.
245 mitigationAction: setting.mitigationAction as OperationMitigationAction,
246 },
247 ),
248 Effect.catchTag("OperationNotFound", () => Effect.undefined),
249 );
250
251 const toAttributes = (
252 zoneId: string,
253 setting: {
254 operationId: string;
255 mitigationAction: OperationMitigationAction;
256 },
257 ): OperationSettingAttributes => ({
258 zoneId,
259 operationId: setting.operationId,
260 mitigationAction: setting.mitigationAction,
261 });