@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, 06:00 UTC

main
ts 264 lines 9.37 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.Label" as const;
14 type TypeId = typeof TypeId;
15
16 export interface LabelProps {
17 /**
18 * Zone the label is defined on.
19 *
20 * Immutable — moving a label between zones triggers a replacement.
21 */
22 zoneId: string;
23 /**
24 * Name of the label. Must be 1–24 characters. If omitted, a unique
25 * lowercase name is generated from the app, stage, and logical ID.
26 *
27 * Immutable — the name is the label's identity, so changing it triggers
28 * a replacement.
29 * @default ${app}-${id}-${stage}-${suffix} (truncated to 24 characters)
30 */
31 name?: string;
32 /**
33 * Human-readable description of the label. Mutable — patched in place.
34 * @default ""
35 */
36 description?: string;
37 }
38
39 export interface LabelAttributes {
40 /** Zone the label is defined on. */
41 zoneId: string;
42 /** Name of the label (its identity within the zone). */
43 name: string;
44 /** Human-readable description of the label. */
45 description: string;
46 /**
47 * Who owns the label: `user` for labels we manage, `managed` for
48 * Cloudflare-curated labels.
49 */
50 source: string;
51 /** ISO8601 creation timestamp. */
52 createdAt: string;
53 /** ISO8601 timestamp of the last update. */
54 lastUpdated: string;
55 }
56
57 /**
58 * Returns true if the given value is an Label resource.
59 */
60 export const isLabel = (value: unknown): value is Label =>
61 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
62
63 export type Label = Resource<TypeId, LabelProps, LabelAttributes, never, Providers>;
64
65 /**
66 * A Cloudflare API Shield user label — a zone-scoped tag that can be
67 * attached to registered API operations to organize and filter them
68 * (e.g. by team, service, or sensitivity).
69 *
70 * The label's `name` is its identity (and Cloudflare limits it to 24
71 * characters), so renaming triggers a replacement; only the `description`
72 * is mutable in place. Deleting a label detaches it from any operations
73 * server-side.
74 * ### Creating a Label
75 * **Example:** Label with a generated name
76 * ```typescript
77 * const label = yield* Cloudflare.ApiShield.Label("TeamPayments", {
78 * zoneId: zone.zoneId,
79 * description: "endpoints owned by the payments team",
80 * });
81 * ```
82 *
83 * **Example:** Label with an explicit name
84 * ```typescript
85 * yield* Cloudflare.ApiShield.Label("Pii", {
86 * zoneId: zone.zoneId,
87 * name: "pii",
88 * description: "endpoints that return personal data",
89 * });
90 * ```
91 *
92 * @see https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-labels/
93 *
94 * @resource
95 * @product API Shield
96 * @category Application Security
97 */
98 export const Label = Resource<Label>(TypeId);
99
100 export const LabelProvider = () =>
101 Provider.succeed(Label, {
102 stables: ["zoneId", "name", "source", "createdAt"],
103
104 list: Effect.fn(function* () {
105 const { accountId } = yield* yield* CloudflareEnvironment;
106 // Labels are zone-scoped — fan out over every zone and list its
107 // user labels. Only `user`-sourced labels are enumerated;
108 // `managed` labels are Cloudflare-curated and not ours to delete.
109 const zones = yield* listAllZones(accountId);
110 const rows = yield* Effect.forEach(
111 zones,
112 (zone) =>
113 apiGateway.listLabels.pages({ zoneId: zone.id, source: "user" }).pipe(
114 Stream.runCollect,
115 Effect.map((chunk) =>
116 Array.from(chunk).flatMap((page) =>
117 (page.result ?? []).map((label) => toAttributes(label, zone.id)),
118 ),
119 ),
120 // A zone may genuinely vanish mid-enumeration: a concurrent
121 // delete purged it (ZonePurged, Cloudflare code 10410), it lacks
122 // the route (InvalidRoute), or it's already gone (NotFound). Skip
123 // that zone rather than fail the whole enumeration. (Transient
124 // code-10000 "Authentication error" blips under concurrency are
125 // retried globally by the Cloudflare retry policy, so they never
126 // reach here as a real failure.)
127 Effect.catchTag(["ZonePurged", "InvalidRoute", "NotFound"], () => Effect.succeed([])),
128 ),
129 { concurrency: 10 },
130 );
131 return rows.flat();
132 }),
133
134 diff: Effect.fn(function* ({ id, olds, news, output }) {
135 const o = olds as LabelProps | undefined;
136 const n = news as LabelProps;
137 if (o === undefined) return undefined;
138 // The name is the label's identity — compare the resolved physical
139 // names (an omitted name resolves deterministically from the id).
140 const oldName = output?.name ?? (yield* createLabelName(id, o.name));
141 // Auto-generated names are engine-owned: the deployed name stays
142 // authoritative even if the generator would name this id differently
143 // today. Only an explicit user-provided name can force a replace.
144 const newName = n.name ?? oldName;
145 if (oldName !== newName) {
146 return { action: "replace" } as const;
147 }
148 // zoneId is Input<string>; compare only once both are concrete.
149 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
150 return { action: "replace" } as const;
151 }
152 return undefined;
153 }),
154
155 read: Effect.fn(function* ({ id, output, olds }) {
156 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
157 if (zoneId === undefined) return undefined;
158
159 // Owned path: refresh by the persisted name.
160 if (output?.name) {
161 const observed = yield* getLabel(zoneId, output.name);
162 return observed ? toAttributes(observed, zoneId) : undefined;
163 }
164
165 // Cold path: recover from lost state via the deterministic name.
166 // Labels carry no ownership markers, so an existing label is
167 // reported as `Unowned` and adoption is gated by the adopt policy.
168 const name = yield* createLabelName(id, olds?.name);
169 const observed = yield* getLabel(zoneId, name);
170 return observed ? Unowned(toAttributes(observed, zoneId)) : undefined;
171 }),
172
173 reconcile: Effect.fn(function* ({ id, news, output }) {
174 // Inputs have been resolved to concrete strings by Plan.
175 const zoneId = news.zoneId as string;
176 const name = output?.name ?? (yield* createLabelName(id, news.name));
177
178 // 1. Observe — read the live label; the attributes cached on
179 // `output` are a hint, not a guarantee.
180 let observed = yield* getLabel(zoneId, name);
181
182 // 2. Ensure — create when missing. A concurrent create surfaces as
183 // `LabelAlreadyExists` (Cloudflare code 70009): converge by
184 // re-reading the label that won the race.
185 if (!observed) {
186 observed = yield* apiGateway
187 .bulkCreateLabelUsers({
188 zoneId,
189 body: [{ name, description: news.description }],
190 })
191 .pipe(
192 Effect.map((response) => response.result[0]),
193 Effect.catchTag("LabelAlreadyExists", (error) =>
194 getLabel(zoneId, name).pipe(
195 Effect.flatMap((existing) =>
196 existing ? Effect.succeed(existing) : Effect.fail(error),
197 ),
198 ),
199 ),
200 );
201 }
202
203 // 3. Sync — diff the observed description against desired; skip the
204 // patch call entirely on a no-op.
205 const desired = news.description ?? "";
206 if (observed.description !== desired) {
207 observed = yield* apiGateway.patchLabelUser({
208 zoneId,
209 name,
210 description: desired,
211 });
212 }
213
214 return toAttributes(observed, zoneId);
215 }),
216
217 delete: Effect.fn(function* ({ output }) {
218 yield* apiGateway
219 .deleteLabelUser({ zoneId: output.zoneId, name: output.name })
220 .pipe(Effect.catchTag("LabelNotFound", () => Effect.void));
221 }),
222 });
223
224 type ObservedLabel = Pick<
225 apiGateway.GetLabelUserResponse,
226 "name" | "description" | "source" | "createdAt" | "lastUpdated"
227 >;
228
229 /**
230 * Read a label by name, mapping "gone" (`LabelNotFound`, Cloudflare error
231 * code 70014) to `undefined`.
232 */
233 const getLabel = (zoneId: string, name: string) =>
234 apiGateway.getLabelUser({ zoneId, name }).pipe(
235 Effect.map((label): ObservedLabel | undefined => label),
236 Effect.catchTag("LabelNotFound", () => Effect.undefined),
237 );
238
239 /**
240 * Resolve the label's physical name: the explicit prop wins; otherwise a
241 * deterministic name is generated from the app, stage, and logical ID,
242 * truncated to Cloudflare's 24-character limit.
243 */
244 const createLabelName = (id: string, name: string | undefined) =>
245 Effect.gen(function* () {
246 return (
247 name ??
248 (yield* createPhysicalName({
249 id,
250 lowercase: true,
251 maxLength: 24,
252 suffixLength: 8,
253 }))
254 );
255 });
256
257 const toAttributes = (label: ObservedLabel, zoneId: string): LabelAttributes => ({
258 zoneId,
259 name: label.name,
260 description: label.description,
261 source: label.source,
262 createdAt: label.createdAt,
263 lastUpdated: label.lastUpdated,
264 });