@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 324 lines 10.9 KB
Raw
1 import * as iam from "@distilled.cloud/cloudflare/iam";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.Iam.ResourceGroup" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * The scope of a resource group — a scope key (e.g.
16 * `com.cloudflare.api.account.{accountId}`) plus the objects it contains
17 * (e.g. `com.cloudflare.api.account.zone.{zoneId}` or `*` for everything
18 * in the scope).
19 */
20 export interface ResourceGroupScopeInput {
21 /**
22 * The scope key, e.g. `com.cloudflare.api.account.{accountId}`.
23 */
24 key: string;
25 /**
26 * The objects within the scope this resource group spans, e.g.
27 * `com.cloudflare.api.account.zone.{zoneId}` or `*`.
28 */
29 objects: { key: string }[];
30 }
31
32 /**
33 * A fully-resolved resource group scope as observed on Cloudflare.
34 */
35 export interface ResourceGroupScope {
36 /** The scope key, e.g. `com.cloudflare.api.account.{accountId}`. */
37 key: string;
38 /** The objects within the scope this resource group spans. */
39 objects: { key: string }[];
40 }
41
42 export interface ResourceGroupProps {
43 /**
44 * Name of the resource group. If omitted, a unique name is generated
45 * from the app, stage, and logical ID.
46 * @default ${app}-${stage}-${id}
47 */
48 name?: string;
49 /**
50 * The scope of the resource group: a scope key (typically
51 * `com.cloudflare.api.account.{accountId}`) and the objects it
52 * contains (zones, or `*` for the whole account). Mutable in place.
53 */
54 scope: ResourceGroupScopeInput;
55 }
56
57 export interface ResourceGroupAttributes {
58 /** Cloudflare-assigned identifier of the resource group. */
59 resourceGroupId: string;
60 /** The Cloudflare account the resource group belongs to. */
61 accountId: string;
62 /** Name of the resource group. */
63 name: string;
64 /** The scope of the resource group as observed on Cloudflare. */
65 scope: ResourceGroupScope;
66 }
67
68 export type ResourceGroup = Resource<
69 TypeId,
70 ResourceGroupProps,
71 ResourceGroupAttributes,
72 never,
73 Providers
74 >;
75
76 /**
77 * A Cloudflare IAM resource group — a named set of account resources
78 * (zones, or the whole account) that fine-grained policies attach to.
79 *
80 * Resource groups pair with permission groups inside a user group policy:
81 * the permission group says *what* actions are allowed, the resource group
82 * says *which* resources they apply to. Both `name` and `scope` are mutable
83 * in place.
84 *
85 * Account-scoped IAM (resource groups, user groups) is an Enterprise
86 * feature.
87 * ### Creating a Resource Group
88 * **Example:** Scope a group to the whole account
89 * ```typescript
90 * const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment;
91 * const group = yield* Cloudflare.Iam.ResourceGroup("AllResources", {
92 * scope: {
93 * key: `com.cloudflare.api.account.${accountId}`,
94 * objects: [{ key: "*" }],
95 * },
96 * });
97 * ```
98 *
99 * **Example:** Scope a group to a single zone
100 * ```typescript
101 * const group = yield* Cloudflare.Iam.ResourceGroup("ZoneOnly", {
102 * name: "my-zone-resources",
103 * scope: {
104 * key: `com.cloudflare.api.account.${accountId}`,
105 * objects: [
106 * { key: `com.cloudflare.api.account.zone.${zone.zoneId}` },
107 * ],
108 * },
109 * });
110 * ```
111 *
112 * ### Using with User Groups
113 * **Example:** Attach to a user group policy
114 * ```typescript
115 * yield* Cloudflare.Iam.UserGroup("Readers", {
116 * policies: [
117 * {
118 * access: "allow",
119 * permissionGroups: [readOnlyPermissionGroupId],
120 * resourceGroups: [group.resourceGroupId],
121 * },
122 * ],
123 * });
124 * ```
125 *
126 * @see https://developers.cloudflare.com/fundamentals/manage-members/scoped-roles/
127 *
128 * @resource
129 * @product IAM
130 * @category Account & Identity
131 */
132 export const ResourceGroup = Resource<ResourceGroup>(TypeId);
133
134 /**
135 * Returns true if the given value is an ResourceGroup resource.
136 */
137 export const isResourceGroup = (value: unknown): value is ResourceGroup =>
138 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
139
140 export const ResourceGroupProvider = () =>
141 Provider.succeed(ResourceGroup, {
142 stables: ["resourceGroupId", "accountId"],
143
144 read: Effect.fn(function* ({ id, output, olds }) {
145 const { accountId } = yield* yield* CloudflareEnvironment;
146 const acct = output?.accountId ?? accountId;
147
148 if (output?.resourceGroupId) {
149 const observed = yield* getResourceGroup(acct, output.resourceGroupId);
150 if (observed) return toAttributes(observed, acct);
151 return undefined;
152 }
153
154 // Cold read — recover from lost state by matching the deterministic
155 // physical name. Names are not unique on Cloudflare's side; an exact
156 // match on our generated/explicit name is the best identity we have.
157 const name = yield* createGroupName(id, olds?.name);
158 const match = yield* findByName(acct, name);
159 return match ? toAttributes(match, acct) : undefined;
160 }),
161
162 reconcile: Effect.fn(function* ({ id, news, output }) {
163 const { accountId } = yield* yield* CloudflareEnvironment;
164 const name = yield* createGroupName(id, news.name);
165 // Inputs have been resolved to concrete strings by Plan.
166 const desiredScope = resolveScope(news.scope);
167
168 // 1. Observe — the id cached on `output` is a hint, not a guarantee:
169 // a missing group falls through to the name scan and then create.
170 let observed = output?.resourceGroupId
171 ? yield* getResourceGroup(accountId, output.resourceGroupId)
172 : undefined;
173 if (!observed) {
174 observed = yield* findByName(accountId, name);
175 }
176
177 // 2. Ensure — create when missing. Names are not unique on
178 // Cloudflare's side, so there is no AlreadyExists race to tolerate.
179 if (!observed) {
180 const created = yield* iam.createResourceGroup({
181 accountId,
182 name,
183 scope: desiredScope,
184 });
185 return toAttributes(created, accountId);
186 }
187
188 // 3. Sync — diff observed name/scope against desired; the update is
189 // a PUT, so send the full body, but skip the call on a no-op.
190 const observedScope = parseScope(observed.scope);
191 const dirty = (observed.name ?? "") !== name || !sameScope(observedScope, desiredScope);
192 if (!dirty) {
193 return toAttributes(observed, accountId);
194 }
195
196 const updated = yield* iam.updateResourceGroup({
197 accountId,
198 resourceGroupId: observed.id,
199 name,
200 scope: desiredScope,
201 });
202 return toAttributes(updated, accountId);
203 }),
204
205 delete: Effect.fn(function* ({ output }) {
206 yield* iam
207 .deleteResourceGroup({
208 accountId: output.accountId,
209 resourceGroupId: output.resourceGroupId,
210 })
211 .pipe(Effect.catchTag("ResourceGroupNotFound", () => Effect.void));
212 }),
213
214 // Account collection — the list op returns the full group record (id,
215 // name, scope) per page, so each item maps straight to the `read`
216 // Attributes shape without a per-item GET. Predefined/system resource
217 // groups are returned alongside ours, so a read-only list is often
218 // non-empty. Cloudflare paginates a single page set; exhaust it.
219 list: Effect.fn(function* () {
220 const { accountId } = yield* yield* CloudflareEnvironment;
221 return yield* iam.listResourceGroups.pages({ accountId }).pipe(
222 Stream.runCollect,
223 Effect.map((chunk) =>
224 Array.from(chunk).flatMap((page) =>
225 (page.result ?? [])
226 // Cloudflare seeds every account with predefined, non-editable
227 // system resource groups named `com.cloudflare.api.account.*`.
228 // They can't be deleted (`UnprocessableEntity: non-editable`),
229 // so exclude them from enumeration.
230 .filter((group) => !isSystemGroupName(group.name))
231 .map((group) => toAttributes(group, accountId)),
232 ),
233 ),
234 );
235 }),
236 });
237
238 type ObservedResourceGroup = {
239 id: string;
240 name?: string | null;
241 scope: iam.ResourceGroupsListResultItemScope;
242 };
243
244 /**
245 * Cloudflare's predefined, non-editable account resource groups use the
246 * reserved `com.cloudflare.api.account.*` name. They are seeded on every
247 * account and cannot be deleted, so they must be excluded from enumeration.
248 */
249 const isSystemGroupName = (name: string | null | undefined): boolean =>
250 (name ?? "").startsWith("com.cloudflare.api.");
251
252 /**
253 * Read a resource group by id, mapping "gone" (`ResourceGroupNotFound`,
254 * HTTP 404 / Cloudflare error code 404) to `undefined`.
255 */
256 const getResourceGroup = (accountId: string, resourceGroupId: string) =>
257 iam.getResourceGroup({ accountId, resourceGroupId }).pipe(
258 Effect.map((g): ObservedResourceGroup | undefined => g),
259 Effect.catchTag("ResourceGroupNotFound", () => Effect.undefined),
260 );
261
262 /**
263 * Find a resource group by exact name. Names are not unique on
264 * Cloudflare's side; pick the lexicographically-first id for determinism.
265 */
266 const findByName = (accountId: string, name: string) =>
267 iam.listResourceGroups.items({ accountId, name }).pipe(
268 Stream.runCollect,
269 Effect.map((chunk) =>
270 Array.from(chunk)
271 .filter((g): g is ObservedResourceGroup & { name: string } => g.name === name)
272 .sort((a, b) => a.id.localeCompare(b.id))
273 .at(0),
274 ),
275 );
276
277 const createGroupName = (id: string, name: string | undefined) =>
278 Effect.gen(function* () {
279 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
280 });
281
282 /** Resolve `Input<string>` scope fields to concrete strings (post-Plan). */
283 const resolveScope = (scope: ResourceGroupScopeInput): ResourceGroupScope => ({
284 key: scope.key as string,
285 objects: scope.objects.map((o) => ({ key: o.key as string })),
286 });
287
288 /**
289 * Decode the `unknown`-typed observed scope into our structured shape.
290 * Cloudflare always returns `{ key, objects: [{ key }] }` for a persisted
291 * resource group.
292 */
293 const parseScope = (scope: unknown): ResourceGroupScope => {
294 const key = Predicate.hasProperty(scope, "key") && typeof scope.key === "string" ? scope.key : "";
295 const objects =
296 Predicate.hasProperty(scope, "objects") && Array.isArray(scope.objects)
297 ? scope.objects.flatMap((o: unknown) =>
298 Predicate.hasProperty(o, "key") && typeof o.key === "string" ? [{ key: o.key }] : [],
299 )
300 : [];
301 return { key, objects };
302 };
303
304 const sameScope = (a: ResourceGroupScope, b: ResourceGroupScope) =>
305 a.key === b.key &&
306 a.objects.length === b.objects.length &&
307 a.objects
308 .map((o) => o.key)
309 .sort()
310 .join(",") ===
311 b.objects
312 .map((o) => o.key)
313 .sort()
314 .join(",");
315
316 const toAttributes = (
317 group: ObservedResourceGroup,
318 accountId: string,
319 ): ResourceGroupAttributes => ({
320 resourceGroupId: group.id,
321 accountId,
322 name: group.name ?? "",
323 scope: parseScope(group.scope),
324 });