The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as iam from "@distilled.cloud/cloudflare/iam"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 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 Schedule from "effect/Schedule"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | |
| 12 | const TypeId = "Cloudflare.Iam.UserGroupMembership" as const; |
| 13 | type TypeId = typeof TypeId; |
| 14 | |
| 15 | export interface UserGroupMembershipProps { |
| 16 | /** |
| 17 | * ID of the user group to add the member to — e.g. |
| 18 | * `userGroup.userGroupId`. Immutable — changing it triggers a |
| 19 | * replacement. |
| 20 | */ |
| 21 | userGroup: string; |
| 22 | /** |
| 23 | * Account member ID to add to the user group (the membership id from |
| 24 | * the account's member roster, not the user id). Immutable — changing |
| 25 | * it triggers a replacement. |
| 26 | */ |
| 27 | memberId: string; |
| 28 | } |
| 29 | |
| 30 | export interface UserGroupMembershipAttributes { |
| 31 | /** ID of the user group the member belongs to. */ |
| 32 | userGroupId: string; |
| 33 | /** Account member ID of the member. */ |
| 34 | memberId: string; |
| 35 | /** The Cloudflare account the user group belongs to. */ |
| 36 | accountId: string; |
| 37 | /** The contact email address of the member, if known. */ |
| 38 | email: string | undefined; |
| 39 | /** The member's status in the account (`accepted` or `pending`). */ |
| 40 | status: string | undefined; |
| 41 | } |
| 42 | |
| 43 | export type UserGroupMembership = Resource< |
| 44 | TypeId, |
| 45 | UserGroupMembershipProps, |
| 46 | UserGroupMembershipAttributes, |
| 47 | never, |
| 48 | Providers |
| 49 | >; |
| 50 | |
| 51 | /** |
| 52 | * Membership of a single account member in a Cloudflare IAM user group. |
| 53 | * |
| 54 | * This is an existence-only resource: it has no mutable aspects beyond its |
| 55 | * identity (user group + member), so changing either property triggers a |
| 56 | * replacement. Cloudflare's member-add API is idempotent — adding a member |
| 57 | * who is already in the group succeeds — so reconcile is a simple |
| 58 | * observe-then-ensure flow. |
| 59 | * |
| 60 | * Account-scoped IAM (user groups and their members) is an Enterprise |
| 61 | * feature. |
| 62 | * ### Adding a Member |
| 63 | * **Example:** Add an account member to a user group |
| 64 | * ```typescript |
| 65 | * const group = yield* Cloudflare.Iam.UserGroup("Operators", {}); |
| 66 | * |
| 67 | * yield* Cloudflare.Iam.UserGroupMembership("SamInOperators", { |
| 68 | * userGroup: group.userGroupId, |
| 69 | * memberId: "b67b4c279ea0177a0ddff0a2ef64b11b", |
| 70 | * }); |
| 71 | * ``` |
| 72 | * |
| 73 | * @see https://developers.cloudflare.com/fundamentals/manage-members/user-groups/ |
| 74 | * |
| 75 | * @resource |
| 76 | * @product IAM |
| 77 | * @category Account & Identity |
| 78 | */ |
| 79 | export const UserGroupMembership = Resource<UserGroupMembership>(TypeId); |
| 80 | |
| 81 | /** |
| 82 | * Returns true if the given value is an UserGroupMembership resource. |
| 83 | */ |
| 84 | export const isUserGroupMembership = (value: unknown): value is UserGroupMembership => |
| 85 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 86 | |
| 87 | export const UserGroupMembershipProvider = () => |
| 88 | Provider.succeed(UserGroupMembership, { |
| 89 | stables: ["userGroupId", "memberId", "accountId"], |
| 90 | |
| 91 | // Parent fan-out: memberships are keyed by (user group, member) and |
| 92 | // there is no account-wide membership enumeration API. Enumerate every |
| 93 | // user group in the account (account-scoped), then list each group's |
| 94 | // members with bounded concurrency, paginating both levels exhaustively. |
| 95 | list: Effect.fn(function* () { |
| 96 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 97 | const groups = yield* iam.listUserGroups.pages({ accountId }).pipe( |
| 98 | Stream.runCollect, |
| 99 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.result ?? [])), |
| 100 | ); |
| 101 | const rows = yield* Effect.forEach( |
| 102 | groups, |
| 103 | (group) => |
| 104 | iam.listUserGroupMembers.pages({ accountId, userGroupId: group.id }).pipe( |
| 105 | Stream.runCollect, |
| 106 | Effect.map((chunk) => |
| 107 | Array.from(chunk).flatMap((page) => |
| 108 | (page.result ?? []).map((member): UserGroupMembershipAttributes => |
| 109 | toAttributes(member, group.id, accountId), |
| 110 | ), |
| 111 | ), |
| 112 | ), |
| 113 | // Group removed out-of-band between enumeration and member |
| 114 | // listing — skip it. |
| 115 | Effect.catchTags({ |
| 116 | UserGroupNotFound: () => Effect.succeed([] as UserGroupMembershipAttributes[]), |
| 117 | // A group whose policy Cloudflare can't validate rejects the |
| 118 | // member listing with a 400 ("Policy validation failed"). It's |
| 119 | // not ours to enumerate — contribute nothing rather than failing |
| 120 | // the whole account-wide listing. |
| 121 | PolicyValidationFailed: () => Effect.succeed([] as UserGroupMembershipAttributes[]), |
| 122 | }), |
| 123 | ), |
| 124 | { concurrency: 10 }, |
| 125 | ); |
| 126 | return rows.flat(); |
| 127 | }), |
| 128 | |
| 129 | diff: Effect.fn(function* ({ olds, news }) { |
| 130 | if (!isResolved(news)) return undefined; |
| 131 | // Identity change — both props are the resource's identity, so any |
| 132 | // change is a replacement. Compare only once both sides are concrete. |
| 133 | if (typeof olds?.userGroup === "string" && olds.userGroup !== news.userGroup) { |
| 134 | return { action: "replace" } as const; |
| 135 | } |
| 136 | if (typeof olds?.memberId === "string" && olds.memberId !== news.memberId) { |
| 137 | return { action: "replace" } as const; |
| 138 | } |
| 139 | return undefined; |
| 140 | }), |
| 141 | |
| 142 | read: Effect.fn(function* ({ output, olds }) { |
| 143 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 144 | const acct = output?.accountId ?? accountId; |
| 145 | // Cold read falls back to the previous props — the identity is fully |
| 146 | // user-specified, so the (group, member) pair is the lookup key. The |
| 147 | // props may still hold an unresolved `Output` (e.g. a reference to a |
| 148 | // sibling group's id when state was persisted before reconcile), so |
| 149 | // only use them as a lookup key once they're concrete strings — |
| 150 | // otherwise there is nothing to read. |
| 151 | const oldGroup = typeof olds?.userGroup === "string" ? olds.userGroup : undefined; |
| 152 | const oldMember = typeof olds?.memberId === "string" ? olds.memberId : undefined; |
| 153 | const userGroupId = output?.userGroupId ?? oldGroup; |
| 154 | const memberId = output?.memberId ?? oldMember; |
| 155 | if (userGroupId === undefined || memberId === undefined) { |
| 156 | return undefined; |
| 157 | } |
| 158 | const observed = yield* getMembership(acct, userGroupId, memberId); |
| 159 | return observed ? toAttributes(observed, userGroupId, acct) : undefined; |
| 160 | }), |
| 161 | |
| 162 | reconcile: Effect.fn(function* ({ news }) { |
| 163 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 164 | // Inputs have been resolved to concrete strings by Plan. |
| 165 | const userGroupId = news.userGroup as string; |
| 166 | const memberId = news.memberId as string; |
| 167 | |
| 168 | // A user group created earlier in the same deploy is eventually |
| 169 | // consistent: its `/members` sub-resource API briefly answers GET and |
| 170 | // POST with `UserGroupNotFound` (404) until the new group propagates |
| 171 | // across Cloudflare's edge. Ride out that window with a bounded retry |
| 172 | // — `UserGroupNotFound` here means "the group isn't visible yet", not |
| 173 | // "the group is gone" (we are mid-create of its membership). |
| 174 | const ensure = Effect.gen(function* () { |
| 175 | // Observe — membership is existence-only; if it's already there we |
| 176 | // are done. A missing *member* (`UserGroupMemberNotFound`) is the |
| 177 | // expected greenfield state; a missing *group* (`UserGroupNotFound`) |
| 178 | // bubbles to the retry below. |
| 179 | const observed = yield* iam.getUserGroupMember({ accountId, userGroupId, memberId }).pipe( |
| 180 | Effect.map((m): ObservedMember | undefined => m), |
| 181 | Effect.catchTag("UserGroupMemberNotFound", () => Effect.undefined), |
| 182 | ); |
| 183 | if (observed) { |
| 184 | return toAttributes(observed, userGroupId, accountId); |
| 185 | } |
| 186 | |
| 187 | // Ensure — add the member. The batch POST is idempotent for members |
| 188 | // already in the group, so a concurrent add is not an error. |
| 189 | const created = yield* iam.createUserGroupMember({ |
| 190 | accountId, |
| 191 | userGroupId, |
| 192 | members: [{ id: memberId }], |
| 193 | }); |
| 194 | const member = created.result.find((m) => m.id === memberId); |
| 195 | if (member) { |
| 196 | return toAttributes(member, userGroupId, accountId); |
| 197 | } |
| 198 | // The POST response echoes the full member set; fall back to a read |
| 199 | // for the member we just added. |
| 200 | const reread = yield* getMembership(accountId, userGroupId, memberId); |
| 201 | return toAttributes(reread ?? { id: memberId }, userGroupId, accountId); |
| 202 | }); |
| 203 | |
| 204 | return yield* ensure.pipe( |
| 205 | Effect.retry({ |
| 206 | while: (e) => e._tag === "UserGroupNotFound", |
| 207 | schedule: Schedule.exponential("500 millis"), |
| 208 | times: 8, |
| 209 | }), |
| 210 | ); |
| 211 | }), |
| 212 | |
| 213 | delete: Effect.fn(function* ({ output }) { |
| 214 | yield* iam |
| 215 | .deleteUserGroupMember({ |
| 216 | accountId: output.accountId, |
| 217 | userGroupId: output.userGroupId, |
| 218 | memberId: output.memberId, |
| 219 | }) |
| 220 | .pipe( |
| 221 | // Already gone — the member (404 in group, or no longer a valid |
| 222 | // account member at all → InvalidMember) or the whole user group |
| 223 | // (404) has been removed out-of-band. |
| 224 | Effect.catchTag( |
| 225 | ["UserGroupMemberNotFound", "UserGroupNotFound", "InvalidMember"], |
| 226 | () => Effect.void, |
| 227 | ), |
| 228 | ); |
| 229 | }), |
| 230 | }); |
| 231 | |
| 232 | type ObservedMember = { |
| 233 | id: string; |
| 234 | email?: string | null; |
| 235 | status?: string | null; |
| 236 | }; |
| 237 | |
| 238 | /** |
| 239 | * Read a membership, mapping "gone" — the member not being in the group |
| 240 | * (`UserGroupMemberNotFound`) or the group itself missing |
| 241 | * (`UserGroupNotFound`) — to `undefined`. |
| 242 | */ |
| 243 | const getMembership = (accountId: string, userGroupId: string, memberId: string) => |
| 244 | iam.getUserGroupMember({ accountId, userGroupId, memberId }).pipe( |
| 245 | Effect.map((m): ObservedMember | undefined => m), |
| 246 | Effect.catchTag(["UserGroupMemberNotFound", "UserGroupNotFound"], () => Effect.undefined), |
| 247 | ); |
| 248 | |
| 249 | const toAttributes = ( |
| 250 | member: ObservedMember, |
| 251 | userGroupId: string, |
| 252 | accountId: string, |
| 253 | ): UserGroupMembershipAttributes => ({ |
| 254 | userGroupId, |
| 255 | memberId: member.id, |
| 256 | accountId, |
| 257 | email: member.email ?? undefined, |
| 258 | status: member.status ?? undefined, |
| 259 | }); |