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

main
ts 279 lines 10.4 KB
Raw
1 import * as apiGateway from "@distilled.cloud/cloudflare/api-gateway";
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.ApiShield.Configuration" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * A session identifier ("auth ID characteristic") used by API Shield to
15 * correlate API requests to individual API consumers. Header and cookie
16 * characteristics name the header/cookie carrying the session token; `jwt`
17 * characteristics take a claim path expression in `name`.
18 */
19 export type AuthIdCharacteristic =
20 | {
21 /** Name of the header or cookie carrying the session identifier. */
22 name: string;
23 /** Where the session identifier lives on the request. */
24 type: "header" | "cookie";
25 }
26 | {
27 /** Claim path expression locating the session identifier in the JWT. */
28 name: string;
29 /** The session identifier is a claim inside a validated JWT. */
30 type: "jwt";
31 };
32
33 export interface ConfigurationProps {
34 /**
35 * Zone whose API Shield configuration is managed.
36 *
37 * Immutable — moving the configuration between zones triggers a
38 * replacement (the old zone's configuration is restored to the value it
39 * had before Alchemy managed it).
40 */
41 zoneId: string;
42 /**
43 * The session identifiers ("auth ID characteristics") API Shield uses to
44 * attribute API requests to individual consumers — used by API Discovery
45 * and volumetric abuse detection. At most 10.
46 *
47 * Mutable — written in place via PUT.
48 */
49 authIdCharacteristics: AuthIdCharacteristic[];
50 }
51
52 export interface ConfigurationAttributes {
53 /** Zone whose API Shield configuration is managed. */
54 zoneId: string;
55 /** The session identifiers currently configured on the zone. */
56 authIdCharacteristics: AuthIdCharacteristic[];
57 /**
58 * The session identifiers the zone had before Alchemy first managed the
59 * configuration. Restored on destroy, so deleting the resource puts the
60 * zone back the way it was found.
61 */
62 initialAuthIdCharacteristics: AuthIdCharacteristic[];
63 }
64
65 export type Configuration = Resource<
66 TypeId,
67 ConfigurationProps,
68 ConfigurationAttributes,
69 never,
70 Providers
71 >;
72
73 /**
74 * The API Shield configuration of a Cloudflare zone — the session
75 * identifiers ("auth ID characteristics") used to attribute API traffic to
76 * individual consumers for API Discovery and volumetric abuse detection.
77 *
78 * The configuration is a zone singleton: it always exists (defaulting to an
79 * empty list), so this resource never creates or deletes anything physical.
80 * Reconcile PUTs the configuration when the observed characteristics differ
81 * from the desired ones; destroy restores the characteristics the zone had
82 * before Alchemy first managed them.
83 *
84 * Requires an API Shield entitlement (Enterprise) — on other plans every
85 * operation fails with Cloudflare's `NotEntitled` error (code 10403).
86 * ### Configuring session identifiers
87 * **Example:** Identify sessions by an Authorization header
88 * ```typescript
89 * yield* Cloudflare.ApiShield.Configuration("SessionIds", {
90 * zoneId: zone.zoneId,
91 * authIdCharacteristics: [{ name: "authorization", type: "header" }],
92 * });
93 * ```
94 *
95 * **Example:** Identify sessions by a cookie and a JWT claim
96 * ```typescript
97 * yield* Cloudflare.ApiShield.Configuration("SessionIds", {
98 * zoneId: zone.zoneId,
99 * authIdCharacteristics: [
100 * { name: "session_id", type: "cookie" },
101 * { name: '$.cf.token_configurations[?(@.title=="api")].sub', type: "jwt" },
102 * ],
103 * });
104 * ```
105 *
106 * @see https://developers.cloudflare.com/api-shield/get-started/#session-identifiers
107 *
108 * @resource
109 * @product API Shield
110 * @category Application Security
111 */
112 export const Configuration = Resource<Configuration>(TypeId);
113
114 /**
115 * Returns true if the given value is an Configuration resource.
116 */
117 export const isConfiguration = (value: unknown): value is Configuration =>
118 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
119
120 export const ConfigurationProvider = () =>
121 Provider.succeed(Configuration, {
122 stables: ["zoneId", "initialAuthIdCharacteristics"],
123
124 list: Effect.fn(function* () {
125 const { accountId } = yield* yield* CloudflareEnvironment;
126 // No account-wide API for this zone singleton — enumerate every
127 // zone in the account and read its configuration (it always exists,
128 // defaulting to an empty list, on every entitled zone).
129 const allZones = yield* listAllZones(accountId);
130 const rows = yield* Effect.forEach(
131 allZones.map((zone) => zone.id),
132 (zoneId) =>
133 apiGateway.getConfiguration({ zoneId }).pipe(
134 Effect.map((observed) => {
135 const characteristics = toCharacteristics(observed.authIdCharacteristics);
136 return toAttributes(
137 zoneId,
138 observed.authIdCharacteristics,
139 // A freshly listed item adopts its observed value as the
140 // pre-management baseline, mirroring a cold `read`.
141 characteristics,
142 );
143 }),
144 // API Shield is entitlement-gated and zones may be partial or
145 // deleted out-of-band — skip any zone we can't read.
146 Effect.catchTag(
147 ["NotEntitled", "InvalidObjectIdentifier", "Forbidden"],
148 () => Effect.undefined,
149 ),
150 ),
151 { concurrency: 10 },
152 );
153 return rows.filter((row): row is ConfigurationAttributes => row !== undefined);
154 }),
155
156 diff: Effect.fn(function* ({ olds, news, output }) {
157 const o = olds as ConfigurationProps | undefined;
158 const n = news as ConfigurationProps;
159 // zoneId is Input<string>; compare only once both sides are concrete.
160 const oldZoneId = output?.zoneId ?? (typeof o?.zoneId === "string" ? o.zoneId : undefined);
161 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
162 return { action: "replace" } as const;
163 }
164 return undefined;
165 }),
166
167 read: Effect.fn(function* ({ output, olds }) {
168 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
169 if (zoneId === undefined) return undefined;
170 const observed = yield* apiGateway.getConfiguration({ zoneId }).pipe(
171 // Zone deleted out-of-band — the configuration is gone with it.
172 Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined),
173 );
174 if (observed === undefined) return undefined;
175 // The configuration is a singleton that always exists with a default
176 // (empty) value — there is nothing to "own", so a cold read adopts
177 // freely (never `Unowned`). The observed value at adoption time
178 // becomes the baseline restored on destroy.
179 const initial =
180 output !== undefined
181 ? output.initialAuthIdCharacteristics
182 : toCharacteristics(observed.authIdCharacteristics);
183 return toAttributes(zoneId, observed.authIdCharacteristics, initial);
184 }),
185
186 reconcile: Effect.fn(function* ({ news, output }) {
187 // Inputs have been resolved to concrete strings by Plan.
188 const zoneId = news.zoneId as string;
189
190 // 1. Observe — the configuration always exists; read its live value.
191 const observed = yield* apiGateway.getConfiguration({ zoneId });
192
193 // 2. Capture — the pre-management characteristics, restored on
194 // destroy. `output` (including an adoption read) already carries
195 // them; otherwise this is our first touch and the observed value
196 // is the zone's original.
197 const initial =
198 output !== undefined
199 ? output.initialAuthIdCharacteristics
200 : toCharacteristics(observed.authIdCharacteristics);
201
202 // 3. Sync — PUT only when the observed characteristics differ.
203 if (
204 characteristicsEqual(
205 toCharacteristics(observed.authIdCharacteristics),
206 news.authIdCharacteristics,
207 )
208 ) {
209 return toAttributes(zoneId, observed.authIdCharacteristics, initial);
210 }
211 const synced = yield* apiGateway.putConfiguration({
212 zoneId,
213 authIdCharacteristics: news.authIdCharacteristics,
214 });
215 return toAttributes(zoneId, synced.authIdCharacteristics, initial);
216 }),
217
218 delete: Effect.fn(function* ({ output }) {
219 const { zoneId, initialAuthIdCharacteristics } = output;
220 // Observe — if the zone itself is gone, so is the configuration.
221 const observed = yield* apiGateway
222 .getConfiguration({ zoneId })
223 .pipe(Effect.catchTag("InvalidObjectIdentifier", () => Effect.undefined));
224 if (observed === undefined) return;
225 // Restore the pre-management characteristics; skip the call when
226 // they already match (idempotent re-delete after a crashed run).
227 if (
228 characteristicsEqual(
229 toCharacteristics(observed.authIdCharacteristics),
230 initialAuthIdCharacteristics,
231 )
232 ) {
233 return;
234 }
235 yield* apiGateway
236 .putConfiguration({
237 zoneId,
238 authIdCharacteristics: initialAuthIdCharacteristics,
239 })
240 .pipe(Effect.catchTag("InvalidObjectIdentifier", () => Effect.void));
241 }),
242 });
243
244 /**
245 * Narrow distilled's open-union characteristics (`"header" | "cookie" |
246 * (string & {})`) to the resource's closed attribute type.
247 */
248 const toCharacteristics = (
249 characteristics: readonly { name: string; type: string }[],
250 ): AuthIdCharacteristic[] =>
251 characteristics.map(
252 (c) =>
253 ({
254 name: c.name,
255 type: c.type,
256 }) as AuthIdCharacteristic,
257 );
258
259 /**
260 * Order-insensitive equality of two characteristic lists — Cloudflare
261 * treats the configuration as a set.
262 */
263 const characteristicsEqual = (a: AuthIdCharacteristic[], b: AuthIdCharacteristic[]): boolean => {
264 if (a.length !== b.length) return false;
265 const key = (c: AuthIdCharacteristic) => `${c.type}${c.name}`;
266 const as = a.map(key).sort();
267 const bs = b.map(key).sort();
268 return as.every((k, i) => k === bs[i]);
269 };
270
271 const toAttributes = (
272 zoneId: string,
273 observed: readonly { name: string; type: string }[],
274 initial: AuthIdCharacteristic[],
275 ): ConfigurationAttributes => ({
276 zoneId,
277 authIdCharacteristics: toCharacteristics(observed),
278 initialAuthIdCharacteristics: initial,
279 });