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

main
ts 341 lines 12.7 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 { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { listAllZones } from "../Zone/lookup.ts";
13
14 const TypeId = "Cloudflare.SchemaValidation.Schema" as const;
15 type TypeId = typeof TypeId;
16
17 export interface SchemaProps {
18 /**
19 * Zone the schema is uploaded to.
20 *
21 * Immutable — moving a schema between zones triggers a replacement.
22 */
23 zoneId: string;
24 /**
25 * Human-readable name for the schema. Cloudflare does not enforce
26 * uniqueness, but Alchemy uses the name as the cold-read identity, so it
27 * should be unique within the zone. If omitted, a unique name is
28 * generated from the app, stage, and logical ID.
29 *
30 * Immutable — there is no rename API, so changing the name triggers a
31 * replacement.
32 * @default ${app}-${stage}-${id}
33 */
34 name?: string;
35 /**
36 * The kind of the schema. Only OpenAPI v3 is supported.
37 *
38 * Immutable — changing the kind triggers a replacement.
39 * @default "openapi_v3"
40 */
41 kind?: "openapi_v3";
42 /**
43 * The raw OpenAPI v3 schema, as a JSON or YAML string. Cloudflare
44 * validates the document on upload and rejects invalid specs.
45 *
46 * Immutable — the uploaded source cannot be modified, so changing it
47 * triggers a replacement (a new schema is uploaded, then the old one is
48 * deleted).
49 */
50 source: string;
51 /**
52 * Whether the schema is enabled for validation.
53 *
54 * Enabling a disabled schema is an in-place update, but Cloudflare does
55 * not allow disabling an enabled schema ("delete schema instead"), so
56 * changing `true` → `false` triggers a replacement.
57 * @default true
58 */
59 validationEnabled?: boolean;
60 }
61
62 export interface SchemaAttributes {
63 /** Cloudflare-assigned UUID of the schema. */
64 schemaId: string;
65 /** Zone the schema is uploaded to. */
66 zoneId: string;
67 /** Human-readable name of the schema. */
68 name: string;
69 /** The kind of the schema. */
70 kind: "openapi_v3" | (string & {});
71 /** The raw schema source as stored by Cloudflare. */
72 source: string;
73 /** Whether the schema is enabled for validation. */
74 validationEnabled: boolean;
75 /** When the schema was uploaded. */
76 createdAt: string;
77 }
78
79 export type SchemaValidationSchema = Resource<
80 TypeId,
81 SchemaProps,
82 SchemaAttributes,
83 never,
84 Providers
85 >;
86
87 /**
88 * An OpenAPI v3 schema uploaded to a zone for API Shield schema validation
89 * (`/zones/{zone_id}/schema_validation/schemas`).
90 *
91 * Uploading a schema registers the endpoints it describes as API Shield
92 * operations (a server-side side effect — deleting the schema does not
93 * delete those operations). The schema body is immutable: changing `source`
94 * uploads a new schema and deletes the old one (replacement). Only the
95 * `validationEnabled` flag is mutable in place.
96 * ### Uploading a Schema
97 * **Example:** Upload an OpenAPI v3 schema
98 * ```typescript
99 * const schema = yield* Cloudflare.SchemaValidation.SchemaValidationSchema("ApiSchema", {
100 * zoneId: zone.zoneId,
101 * source: JSON.stringify({
102 * openapi: "3.0.0",
103 * info: { title: "my-api", version: "1.0.0" },
104 * servers: [{ url: "https://api.example.com" }],
105 * paths: {
106 * "/users": {
107 * get: {
108 * operationId: "listUsers",
109 * responses: { "200": { description: "ok" } },
110 * },
111 * },
112 * },
113 * }),
114 * });
115 * ```
116 *
117 * **Example:** Upload a schema without enabling validation
118 * ```typescript
119 * const schema = yield* Cloudflare.SchemaValidation.SchemaValidationSchema("DraftSchema", {
120 * zoneId: zone.zoneId,
121 * source: openApiDocument,
122 * validationEnabled: false,
123 * });
124 * ```
125 *
126 * ### Toggling validation
127 * **Example:** Enable a previously-disabled schema in place
128 * ```typescript
129 * // Enabling (false → true) patches the schema in place. Disabling an
130 * // enabled schema is rejected by Cloudflare, so `true` → `false` (like a
131 * // `source` change) replaces the schema instead.
132 * yield* Cloudflare.SchemaValidation.SchemaValidationSchema("DraftSchema", {
133 * zoneId: zone.zoneId,
134 * source: openApiDocument,
135 * validationEnabled: true,
136 * });
137 * ```
138 *
139 * @see https://developers.cloudflare.com/api-shield/security/schema-validation/
140 *
141 * @resource
142 * @product Schema Validation
143 * @category Application Security
144 */
145 export const SchemaValidationSchema = Resource<SchemaValidationSchema>(TypeId);
146
147 /**
148 * Returns true if the given value is a SchemaValidationSchema resource.
149 */
150 export const isSchema = (value: unknown): value is SchemaValidationSchema =>
151 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
152
153 export const SchemaProvider = () =>
154 Provider.succeed(SchemaValidationSchema, {
155 stables: ["schemaId", "zoneId", "name", "kind", "source", "createdAt"],
156
157 diff: Effect.fn(function* ({ olds, news, output }) {
158 if (!isResolved(news)) return undefined;
159 // zoneId is a path param — moving zones is a replacement.
160 if (
161 output?.zoneId !== undefined &&
162 typeof news.zoneId === "string" &&
163 news.zoneId !== output.zoneId
164 ) {
165 return { action: "replace" } as const;
166 }
167 // kind is immutable.
168 const oldKind = output?.kind ?? olds?.kind ?? "openapi_v3";
169 if ((news.kind ?? "openapi_v3") !== oldKind) {
170 return { action: "replace" } as const;
171 }
172 // There is no rename API. A generated name (news.name undefined) is
173 // deterministic and therefore never drifts.
174 const oldName = output?.name ?? olds?.name;
175 if (news.name !== undefined && oldName !== undefined && news.name !== oldName) {
176 return { action: "replace" } as const;
177 }
178 // The uploaded source is immutable. Prefer the previously-passed
179 // props as the baseline (what the user last declared) over the
180 // stored copy, in case Cloudflare ever normalizes the document.
181 const oldSource = olds?.source ?? output?.source;
182 if (oldSource !== undefined && news.source !== oldSource) {
183 return { action: "replace" } as const;
184 }
185 // Cloudflare rejects disabling an enabled schema in place
186 // ("Disabling a schema is not allowed, delete schema instead.") —
187 // converge by replacing: upload a new, disabled copy and delete the
188 // old one. Enabling (false → true) is a plain in-place update.
189 const oldEnabled = output?.validationEnabled ?? olds?.validationEnabled ?? true;
190 if (oldEnabled && news.validationEnabled === false) {
191 return { action: "replace" } as const;
192 }
193 return undefined;
194 }),
195
196 read: Effect.fn(function* ({ id, output, olds }) {
197 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
198 if (zoneId === undefined) return undefined;
199
200 if (output?.schemaId) {
201 const observed = yield* getSchema(zoneId, output.schemaId);
202 return observed ? toAttributes(zoneId, observed) : undefined;
203 }
204
205 // Cold read — recover from lost state by matching the deterministic
206 // name. Names are not unique server-side and carry no ownership
207 // marker, so brand the match `Unowned` and let the engine gate
208 // takeover behind adoption.
209 const name = yield* createSchemaName(id, olds?.name);
210 const match = yield* findByName(zoneId, name);
211 if (match === undefined) return undefined;
212 const observed = yield* getSchema(zoneId, match.schemaId);
213 return observed ? Unowned(toAttributes(zoneId, observed)) : undefined;
214 }),
215
216 reconcile: Effect.fn(function* ({ id, news, output }) {
217 // Inputs have been resolved to concrete strings by Plan.
218 const zoneId = news.zoneId as string;
219 const name = yield* createSchemaName(id, news.name);
220 const desiredEnabled = news.validationEnabled ?? true;
221
222 // 1. Observe — the cached schemaId is a hint, not a guarantee: a
223 // SchemaNotFound falls through to "missing" and we re-upload.
224 const observed = output?.schemaId ? yield* getSchema(zoneId, output.schemaId) : undefined;
225
226 // 2. Ensure — upload when missing. Names are not unique server-side,
227 // so there is no AlreadyExists race to tolerate.
228 if (observed === undefined) {
229 const created = yield* schemaValidation.createSchema({
230 zoneId,
231 kind: news.kind ?? "openapi_v3",
232 name,
233 source: news.source,
234 validationEnabled: desiredEnabled,
235 });
236 return toAttributes(zoneId, created);
237 }
238
239 // 3. Sync — `validationEnabled` is the only mutable aspect; the
240 // source/name/kind are immutable and disabling is rejected by the
241 // API, so diff replaces on those changes. Skip the API call
242 // entirely on a no-op.
243 if ((observed.validationEnabled ?? false) === desiredEnabled) {
244 return toAttributes(zoneId, observed);
245 }
246 const patched = yield* schemaValidation.patchSchema({
247 zoneId,
248 schemaId: observed.schemaId,
249 validationEnabled: desiredEnabled,
250 });
251 // The PATCH response omits the stored source (returns "") — keep the
252 // observed copy so the attributes stay faithful.
253 return toAttributes(zoneId, { ...patched, source: observed.source });
254 }),
255
256 delete: Effect.fn(function* ({ output }) {
257 // Idempotent — a schema already deleted out-of-band is success.
258 yield* schemaValidation
259 .deleteSchema({ zoneId: output.zoneId, schemaId: output.schemaId })
260 .pipe(Effect.catchTag("SchemaNotFound", () => Effect.void));
261 }),
262
263 // Zone-scoped collection: schemas live under `/zones/{zone_id}/...`, so
264 // enumerate every zone in the account and list its schemas, paginating
265 // each exhaustively. `omitSource: false` hydrates the full `read`
266 // Attributes shape. Zones whose route is invalid (deleted/partial) reject
267 // with the typed `InvalidRoute` — skip them rather than failing the whole
268 // enumeration.
269 list: Effect.fn(function* () {
270 const { accountId } = yield* yield* CloudflareEnvironment;
271 const zones = yield* listAllZones(accountId);
272 const rows = yield* Effect.forEach(
273 zones,
274 (zone) =>
275 schemaValidation.listSchemas.pages({ zoneId: zone.id, omitSource: false }).pipe(
276 Stream.runCollect,
277 Effect.map((chunk) =>
278 Array.from(chunk).flatMap((page) =>
279 (page.result ?? []).map((schema) => toAttributes(zone.id, schema)),
280 ),
281 ),
282 // Skip zones schema-validation can't enumerate: `InvalidRoute`
283 // (feature not available on the zone), `ZonePurged` (the
284 // account-wide zone listing can momentarily include a zone that
285 // has since been purged), and `Forbidden` (the scoped token /
286 // zone plan doesn't grant schema-validation access).
287 Effect.catchTag(["InvalidRoute", "ZonePurged", "Forbidden"], () =>
288 Effect.succeed<SchemaAttributes[]>([]),
289 ),
290 ),
291 { concurrency: 10 },
292 );
293 return rows.flat();
294 }),
295 });
296
297 /**
298 * Read a schema by id, mapping "gone" (`SchemaNotFound`, Cloudflare error
299 * code 19400) to `undefined`.
300 */
301 const getSchema = (zoneId: string, schemaId: string) =>
302 schemaValidation
303 .getSchema({ zoneId, schemaId, omitSource: false })
304 .pipe(Effect.catchTag("SchemaNotFound", () => Effect.undefined));
305
306 /**
307 * Find a schema by exact name (meta-data only — sources omitted). If several
308 * schemas carry the same name, pick the oldest for determinism.
309 */
310 const findByName = (zoneId: string, name: string) =>
311 schemaValidation.listSchemas.items({ zoneId, omitSource: true }).pipe(
312 Stream.filter((s) => s.name === name),
313 Stream.runCollect,
314 Effect.map((chunk) =>
315 Array.from(chunk)
316 .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
317 .at(0),
318 ),
319 );
320
321 const createSchemaName = (id: string, name: string | undefined) =>
322 Effect.gen(function* () {
323 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
324 });
325
326 const toAttributes = (
327 zoneId: string,
328 schema:
329 | schemaValidation.GetSchemaResponse
330 | schemaValidation.CreateSchemaResponse
331 | schemaValidation.PatchSchemaResponse
332 | schemaValidation.ListSchemasResponse["result"][number],
333 ): SchemaAttributes => ({
334 schemaId: schema.schemaId,
335 zoneId,
336 name: schema.name,
337 kind: schema.kind,
338 source: schema.source,
339 validationEnabled: schema.validationEnabled ?? false,
340 createdAt: schema.createdAt,
341 });