@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 439 lines 15.3 KB
Raw
1 import * as accounts from "@distilled.cloud/cloudflare/accounts";
2 import { Unowned } from "alchemy/AdoptPolicy";
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.Account.Member" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * A member's invitation status in the account. New invites start as
16 * `pending` and become `accepted` when the invitee accepts.
17 */
18 export type MemberStatus = "accepted" | "pending";
19
20 /**
21 * A scoped access policy attached to an account membership. Policies are an
22 * Enterprise alternative to legacy `roles` — they grant a permission group
23 * over a resource group with an explicit allow/deny.
24 */
25 export interface MemberPolicy {
26 /**
27 * Whether the policy allows or denies the permission groups on the
28 * resource groups.
29 */
30 access: "allow" | "deny";
31 /**
32 * Permission groups granted by this policy.
33 */
34 permissionGroups: { id: string }[];
35 /**
36 * Resource groups this policy applies to.
37 */
38 resourceGroups: { id: string }[];
39 }
40
41 export interface MemberProps {
42 /**
43 * The contact email address of the user to invite. The email is the
44 * identity of the membership — there is no API to change it, so updating
45 * this property triggers a replacement (a new invite is sent and the old
46 * membership is removed).
47 */
48 email: string;
49 /**
50 * IDs of legacy account roles to assign to the member. Mutable — role
51 * changes are applied in place via `PUT`. Role IDs can be looked up by
52 * name with {@link findAccountRoleByName}.
53 *
54 * Exactly one of `roles` or `policies` should be provided.
55 */
56 roles?: string[];
57 /**
58 * Scoped access policies to attach to the member (Enterprise feature).
59 * Mutable — policy changes are applied in place via `PUT`.
60 *
61 * Exactly one of `roles` or `policies` should be provided.
62 */
63 policies?: MemberPolicy[];
64 /**
65 * Status of the member invitation. Only `pending` can be requested when
66 * inviting; the invitee flips it to `accepted` by accepting. Changing an
67 * already-`accepted` membership back to `pending` triggers a replacement
68 * (the member is removed and re-invited).
69 * @default "pending"
70 */
71 status?: MemberStatus;
72 }
73
74 export interface MemberAttributes {
75 /**
76 * Membership identifier tag assigned by Cloudflare.
77 */
78 memberId: string;
79 /**
80 * The Cloudflare account the membership belongs to.
81 */
82 accountId: string;
83 /**
84 * The contact email address of the member.
85 */
86 email: string;
87 /**
88 * The member's invitation status (`pending` until the invite is
89 * accepted).
90 */
91 status: MemberStatus;
92 /**
93 * Roles assigned to the member, resolved to `{ id, name }` pairs.
94 */
95 roles: { id: string; name: string }[];
96 /**
97 * Scoped access policies attached to the member, or `undefined` when the
98 * membership uses legacy roles only.
99 */
100 policies: MemberPolicy[] | undefined;
101 /**
102 * The user id behind the membership, if the invitee already has a
103 * Cloudflare user.
104 */
105 userId: string | undefined;
106 }
107
108 export type Member = Resource<TypeId, MemberProps, MemberAttributes, never, Providers>;
109
110 /**
111 * A member of a Cloudflare account — an invitation for a user (by email) to
112 * join the account with a set of roles or scoped policies.
113 *
114 * The membership's identity is its `email`: there is no API to change the
115 * address, so updating `email` triggers a replacement (a fresh invite). The
116 * assigned `roles`/`policies` are mutable in place. New invites stay
117 * `pending` until the invitee accepts; deleting the resource cancels a
118 * pending invite or removes an accepted member.
119 *
120 * Safety: memberships carry no ownership markers. When there is no prior
121 * state, `read` scans the account for an existing membership with the same
122 * email and reports it as `Unowned`, so the engine refuses to take it over
123 * unless `--adopt` (or `adopt(true)`) is set.
124 * ### Inviting a member
125 * **Example:** Invite with a role looked up by name
126 * ```typescript
127 * const role = yield* Cloudflare.Account.findAccountRoleByName(
128 * accountId,
129 * "Administrator Read Only",
130 * );
131 *
132 * yield* Cloudflare.Account.Member("Auditor", {
133 * email: "auditor@example.com",
134 * roles: [role!.id],
135 * });
136 * ```
137 *
138 * ### Changing roles
139 * **Example:** Swap the member's role in place
140 * ```typescript
141 * // Same email — the membership is updated, not replaced.
142 * yield* Cloudflare.Account.Member("Auditor", {
143 * email: "auditor@example.com",
144 * roles: [adminRole.id],
145 * });
146 * ```
147 *
148 * ### Scoped policies (Enterprise)
149 * **Example:** Invite with a scoped policy instead of roles
150 * ```typescript
151 * yield* Cloudflare.Account.Member("ScopedOperator", {
152 * email: "operator@example.com",
153 * policies: [{
154 * access: "allow",
155 * permissionGroups: [{ id: permissionGroupId }],
156 * resourceGroups: [{ id: resourceGroupId }],
157 * }],
158 * });
159 * ```
160 *
161 * @see https://developers.cloudflare.com/fundamentals/manage-members/
162 *
163 * @resource
164 * @product Accounts
165 * @category Account & Identity
166 */
167 export const Member = Resource<Member>(TypeId);
168
169 /**
170 * Returns true if the given value is an Member resource.
171 */
172 export const isMember = (value: unknown): value is Member =>
173 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
174
175 export const MemberProvider = () =>
176 Provider.succeed(Member, {
177 stables: ["memberId", "accountId", "email", "userId"],
178
179 list: Effect.fn(function* () {
180 const { accountId } = yield* yield* CloudflareEnvironment;
181 // Exhaustively paginate the account membership list to collect every
182 // member id, then re-read each membership through `getMember` so each
183 // element matches the EXACT shape `read`/`reconcile` produce. A
184 // membership that vanishes between the list and the per-item read
185 // (typed `MemberNotFound`, Cloudflare code 1003) is dropped.
186 const ids = yield* accounts.listMembers.pages({ accountId }).pipe(
187 Stream.runCollect,
188 Effect.map((chunk) =>
189 Array.from(chunk).flatMap((page) =>
190 (page.result ?? []).map((member) => member.id).filter((id): id is string => id != null),
191 ),
192 ),
193 );
194 const rows = yield* Effect.forEach(
195 ids,
196 (memberId) =>
197 getMember(accountId, memberId).pipe(
198 Effect.map((member) => (member ? toAttributes(member, accountId) : undefined)),
199 ),
200 { concurrency: 10 },
201 );
202 return rows.filter((row): row is MemberAttributes => row !== undefined);
203 }),
204
205 diff: Effect.fn(function* ({ olds = {}, news }) {
206 const o = olds as Partial<MemberProps>;
207 const n = news as MemberProps;
208 // No prior props to compare against — let the engine decide.
209 if (o.email === undefined) return undefined;
210 // The email is the identity of the invite — it cannot be changed.
211 if (!sameEmail(o.email, n.email)) {
212 return { action: "replace" } as const;
213 }
214 // Per the API, demoting an accepted membership back to `pending`
215 // requires removing and re-inviting the member.
216 if (o.status === "accepted" && n.status === "pending") {
217 return { action: "replace" } as const;
218 }
219 return undefined;
220 }),
221
222 read: Effect.fn(function* ({ output, olds }) {
223 const { accountId } = yield* yield* CloudflareEnvironment;
224 const acct = output?.accountId ?? accountId;
225
226 // Owned path: refresh by our persisted membership id.
227 if (output?.memberId) {
228 const observed = yield* getMember(acct, output.memberId);
229 if (observed) return toAttributes(observed, acct);
230 }
231
232 // Adoption path: a membership for this email may already exist.
233 // Memberships carry no ownership markers, so we cannot prove we
234 // created it — brand it `Unowned` so the engine refuses to take
235 // over unless `adopt` is set.
236 const email = output?.email ?? (olds?.email as string | undefined);
237 if (email) {
238 const observed = yield* findByEmail(acct, email);
239 if (observed) return Unowned(toAttributes(observed, acct));
240 }
241 return undefined;
242 }),
243
244 reconcile: Effect.fn(function* ({ news, output }) {
245 const { accountId } = yield* yield* CloudflareEnvironment;
246 // Inputs have been resolved to concrete strings by Plan.
247 const desiredRoles = news.roles as string[] | undefined;
248
249 // 1. Observe — the membership id cached on `output` is a hint, not
250 // a guarantee: a missing member falls through to the email scan
251 // and then to create.
252 let observed = output?.memberId ? yield* getMember(accountId, output.memberId) : undefined;
253
254 // 2. Fall back to scanning the account for the email. Ownership has
255 // already been verified upstream — `read` reports existing
256 // memberships as `Unowned` and the engine gates takeover behind
257 // the adopt policy before reconcile ever runs.
258 if (!observed) {
259 observed = yield* findByEmail(accountId, news.email);
260 }
261
262 // 3. Ensure — invite when missing. A concurrent (or orphaned) invite
263 // for the same email surfaces either as a generic validation error
264 // or as the typed `AccountMemberAlreadyExists` (Cloudflare answers
265 // the duplicate with HTTP 400 "Account member already exists for
266 // email address"): in both cases converge by re-scanning for the
267 // membership that won the race and adopting it.
268 if (!observed) {
269 const created = yield* accounts
270 .createMember({
271 accountId,
272 email: news.email,
273 roles: desiredRoles,
274 policies: news.policies,
275 status: news.status,
276 })
277 .pipe(
278 Effect.catchTag(["ValidationError", "AccountMemberAlreadyExists"], (error) =>
279 findByEmail(accountId, news.email).pipe(
280 Effect.flatMap((existing) =>
281 existing ? Effect.succeed(existing) : Effect.fail(error),
282 ),
283 ),
284 ),
285 );
286 observed = created;
287 }
288
289 // 4. Sync — diff the observed roles/policies against desired; skip
290 // the PUT entirely on a no-op. `status` is not synced: only the
291 // invitee can accept, and accepted -> pending is a replacement
292 // handled by diff.
293 const memberId = observed.id ?? "";
294 const rolesDirty =
295 desiredRoles !== undefined &&
296 !sameIdSet(
297 (observed.roles ?? []).map((role) => role.id),
298 desiredRoles,
299 );
300 const policiesDirty =
301 news.policies !== undefined && !samePolicies(observed.policies ?? [], news.policies);
302 if (rolesDirty || policiesDirty) {
303 observed = yield* accounts.updateMember({
304 accountId,
305 memberId,
306 roles: desiredRoles?.map((id) => ({ id })),
307 policies: news.policies,
308 });
309 }
310
311 return toAttributes(observed, accountId);
312 }),
313
314 delete: Effect.fn(function* ({ output }) {
315 // Removing a member cancels a pending invite or revokes an accepted
316 // membership. An already-gone member surfaces as `MemberNotFound`
317 // (Cloudflare error code 1003) — that's success for delete.
318 yield* accounts
319 .deleteMember({
320 accountId: output.accountId,
321 memberId: output.memberId,
322 })
323 .pipe(Effect.catchTag("MemberNotFound", () => Effect.void));
324 }),
325 });
326
327 /**
328 * Look up a legacy account role by its exact name (e.g. `"Administrator"`,
329 * `"Administrator Read Only"`). Returns `undefined` when the account has no
330 * role with that name. Useful for resolving the `roles` prop of
331 * {@link Member} without hard-coding role IDs.
332 */
333 export const findAccountRoleByName = (accountId: string, name: string) =>
334 accounts.listRoles.items({ accountId }).pipe(
335 Stream.runCollect,
336 Effect.map((chunk) => Array.from(chunk).find((role) => role.name === name)),
337 );
338
339 // ---------------------------------------------------------------------------
340 // API helpers
341 // ---------------------------------------------------------------------------
342
343 type ObservedMember =
344 | accounts.GetMemberResponse
345 | accounts.CreateMemberResponse
346 | accounts.UpdateMemberResponse;
347
348 /**
349 * Read a membership by id, mapping "gone" (`MemberNotFound`, Cloudflare
350 * error code 1003) to `undefined`.
351 */
352 const getMember = (accountId: string, memberId: string) =>
353 accounts.getMember({ accountId, memberId }).pipe(
354 Effect.map((member): ObservedMember | undefined => member),
355 Effect.catchTag("MemberNotFound", () => Effect.undefined),
356 );
357
358 /**
359 * Find a membership by email. Emails are unique within an account, so at
360 * most one membership can match. The comparison is case-insensitive —
361 * Cloudflare normalizes addresses.
362 */
363 const findByEmail = (accountId: string, email: string) =>
364 accounts.listMembers.items({ accountId }).pipe(
365 Stream.runCollect,
366 Effect.flatMap((chunk) => {
367 const match = Array.from(chunk).find(
368 (member) => member.email != null && sameEmail(member.email, email),
369 );
370 // The list payload omits nothing we need, but re-read through
371 // `getMember` so every code path observes the same response shape.
372 return match?.id != null ? getMember(accountId, match.id) : Effect.undefined;
373 }),
374 );
375
376 const sameEmail = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
377
378 const sameIdSet = (observed: readonly string[], desired: readonly string[]) =>
379 observed.length === desired.length &&
380 [...observed].sort().join(",") === [...desired].sort().join(",");
381
382 const samePolicies = (
383 observed: NonNullable<accounts.GetMemberResponse["policies"]>,
384 desired: MemberPolicy[],
385 ) => {
386 if (observed.length !== desired.length) return false;
387 const normalize = (policies: readonly NormalizedPolicy[]) =>
388 policies
389 .map(
390 (policy) =>
391 `${policy.access}:${idList(policy.permissionGroups)}:${idList(policy.resourceGroups)}`,
392 )
393 .sort()
394 .join("|");
395 return (
396 normalize(
397 observed.map((policy) => ({
398 access: policy.access ?? "allow",
399 permissionGroups: policy.permissionGroups ?? [],
400 resourceGroups: policy.resourceGroups ?? [],
401 })),
402 ) === normalize(desired)
403 );
404 };
405
406 interface NormalizedPolicy {
407 access: string;
408 permissionGroups: readonly { id: string }[];
409 resourceGroups: readonly { id: string }[];
410 }
411
412 const idList = (groups: readonly { id: string }[]) =>
413 groups
414 .map((group) => group.id)
415 .sort()
416 .join(",");
417
418 const toAttributes = (member: ObservedMember, accountId: string): MemberAttributes => ({
419 memberId: member.id ?? "",
420 accountId,
421 email: member.email ?? "",
422 status: (member.status ?? "pending") as MemberStatus,
423 roles: (member.roles ?? []).map((role) => ({
424 id: role.id,
425 name: role.name,
426 })),
427 policies: member.policies
428 ? member.policies.map((policy) => ({
429 access: (policy.access ?? "allow") as "allow" | "deny",
430 permissionGroups: (policy.permissionGroups ?? []).map((group) => ({
431 id: group.id,
432 })),
433 resourceGroups: (policy.resourceGroups ?? []).map((group) => ({
434 id: group.id,
435 })),
436 }))
437 : undefined,
438 userId: member.user?.id ?? undefined,
439 });