@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 304 lines 11.2 KB
Raw
1 import * as apiGateway from "@distilled.cloud/cloudflare/api-gateway";
2 import { Unowned } from "alchemy/AdoptPolicy";
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 { listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.ApiShield.UserSchema" as const;
14 type TypeId = typeof TypeId;
15
16 export interface UserSchemaProps {
17 /**
18 * Zone the schema is uploaded to.
19 *
20 * Immutable — moving a schema between zones triggers a replacement.
21 */
22 zoneId: string;
23 /**
24 * Name of the schema. If omitted, a unique name is generated from the
25 * app, stage, and logical ID.
26 *
27 * Immutable — there is no rename API, so changing the name triggers a
28 * replacement.
29 * @default ${app}-${id}-${stage}-${suffix}
30 */
31 name?: string;
32 /**
33 * The OpenAPI v3 schema source (JSON or YAML) to upload.
34 *
35 * Immutable — Cloudflare offers no API to update an uploaded schema's
36 * contents, so changing the source triggers a replacement.
37 */
38 schema: string;
39 /**
40 * Whether the schema is enabled for (legacy "classic") schema
41 * validation. Enabling is an in-place update; Cloudflare forbids
42 * disabling an enabled schema (error 20400), so turning this back off
43 * triggers a replacement.
44 * @default false
45 */
46 validationEnabled?: boolean;
47 }
48
49 export interface UserSchemaAttributes {
50 /** Cloudflare-assigned UUID of the schema. */
51 schemaId: string;
52 /** Zone the schema is uploaded to. */
53 zoneId: string;
54 /** Name of the schema. */
55 name: string;
56 /** Kind of schema. Always `openapi_v3`. */
57 kind: "openapi_v3" | (string & {});
58 /** The schema source as stored by Cloudflare. */
59 source: string;
60 /** Whether the schema is enabled for validation. */
61 validationEnabled: boolean;
62 /** ISO8601 creation timestamp. */
63 createdAt: string;
64 }
65
66 export type UserSchema = Resource<TypeId, UserSchemaProps, UserSchemaAttributes, never, Providers>;
67
68 /**
69 * A Cloudflare API Shield user schema — an OpenAPI v3 document uploaded to
70 * a zone for (legacy "classic") schema validation of API traffic.
71 *
72 * An uploaded schema's contents cannot be modified, so changing the
73 * `schema` source (or the `name`) triggers a replacement. The only in-place
74 * update is enabling validation; Cloudflare forbids disabling an enabled
75 * schema, so turning validation back off also triggers a replacement.
76 *
77 * For current zone-level schema validation (v2), prefer the
78 * `Cloudflare.SchemaValidation` resources.
79 * ### Uploading a Schema
80 * **Example:** Upload an OpenAPI v3 schema
81 * ```typescript
82 * const fs = yield* FileSystem.FileSystem;
83 * const source = yield* fs.readFileString("./openapi.json");
84 *
85 * const schema = yield* Cloudflare.ApiShield.UserSchema("PetstoreSchema", {
86 * zoneId: zone.zoneId,
87 * name: "petstore",
88 * schema: source,
89 * });
90 * // schema.schemaId is the Cloudflare-assigned UUID
91 * ```
92 *
93 * **Example:** Upload and enable validation
94 * ```typescript
95 * yield* Cloudflare.ApiShield.UserSchema("PetstoreSchema", {
96 * zoneId: zone.zoneId,
97 * schema: source,
98 * validationEnabled: true,
99 * });
100 * ```
101 *
102 * @see https://developers.cloudflare.com/api-shield/security/schema-validation/
103 *
104 * @resource
105 * @product API Shield
106 * @category Application Security
107 */
108 export const UserSchema = Resource<UserSchema>(TypeId);
109
110 /**
111 * Returns true if the given value is an UserSchema resource.
112 */
113 export const isUserSchema = (value: unknown): value is UserSchema =>
114 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
115
116 export const UserSchemaProvider = () =>
117 Provider.succeed(UserSchema, {
118 stables: ["zoneId", "name", "kind"],
119
120 diff: Effect.fn(function* ({ id, olds, news, output }) {
121 const o = olds as UserSchemaProps | undefined;
122 const n = news as UserSchemaProps;
123 if (o === undefined) return undefined;
124 // The name is part of the schema's identity — compare the resolved
125 // physical names (an omitted name resolves deterministically).
126 const oldName = output?.name ?? (yield* createSchemaName(id, o.name));
127 // Auto-generated names are engine-owned: the deployed name stays
128 // authoritative even if the generator would name this id differently
129 // today. Only an explicit user-provided name can force a replace.
130 const newName = n.name ?? oldName;
131 if (oldName !== newName) {
132 return { action: "replace" } as const;
133 }
134 // The uploaded source cannot be modified in place.
135 if (o.schema !== n.schema) {
136 return { action: "replace" } as const;
137 }
138 // Cloudflare forbids disabling validation on an enabled schema.
139 if ((o.validationEnabled ?? false) && !(n.validationEnabled ?? false)) {
140 return { action: "replace" } as const;
141 }
142 // zoneId is Input<string>; compare only once both are concrete.
143 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
144 return { action: "replace" } as const;
145 }
146 return undefined;
147 }),
148
149 read: Effect.fn(function* ({ id, output, olds }) {
150 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
151 if (zoneId === undefined) return undefined;
152
153 // Owned path: refresh by the persisted schema id.
154 if (output?.schemaId) {
155 const observed = yield* getSchema(zoneId, output.schemaId);
156 return observed ? toAttributes(observed, zoneId) : undefined;
157 }
158
159 // Cold path: recover from lost state via the deterministic name.
160 // Schemas carry no ownership markers, so an existing schema is
161 // reported as `Unowned` and adoption is gated by the adopt policy.
162 const name = yield* createSchemaName(id, olds?.name);
163 const observed = yield* findByName(zoneId, name);
164 return observed ? Unowned(toAttributes(observed, zoneId)) : undefined;
165 }),
166
167 reconcile: Effect.fn(function* ({ id, news, output }) {
168 // Inputs have been resolved to concrete strings by Plan.
169 const zoneId = news.zoneId as string;
170 const name = output?.name ?? (yield* createSchemaName(id, news.name));
171 const desiredEnabled = news.validationEnabled ?? false;
172
173 // 1. Observe — the schema id cached on `output` is a hint, not a
174 // guarantee: a missing schema falls through to ensure.
175 let observed = output?.schemaId ? yield* getSchema(zoneId, output.schemaId) : undefined;
176
177 // An adopted (or drifted) schema whose stored source no longer
178 // matches the desired one cannot be updated in place — converge by
179 // recreating it.
180 if (observed && (observed.source ?? "") !== news.schema) {
181 yield* apiGateway
182 .deleteUserSchema({ zoneId, schemaId: observed.schemaId })
183 .pipe(Effect.catchTag("SchemaNotFound", () => Effect.void));
184 observed = undefined;
185 }
186
187 // 2. Ensure — upload when missing. Names are not unique, so there is
188 // no AlreadyExists race to tolerate.
189 if (!observed) {
190 const file = yield* Effect.sync(() => new File([news.schema], `${name}.json`));
191 const created = yield* apiGateway.createUserSchema({
192 zoneId,
193 file,
194 kind: "openapi_v3",
195 name,
196 validationEnabled: desiredEnabled,
197 });
198 observed = created.schema;
199 }
200
201 // 3. Sync — enabling validation is the only in-place update (the
202 // disable direction is a replacement, handled by diff). Skip the
203 // patch entirely on a no-op.
204 if (desiredEnabled && !(observed.validationEnabled ?? false)) {
205 const patched = yield* apiGateway.patchUserSchema({
206 zoneId,
207 schemaId: observed.schemaId,
208 validationEnabled: true,
209 });
210 // The patch response omits the source — keep the observed one.
211 observed = { ...patched, source: observed.source };
212 }
213
214 return toAttributes(observed, zoneId);
215 }),
216
217 delete: Effect.fn(function* ({ output }) {
218 yield* apiGateway
219 .deleteUserSchema({
220 zoneId: output.zoneId,
221 schemaId: output.schemaId,
222 })
223 .pipe(Effect.catchTag("SchemaNotFound", () => Effect.void));
224 }),
225
226 // Schemas live inside a zone; there is no account-wide list. Fan out
227 // over every zone in the account and exhaustively paginate each zone's
228 // schemas, hydrating into the same `Attributes` shape `read` produces.
229 list: Effect.fn(function* () {
230 const { accountId } = yield* yield* CloudflareEnvironment;
231 const zones = yield* listAllZones(accountId);
232 const rows = yield* Effect.forEach(
233 zones,
234 (zone) =>
235 apiGateway.listUserSchemas.pages({ zoneId: zone.id }).pipe(
236 Stream.runCollect,
237 Effect.map((chunk) =>
238 Array.from(chunk).flatMap((page) =>
239 (page.result ?? []).map((schema) => toAttributes(schema, zone.id)),
240 ),
241 ),
242 // Zones without the API Shield entitlement reject the listing
243 // route; skip them rather than failing the whole enumeration.
244 Effect.catchTags({
245 Forbidden: () => Effect.succeed([] as UserSchemaAttributes[]),
246 // A zone purged (deleted) out-of-band mid-enumeration — it was in
247 // the zone list but no longer exists; drop it.
248 ZonePurged: () => Effect.succeed([] as UserSchemaAttributes[]),
249 }),
250 ),
251 { concurrency: 10 },
252 );
253 return rows.flat();
254 }),
255 });
256
257 type ObservedSchema = Pick<
258 apiGateway.GetUserSchemaResponse,
259 "schemaId" | "name" | "kind" | "source" | "validationEnabled" | "createdAt"
260 >;
261
262 /**
263 * Read a schema by id, mapping "gone" (`SchemaNotFound`, Cloudflare error
264 * code 19400) to `undefined`.
265 */
266 const getSchema = (zoneId: string, schemaId: string) =>
267 apiGateway.getUserSchema({ zoneId, schemaId }).pipe(
268 Effect.map((schema): ObservedSchema | undefined => schema),
269 Effect.catchTag("SchemaNotFound", () => Effect.undefined),
270 );
271
272 /**
273 * Find a schema by name. Cloudflare does not enforce name uniqueness, so
274 * the first match wins — cold recovery only ever races with itself here
275 * because generated names are deterministic per logical ID.
276 */
277 const findByName = (zoneId: string, name: string) =>
278 apiGateway.listUserSchemas.items({ zoneId }).pipe(
279 Stream.runCollect,
280 Effect.map((chunk) =>
281 Array.from(chunk).find(
282 (schema): schema is ObservedSchema & typeof schema => schema.name === name,
283 ),
284 ),
285 );
286
287 /**
288 * Resolve the schema's physical name: the explicit prop wins; otherwise a
289 * deterministic name is generated from the app, stage, and logical ID.
290 */
291 const createSchemaName = (id: string, name: string | undefined) =>
292 Effect.gen(function* () {
293 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
294 });
295
296 const toAttributes = (schema: ObservedSchema, zoneId: string): UserSchemaAttributes => ({
297 schemaId: schema.schemaId,
298 zoneId,
299 name: schema.name,
300 kind: schema.kind,
301 source: schema.source ?? "",
302 validationEnabled: schema.validationEnabled ?? false,
303 createdAt: schema.createdAt,
304 });