The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Predicate from "effect/Predicate"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export class GroupUnexpectedResponse extends Data.TaggedError("GroupUnexpectedResponse")<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | /** |
| 20 | * One arm of a Cloudflare Access group rule discriminated union. A rule is a |
| 21 | * single-key object whose key selects the rule kind (`email`, `emailDomain`, |
| 22 | * `everyone`, `ip`, `geo`, `serviceToken`, etc.) and whose value carries the |
| 23 | * rule's parameters. |
| 24 | * |
| 25 | * Re-exported from `@distilled.cloud/cloudflare/zero-trust`'s |
| 26 | * `CreateAccessGroupForAccountRequest` so the full Cloudflare rule surface is |
| 27 | * available without re-declaring the union. |
| 28 | */ |
| 29 | export type GroupRule = zeroTrust.CreateAccessGroupForAccountRequest["include"][number]; |
| 30 | |
| 31 | /** |
| 32 | * One arm of the exclude-side rule union, and its require-side twin. |
| 33 | * Cloudflare's spec types the exclude/require rule lists separately from |
| 34 | * include — a few rule kinds (e.g. the GitHub-organization rule) carry the |
| 35 | * raw wire shape there — so these props use the SDK's own unions rather |
| 36 | * than reusing {@link GroupRule}. |
| 37 | */ |
| 38 | export type GroupExcludeRule = NonNullable< |
| 39 | zeroTrust.CreateAccessGroupForAccountRequest["exclude"] |
| 40 | >[number]; |
| 41 | export type GroupRequireRule = NonNullable< |
| 42 | zeroTrust.CreateAccessGroupForAccountRequest["require"] |
| 43 | >[number]; |
| 44 | |
| 45 | export type GroupProps = { |
| 46 | /** |
| 47 | * Display name for the group. Used as a stable identifier so the provider |
| 48 | * can locate the group by name during adoption / state recovery. If |
| 49 | * omitted, a unique name is generated from the stack/stage/logical id. |
| 50 | * |
| 51 | * @default ${app}-${stage}-${id} |
| 52 | */ |
| 53 | name?: string; |
| 54 | /** |
| 55 | * Rules combined with logical OR. A user needs to meet only one of the |
| 56 | * Include rules to match the group. Required and must be non-empty. |
| 57 | */ |
| 58 | include: GroupRule[]; |
| 59 | /** |
| 60 | * Rules combined with logical NOT. A user matching any Exclude rule does |
| 61 | * not match the group, even if they satisfied an Include rule. |
| 62 | */ |
| 63 | exclude?: GroupExcludeRule[]; |
| 64 | /** |
| 65 | * Rules combined with logical AND. A user must satisfy every Require rule |
| 66 | * in addition to an Include rule. |
| 67 | */ |
| 68 | require?: GroupRequireRule[]; |
| 69 | /** |
| 70 | * Whether this is the default group for the Zero Trust organization. |
| 71 | * |
| 72 | * @default false |
| 73 | */ |
| 74 | isDefault?: boolean; |
| 75 | }; |
| 76 | |
| 77 | export type Group = Resource< |
| 78 | "Cloudflare.Access.Group", |
| 79 | GroupProps, |
| 80 | { |
| 81 | /** UUID of the group assigned by Cloudflare. */ |
| 82 | groupId: string; |
| 83 | /** Cloudflare account that owns the group. */ |
| 84 | accountId: string; |
| 85 | /** Display name reported by Cloudflare. */ |
| 86 | name: string; |
| 87 | /** Whether Cloudflare reports this group as the organization default. */ |
| 88 | isDefault: boolean | undefined; |
| 89 | }, |
| 90 | never, |
| 91 | Providers |
| 92 | >; |
| 93 | |
| 94 | /** |
| 95 | * A Cloudflare Zero Trust Access group — a reusable, account-scoped set of |
| 96 | * Access rule criteria. Groups are referenced from Access policies via a |
| 97 | * `{ group: { id } }` rule, letting many policies share one membership |
| 98 | * definition. |
| 99 | * ### Creating a Group |
| 100 | * **Example:** Allow a single email domain |
| 101 | * ```typescript |
| 102 | * const group = yield* Cloudflare.Access.Group("ExampleDomain", { |
| 103 | * include: [{ emailDomain: { domain: "example.com" } }], |
| 104 | * }); |
| 105 | * ``` |
| 106 | * |
| 107 | * **Example:** Combine include, exclude and require rules |
| 108 | * ```typescript |
| 109 | * const group = yield* Cloudflare.Access.Group("UsEngineers", { |
| 110 | * include: [{ emailDomain: { domain: "example.com" } }], |
| 111 | * exclude: [{ email: { email: "intern@example.com" } }], |
| 112 | * require: [{ geo: { countryCode: "US" } }], |
| 113 | * }); |
| 114 | * ``` |
| 115 | * |
| 116 | * ### Referencing a Group from a Policy |
| 117 | * **Example:** Allow members of the group |
| 118 | * ```typescript |
| 119 | * const group = yield* Cloudflare.Access.Group("Team", { |
| 120 | * include: [{ emailDomain: { domain: "example.com" } }], |
| 121 | * }); |
| 122 | * |
| 123 | * const policy = yield* Cloudflare.Access.Policy("AllowTeam", { |
| 124 | * decision: "allow", |
| 125 | * include: [{ group: { id: group.groupId } }], |
| 126 | * }); |
| 127 | * ``` |
| 128 | * |
| 129 | * @resource |
| 130 | * @product Access |
| 131 | * @category Cloudflare One (Zero Trust) |
| 132 | */ |
| 133 | export const Group = Resource<Group>("Cloudflare.Access.Group"); |
| 134 | |
| 135 | export const isGroup = (value: unknown): value is Group => |
| 136 | Predicate.hasProperty(value, "Type") && value.Type === "Cloudflare.Access.Group"; |
| 137 | |
| 138 | export const GroupProvider = () => |
| 139 | Provider.succeed(Group, { |
| 140 | stables: ["groupId", "accountId"], |
| 141 | diff: Effect.fn(function* ({ news, output }) { |
| 142 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 143 | if (!isResolved(news)) return undefined; |
| 144 | if ((output?.accountId ?? accountId) !== accountId) { |
| 145 | return { action: "replace" } as const; |
| 146 | } |
| 147 | // Everything else (name, rules, isDefault) converges via PUT. |
| 148 | }), |
| 149 | read: Effect.fn(function* ({ id, output, olds }) { |
| 150 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 151 | const acct = output?.accountId ?? accountId; |
| 152 | if (output?.groupId) { |
| 153 | const direct = yield* zeroTrust |
| 154 | .getAccessGroupForAccount({ |
| 155 | accountId: acct, |
| 156 | groupId: output.groupId, |
| 157 | }) |
| 158 | .pipe( |
| 159 | Effect.map(toObserved), |
| 160 | Effect.catchTag("AccessGroupNotFound", () => Effect.undefined), |
| 161 | ); |
| 162 | if (direct && direct.id) { |
| 163 | return { |
| 164 | groupId: direct.id, |
| 165 | accountId: acct, |
| 166 | name: direct.name ?? output.name, |
| 167 | isDefault: direct.isDefault ?? output.isDefault, |
| 168 | }; |
| 169 | } |
| 170 | } |
| 171 | const name = yield* createGroupName(id, olds?.name ?? output?.name); |
| 172 | const existing = yield* findGroupByName(acct, name); |
| 173 | if (!existing || !existing.id) return undefined; |
| 174 | return { |
| 175 | groupId: existing.id, |
| 176 | accountId: acct, |
| 177 | name: existing.name ?? name, |
| 178 | isDefault: existing.isDefault ?? undefined, |
| 179 | }; |
| 180 | }), |
| 181 | list: Effect.fn(function* () { |
| 182 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 183 | return yield* zeroTrust.listAccessGroupsForAccount.pages({ accountId }).pipe( |
| 184 | Stream.runCollect, |
| 185 | Effect.map((chunk) => |
| 186 | Array.from(chunk).flatMap((page) => |
| 187 | (page.result ?? []) |
| 188 | .filter((g): g is (typeof page.result)[number] & { id: string } => g.id != null) |
| 189 | .map((g) => ({ |
| 190 | groupId: g.id, |
| 191 | accountId, |
| 192 | name: g.name ?? "", |
| 193 | isDefault: g.isDefault ?? undefined, |
| 194 | })), |
| 195 | ), |
| 196 | ), |
| 197 | ); |
| 198 | }), |
| 199 | reconcile: Effect.fn(function* ({ id, news = {} as GroupProps, output }) { |
| 200 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 201 | const name = yield* createGroupName(id, news.name); |
| 202 | const acct = output?.accountId ?? accountId; |
| 203 | |
| 204 | // Observe — prefer the cached groupId, fall back to a name lookup so |
| 205 | // we recover from out-of-band deletes and partial state-persistence |
| 206 | // failures. |
| 207 | let observed: ObservedGroup | undefined; |
| 208 | if (output?.groupId) { |
| 209 | observed = yield* zeroTrust |
| 210 | .getAccessGroupForAccount({ |
| 211 | accountId: acct, |
| 212 | groupId: output.groupId, |
| 213 | }) |
| 214 | .pipe( |
| 215 | Effect.map(toObserved), |
| 216 | Effect.catchTag("AccessGroupNotFound", () => Effect.undefined), |
| 217 | ); |
| 218 | } |
| 219 | if (!observed) { |
| 220 | observed = yield* findGroupByName(acct, name); |
| 221 | } |
| 222 | |
| 223 | // Ensure — create the group when missing. Tolerate a race where a |
| 224 | // parallel actor created the same-named group by re-observing. |
| 225 | let ensured: ObservedGroup; |
| 226 | if (!observed || !observed.id) { |
| 227 | ensured = yield* zeroTrust |
| 228 | .createAccessGroupForAccount({ |
| 229 | accountId: acct, |
| 230 | name, |
| 231 | include: news.include, |
| 232 | exclude: news.exclude, |
| 233 | require: news.require, |
| 234 | isDefault: news.isDefault, |
| 235 | }) |
| 236 | .pipe( |
| 237 | Effect.map(toObserved), |
| 238 | Effect.catch((err) => |
| 239 | Effect.gen(function* () { |
| 240 | const existing = yield* findGroupByName(acct, name); |
| 241 | if (existing && existing.id) return existing; |
| 242 | return yield* err; |
| 243 | }), |
| 244 | ), |
| 245 | ); |
| 246 | } else { |
| 247 | // Sync — Cloudflare PUTs the group as a whole replacement, so a |
| 248 | // single update converges every mutable field (name, rule sets, |
| 249 | // isDefault). The API is idempotent for equal payloads. |
| 250 | const prior = observed; |
| 251 | const updated = yield* zeroTrust.updateAccessGroupForAccount({ |
| 252 | accountId: acct, |
| 253 | groupId: prior.id!, |
| 254 | name, |
| 255 | include: news.include, |
| 256 | exclude: news.exclude, |
| 257 | require: news.require, |
| 258 | isDefault: news.isDefault, |
| 259 | }); |
| 260 | ensured = { |
| 261 | id: updated.id ?? prior.id, |
| 262 | name: updated.name ?? prior.name, |
| 263 | isDefault: updated.isDefault ?? prior.isDefault, |
| 264 | }; |
| 265 | } |
| 266 | |
| 267 | if (!ensured.id) { |
| 268 | return yield* new GroupUnexpectedResponse({ message: "Group: ensured group missing id" }); |
| 269 | } |
| 270 | return { |
| 271 | groupId: ensured.id, |
| 272 | accountId: acct, |
| 273 | name: ensured.name ?? name, |
| 274 | isDefault: ensured.isDefault ?? news.isDefault, |
| 275 | }; |
| 276 | }), |
| 277 | delete: Effect.fn(function* ({ output }) { |
| 278 | yield* zeroTrust |
| 279 | .deleteAccessGroupForAccount({ |
| 280 | accountId: output.accountId, |
| 281 | groupId: output.groupId, |
| 282 | }) |
| 283 | .pipe(Effect.catchTag("AccessGroupNotFound", () => Effect.void)); |
| 284 | }), |
| 285 | }); |
| 286 | |
| 287 | const createGroupName = (id: string, name: string | undefined) => |
| 288 | Effect.gen(function* () { |
| 289 | if (name) return name; |
| 290 | return yield* createPhysicalName({ id }); |
| 291 | }); |
| 292 | |
| 293 | const findGroupByName = (acct: string, name: string) => |
| 294 | zeroTrust.listAccessGroupsForAccount.items({ accountId: acct }).pipe( |
| 295 | Stream.filter((g): g is ObservedGroup => g.name === name), |
| 296 | Stream.runHead, |
| 297 | Effect.map(Option.getOrUndefined), |
| 298 | Effect.orElseSucceed(() => undefined), |
| 299 | ); |
| 300 | |
| 301 | type ObservedGroup = { |
| 302 | id?: string | null; |
| 303 | name?: string | null; |
| 304 | isDefault?: boolean | null; |
| 305 | }; |
| 306 | |
| 307 | const toObserved = (g: ObservedGroup): ObservedGroup => ({ |
| 308 | id: g.id, |
| 309 | name: g.name, |
| 310 | isDefault: g.isDefault, |
| 311 | }); |