@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 246 lines 9 KB
Raw
1 import * as aiSecurity from "@distilled.cloud/cloudflare/ai-security";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
7 import type { Providers } from "../Providers.ts";
8 import { listAllZones } from "../Zone/lookup.ts";
9
10 const TypeId = "Cloudflare.AI.Security.CustomTopics" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * A custom topic category for AI Security for Apps content detection.
15 */
16 export type Topic = {
17 /**
18 * Human-readable label for the topic category.
19 */
20 label: string;
21 /**
22 * The topic description used to classify AI (LLM) traffic content.
23 */
24 topic: string;
25 };
26
27 export type CustomTopicsProps = {
28 /**
29 * Zone the custom topics belong to. Stable — changing the zone
30 * triggers a replacement (the old zone's topic list is restored to
31 * the value it had before Alchemy managed it).
32 */
33 zoneId: string;
34 /**
35 * The full list of custom topic categories. Mutable — the PUT
36 * replaces the entire list, so reconcile syncs the list as a whole.
37 */
38 topics: Topic[];
39 };
40
41 export type CustomTopicsAttributes = {
42 /** Zone the custom topics belong to. */
43 zoneId: string;
44 /** The custom topic categories currently configured on the zone. */
45 topics: Topic[];
46 /**
47 * The topic list the zone had before Alchemy first managed it.
48 * Restored on destroy, so deleting the resource puts the zone back
49 * the way it was found.
50 */
51 initialTopics: Topic[];
52 };
53
54 export type CustomTopics = Resource<
55 TypeId,
56 CustomTopicsProps,
57 CustomTopicsAttributes,
58 never,
59 Providers
60 >;
61
62 /**
63 * Custom topic categories for AI Security for Apps (Firewall for AI)
64 * content detection on a Cloudflare zone
65 * (`/zones/{zone_id}/ai-security/custom-topics`).
66 *
67 * The topic list is a zone singleton — it always exists (defaulting to
68 * empty) and is never created or deleted, only replaced wholesale via
69 * PUT. Reconcile PUTs the desired list when the observed list differs;
70 * destroy restores the list the zone had before Alchemy first managed it.
71 *
72 * Declare at most one `CustomTopics` per zone — two instances
73 * managing the same zone would fight over the single underlying list.
74 *
75 * AI Security for Apps is entitlement-gated: on accounts without the
76 * feature every call fails with the typed `AiSecurityNotEntitled` error
77 * (Cloudflare error code 13101).
78 * ### Managing custom topics
79 * **Example:** Classify traffic into two custom topics
80 * ```typescript
81 * const topics = yield* Cloudflare.AI.CustomTopics("Topics", {
82 * zoneId: zone.zoneId,
83 * topics: [
84 * { label: "billing", topic: "Questions about invoices and payments" },
85 * { label: "abuse", topic: "Harassment or abusive language" },
86 * ],
87 * });
88 * ```
89 *
90 * **Example:** Clear all custom topics
91 * ```typescript
92 * yield* Cloudflare.AI.CustomTopics("Topics", {
93 * zoneId: zone.zoneId,
94 * topics: [],
95 * });
96 * ```
97 *
98 * @see https://developers.cloudflare.com/waf/detections/firewall-for-ai/
99 *
100 * @resource
101 * @product AI Security
102 * @category Application Security
103 */
104 export const CustomTopics = Resource<CustomTopics>(TypeId, {
105 aliases: ["Cloudflare.AiSecurity.CustomTopics"],
106 });
107
108 /**
109 * Returns true if the given value is a CustomTopics resource.
110 */
111 export const isCustomTopics = (value: unknown): value is CustomTopics =>
112 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
113
114 export const CustomTopicsProvider = () =>
115 Provider.succeed(CustomTopics, {
116 stables: ["zoneId", "initialTopics"],
117
118 list: Effect.fn(function* () {
119 const { accountId } = yield* yield* CloudflareEnvironment;
120 // No account-wide API for this zone singleton — enumerate every
121 // zone in the account and read its custom-topics list (the list
122 // always exists, defaulting to empty, on every entitled zone).
123 const allZones = yield* listAllZones(accountId);
124 const rows = yield* Effect.forEach(
125 allZones.map((zone) => zone.id),
126 (zoneId) =>
127 aiSecurity.getCustomTopic({ zoneId }).pipe(
128 Effect.map((observed) => {
129 const topics = normalizeTopics(observed.topics);
130 return {
131 zoneId,
132 topics,
133 // A freshly listed item adopts its observed list as the
134 // pre-management baseline, mirroring a cold `read`.
135 initialTopics: topics,
136 };
137 }),
138 // AI Security is entitlement-gated and zones may be partial
139 // or deleted out-of-band — skip any zone we can't read.
140 Effect.catchTag(
141 ["AiSecurityNotEntitled", "ZoneNotAuthorized", "Forbidden"],
142 () => Effect.undefined,
143 ),
144 ),
145 { concurrency: 10 },
146 );
147 return rows.filter((row): row is CustomTopicsAttributes => row !== undefined);
148 }),
149
150 diff: Effect.fn(function* ({ olds = {}, news, output }) {
151 const o = olds as CustomTopicsProps;
152 const n = news as CustomTopicsProps;
153 // zoneId is Input<string>; compare only once both sides are concrete.
154 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
155 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
156 return { action: "replace" } as const;
157 }
158 return undefined;
159 }),
160
161 read: Effect.fn(function* ({ output, olds }) {
162 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
163 if (!zoneId) return undefined;
164 const observed = yield* aiSecurity.getCustomTopic({ zoneId }).pipe(
165 // Zone deleted out-of-band — the singleton is gone with it.
166 Effect.catchTag("ZoneNotAuthorized", () => Effect.undefined),
167 );
168 if (observed === undefined) return undefined;
169 // The list is a singleton that always exists (default empty) —
170 // there is nothing to "own", so a cold read adopts freely (never
171 // `Unowned`). The observed list at adoption time becomes the
172 // `initialTopics` restored on destroy.
173 const topics = normalizeTopics(observed.topics);
174 const initialTopics = output !== undefined ? output.initialTopics : topics;
175 return { zoneId, topics, initialTopics };
176 }),
177
178 reconcile: Effect.fn(function* ({ news, output }) {
179 // Inputs have been resolved to concrete strings by Plan.
180 const zoneId = news.zoneId as string;
181 const desired = news.topics;
182
183 // 1. Observe — the singleton always exists; read the live list.
184 const observed = yield* aiSecurity.getCustomTopic({ zoneId });
185 const observedTopics = normalizeTopics(observed.topics);
186
187 // 2. Capture — the pre-management list, restored on destroy.
188 // `output` (including an adoption read) already carries it;
189 // otherwise this is our first touch and the observed list is
190 // the zone's original.
191 const initialTopics = output !== undefined ? output.initialTopics : observedTopics;
192
193 // 3. Sync — PUT the full desired list only when it differs.
194 if (topicsEqual(observedTopics, desired)) {
195 return { zoneId, topics: observedTopics, initialTopics };
196 }
197 const updated = yield* aiSecurity.putCustomTopic({
198 zoneId,
199 topics: desired,
200 });
201 return {
202 zoneId,
203 topics: normalizeTopics(updated.topics ?? desired),
204 initialTopics,
205 };
206 }),
207
208 delete: Effect.fn(function* ({ output }) {
209 const { zoneId, initialTopics } = output;
210 // Observe — if the zone itself is gone, so is the list; if the
211 // entitlement was revoked, the list is unreachable and there is
212 // nothing we can restore.
213 const observed = yield* aiSecurity.getCustomTopic({ zoneId }).pipe(
214 Effect.catchTags({
215 ZoneNotAuthorized: () => Effect.undefined,
216 AiSecurityNotEntitled: () => Effect.undefined,
217 }),
218 );
219 if (observed === undefined) return;
220 // Restore the pre-management list; skip the call when it already
221 // matches (idempotent re-delete after a crashed run).
222 if (topicsEqual(normalizeTopics(observed.topics), initialTopics)) return;
223 yield* aiSecurity
224 .putCustomTopic({ zoneId, topics: initialTopics })
225 .pipe(Effect.catchTag("ZoneNotAuthorized", () => Effect.void));
226 }),
227 });
228
229 /**
230 * Normalize the API's `topics ?? null` into a concrete (mutable) array.
231 */
232 const normalizeTopics = (topics: readonly Topic[] | null | undefined): Topic[] =>
233 (topics ?? []).map((t) => ({ ...t }));
234
235 /**
236 * Order-insensitive structural equality on the `topic` key — the PUT
237 * replaces the whole list, so two lists are equal when they contain the
238 * same `{ label, topic }` pairs regardless of order.
239 */
240 const topicsEqual = (a: readonly Topic[], b: readonly Topic[]): boolean => {
241 if (a.length !== b.length) return false;
242 const key = (t: Topic) => `${t.topic}${t.label}`;
243 const as = a.map(key).sort();
244 const bs = b.map(key).sort();
245 return as.every((k, i) => k === bs[i]);
246 };