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

main
ts 202 lines 7.87 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 AiSecuritySettingsTypeId = "Cloudflare.AI.SecuritySettings" as const;
11 type AiSecuritySettingsTypeId = typeof AiSecuritySettingsTypeId;
12
13 export type SecuritySettingsProps = {
14 /**
15 * Zone the AI Security settings belong to. Stable — changing the zone
16 * triggers a replacement (the old zone's setting is restored to the
17 * value it had before Alchemy managed it).
18 */
19 zoneId: string;
20 /**
21 * Whether AI Security for Apps (Firewall for AI) is enabled on the
22 * zone. Mutable — toggled in place via PUT.
23 *
24 * @default false
25 */
26 enabled?: boolean;
27 };
28
29 export type SecuritySettingsAttributes = {
30 /** Zone the AI Security settings belong to. */
31 zoneId: string;
32 /** Whether AI Security for Apps is currently enabled on the zone. */
33 enabled: boolean;
34 /**
35 * The value `enabled` had before Alchemy first managed the setting.
36 * Restored on destroy, so deleting the resource puts the zone back
37 * the way it was found.
38 */
39 initialEnabled: boolean;
40 };
41
42 /**
43 * Returns true if the given value is a SecuritySettings resource.
44 */
45 export const isSecuritySettings = (value: unknown): value is SecuritySettings =>
46 Predicate.hasProperty(value, "Type") && value.Type === AiSecuritySettingsTypeId;
47
48 export type SecuritySettings = Resource<
49 AiSecuritySettingsTypeId,
50 SecuritySettingsProps,
51 SecuritySettingsAttributes,
52 never,
53 Providers
54 >;
55
56 /**
57 * AI Security for Apps (Firewall for AI) settings on a Cloudflare zone
58 * (`/zones/{zone_id}/ai-security/settings`).
59 *
60 * The settings object is a zone singleton — it always exists and is never
61 * created or deleted, only toggled. Reconcile PUTs the desired `enabled`
62 * value when the observed value differs; destroy restores the value the
63 * zone had before Alchemy first managed it.
64 *
65 * Declare at most one `SecuritySettings` per zone — two instances
66 * managing the same zone would fight over the single underlying setting.
67 *
68 * AI Security for Apps is entitlement-gated: on accounts without the
69 * feature every call fails with the typed `AiSecurityNotEntitled` error
70 * (Cloudflare error code 13101).
71 * ### Enabling AI Security
72 * **Example:** Enable AI Security for Apps on a zone
73 * ```typescript
74 * const securitySettings = yield* Cloudflare.AI.SecuritySettings("AiSecurity", {
75 * zoneId: zone.zoneId,
76 * enabled: true,
77 * });
78 * ```
79 *
80 * **Example:** Pin AI Security off
81 * ```typescript
82 * yield* Cloudflare.AI.SecuritySettings("AiSecurity", {
83 * zoneId: zone.zoneId,
84 * enabled: false,
85 * });
86 * ```
87 *
88 * @see https://developers.cloudflare.com/waf/detections/firewall-for-ai/
89 *
90 * @resource
91 * @product AI Security
92 * @category Application Security
93 */
94 export const SecuritySettings = Resource<SecuritySettings>(AiSecuritySettingsTypeId, {
95 aliases: ["Cloudflare.AiSecurity.Settings"],
96 });
97
98 export const SecuritySettingsProvider = () =>
99 Provider.succeed(SecuritySettings, {
100 nuke: { singleton: true },
101 stables: ["zoneId", "initialEnabled"],
102
103 list: Effect.fn(function* () {
104 const { accountId } = yield* yield* CloudflareEnvironment;
105 // No account-wide API for this zone singleton — enumerate every
106 // zone in the account and read its setting. The observed value at
107 // read time is its own `initialEnabled` (nothing is being managed).
108 const allZones = yield* listAllZones(accountId);
109 const rows = yield* Effect.forEach(
110 allZones.map((zone) => zone.id),
111 (zoneId) =>
112 aiSecurity.getAiSecurity({ zoneId }).pipe(
113 Effect.map((observed): SecuritySettingsAttributes => {
114 const enabled = observed.enabled ?? false;
115 return { zoneId, enabled, initialEnabled: enabled };
116 }),
117 // Entitlement-gated or out-of-band-deleted zones reject the
118 // route; skip them rather than failing the whole enumeration.
119 Effect.catchTags({
120 AiSecurityNotEntitled: () => Effect.undefined,
121 ZoneNotAuthorized: () => Effect.undefined,
122 }),
123 ),
124 { concurrency: 10 },
125 );
126 return rows.filter((row): row is SecuritySettingsAttributes => row !== undefined);
127 }),
128
129 diff: Effect.fn(function* ({ olds = {}, news, output }) {
130 const o = olds as SecuritySettingsProps;
131 const n = news as SecuritySettingsProps;
132 // zoneId is Input<string>; compare only once both sides are concrete.
133 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
134 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
135 return { action: "replace" } as const;
136 }
137 return undefined;
138 }),
139
140 read: Effect.fn(function* ({ output, olds }) {
141 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
142 if (!zoneId) return undefined;
143 const observed = yield* aiSecurity.getAiSecurity({ zoneId }).pipe(
144 // Zone deleted out-of-band — the singleton is gone with it.
145 Effect.catchTag("ZoneNotAuthorized", () => Effect.undefined),
146 );
147 if (observed === undefined) return undefined;
148 // The setting is a singleton that always exists with a Cloudflare
149 // default — there is nothing to "own", so a cold read adopts
150 // freely (never `Unowned`). The observed value at adoption time
151 // becomes the `initialEnabled` restored on destroy.
152 const enabled = observed.enabled ?? false;
153 const initialEnabled = output !== undefined ? output.initialEnabled : enabled;
154 return { zoneId, enabled, initialEnabled };
155 }),
156
157 reconcile: Effect.fn(function* ({ news, output }) {
158 // Inputs have been resolved to concrete strings by Plan.
159 const zoneId = news.zoneId as string;
160 const desired = news.enabled ?? false;
161
162 // 1. Observe — the singleton always exists; read its live value.
163 const observed = yield* aiSecurity.getAiSecurity({ zoneId });
164 const observedEnabled = observed.enabled ?? false;
165
166 // 2. Capture — the pre-management value, restored on destroy.
167 // `output` (including an adoption read) already carries it;
168 // otherwise this is our first touch and the observed value is
169 // the zone's original.
170 const initialEnabled = output !== undefined ? output.initialEnabled : observedEnabled;
171
172 // 3. Sync — PUT only when the observed value differs.
173 if (observedEnabled === desired) {
174 return { zoneId, enabled: observedEnabled, initialEnabled };
175 }
176 const updated = yield* aiSecurity.putAiSecurity({
177 zoneId,
178 enabled: desired,
179 });
180 return { zoneId, enabled: updated.enabled ?? desired, initialEnabled };
181 }),
182
183 delete: Effect.fn(function* ({ output }) {
184 const { zoneId, initialEnabled } = output;
185 // Observe — if the zone itself is gone, so is the setting; if the
186 // entitlement was revoked, the setting is unreachable and there is
187 // nothing we can restore.
188 const observed = yield* aiSecurity.getAiSecurity({ zoneId }).pipe(
189 Effect.catchTags({
190 ZoneNotAuthorized: () => Effect.undefined,
191 AiSecurityNotEntitled: () => Effect.undefined,
192 }),
193 );
194 if (observed === undefined) return;
195 // Restore the pre-management value; skip the call when it already
196 // matches (idempotent re-delete after a crashed run).
197 if ((observed.enabled ?? false) === initialEnabled) return;
198 yield* aiSecurity
199 .putAiSecurity({ zoneId, enabled: initialEnabled })
200 .pipe(Effect.catchTag("ZoneNotAuthorized", () => Effect.void));
201 }),
202 });