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
| 1 | import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { arrayEqualsUnordered } from "alchemy/Util/equal"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Predicate from "effect/Predicate"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | |
| 15 | export class ListUnexpectedResponse extends Data.TaggedError("ListUnexpectedResponse")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | const TypeId = "Cloudflare.Gateway.List" as const; |
| 21 | type TypeId = typeof TypeId; |
| 22 | |
| 23 | /** |
| 24 | * The kind of values a Gateway list holds. Immutable — changing the type |
| 25 | * triggers a replacement. |
| 26 | */ |
| 27 | export type ListType = |
| 28 | | "SERIAL" |
| 29 | | "URL" |
| 30 | | "DOMAIN" |
| 31 | | "EMAIL" |
| 32 | | "IP" |
| 33 | | "CATEGORY" |
| 34 | | "LOCATION" |
| 35 | | "DEVICE" |
| 36 | | "AAGUID"; |
| 37 | |
| 38 | /** |
| 39 | * A single entry in a Gateway list. |
| 40 | */ |
| 41 | export interface ListItem { |
| 42 | /** |
| 43 | * The item's value — a domain, URL, IP, email, serial number, etc. |
| 44 | * depending on the list's `type`. |
| 45 | */ |
| 46 | value: string; |
| 47 | /** |
| 48 | * Optional free-form description of the item. |
| 49 | */ |
| 50 | description?: string; |
| 51 | } |
| 52 | |
| 53 | export interface ListProps { |
| 54 | /** |
| 55 | * Display name for the list. Used as a stable identifier so the provider |
| 56 | * can locate the list by name during adoption / state recovery. If |
| 57 | * omitted, a unique name is generated from the app, stage, and logical ID. |
| 58 | * |
| 59 | * @default ${app}-${stage}-${id} |
| 60 | */ |
| 61 | name?: string; |
| 62 | /** |
| 63 | * The kind of values the list holds (DOMAIN, IP, URL, EMAIL, SERIAL, |
| 64 | * CATEGORY, LOCATION, DEVICE, AAGUID). Immutable — changing the type |
| 65 | * triggers a replacement. |
| 66 | */ |
| 67 | type: ListType; |
| 68 | /** |
| 69 | * Free-form description of the list. Mutable. |
| 70 | * |
| 71 | * @default "" |
| 72 | */ |
| 73 | description?: string; |
| 74 | /** |
| 75 | * Entries in the list. Reconciled as a full set via PUT — items present |
| 76 | * here and missing in the cloud are added; extra cloud items are removed. |
| 77 | * |
| 78 | * @default [] |
| 79 | */ |
| 80 | items?: ListItem[]; |
| 81 | } |
| 82 | |
| 83 | export interface ListAttributes { |
| 84 | /** UUID of the list, assigned by Cloudflare. */ |
| 85 | listId: string; |
| 86 | /** Cloudflare account that owns the list. */ |
| 87 | accountId: string; |
| 88 | /** Display name of the list. */ |
| 89 | name: string; |
| 90 | /** The kind of values the list holds. */ |
| 91 | type: ListType; |
| 92 | /** Description of the list. */ |
| 93 | description: string; |
| 94 | /** Current entries in the list. */ |
| 95 | items: ListItem[]; |
| 96 | /** Number of entries in the list. */ |
| 97 | count: number; |
| 98 | /** ISO8601 creation timestamp. */ |
| 99 | createdAt: string | undefined; |
| 100 | /** ISO8601 last-update timestamp. */ |
| 101 | updatedAt: string | undefined; |
| 102 | } |
| 103 | |
| 104 | export type List = Resource<TypeId, ListProps, ListAttributes, never, Providers>; |
| 105 | |
| 106 | /** |
| 107 | * A Cloudflare Zero Trust Gateway list — a named set of domains, IPs, |
| 108 | * URLs, emails, serial numbers, or device IDs referenced from Gateway |
| 109 | * rule wirefilter expressions by UUID (`$<listId>`). |
| 110 | * |
| 111 | * The list's `type` is immutable (changing it replaces the list); name, |
| 112 | * description, and items all converge in place. Items are managed as a |
| 113 | * full set — the provider PUTs the complete desired item set and removes |
| 114 | * anything not declared. |
| 115 | * ### Creating a List |
| 116 | * **Example:** Domain list |
| 117 | * ```typescript |
| 118 | * const blocked = yield* Cloudflare.Gateway.List("BlockedDomains", { |
| 119 | * type: "DOMAIN", |
| 120 | * description: "domains blocked org-wide", |
| 121 | * items: [ |
| 122 | * { value: "badsite.example.com" }, |
| 123 | * { value: "malware.example.net", description: "known C2" }, |
| 124 | * ], |
| 125 | * }); |
| 126 | * ``` |
| 127 | * |
| 128 | * **Example:** IP list |
| 129 | * ```typescript |
| 130 | * const egress = yield* Cloudflare.Gateway.List("OfficeEgress", { |
| 131 | * type: "IP", |
| 132 | * items: [{ value: "203.0.113.0/24" }], |
| 133 | * }); |
| 134 | * ``` |
| 135 | * |
| 136 | * ### Referencing from a Gateway Rule |
| 137 | * **Example:** Block DNS lookups for every domain in the list |
| 138 | * ```typescript |
| 139 | * yield* Cloudflare.Gateway.Rule("BlockListedDomains", { |
| 140 | * action: "block", |
| 141 | * filters: ["dns"], |
| 142 | * traffic: `any(dns.domains[*] in $${blocked.listId})`, |
| 143 | * }); |
| 144 | * ``` |
| 145 | * |
| 146 | * @see https://developers.cloudflare.com/cloudflare-one/policies/gateway/lists/ |
| 147 | * |
| 148 | * @resource |
| 149 | * @product Gateway |
| 150 | * @category Cloudflare One (Zero Trust) |
| 151 | */ |
| 152 | export const List = Resource<List>(TypeId); |
| 153 | |
| 154 | /** |
| 155 | * Returns true if the given value is a List resource. |
| 156 | */ |
| 157 | export const isList = (value: unknown): value is List => |
| 158 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 159 | |
| 160 | export const ListProvider = () => |
| 161 | Provider.succeed(List, { |
| 162 | stables: ["listId", "accountId", "type", "createdAt"], |
| 163 | |
| 164 | list: Effect.fn(function* () { |
| 165 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 166 | const lists = yield* zeroTrust.listGatewayLists.items({ accountId }).pipe( |
| 167 | Stream.runCollect, |
| 168 | Effect.map((chunk) => Array.from(chunk)), |
| 169 | ); |
| 170 | return lists.map((list) => toAttributes(list, accountId)); |
| 171 | }), |
| 172 | |
| 173 | diff: Effect.fn(function* ({ olds = {}, news, output }) { |
| 174 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 175 | if (!isResolved(news)) return undefined; |
| 176 | if ((output?.accountId ?? accountId) !== accountId) { |
| 177 | return { action: "replace" } as const; |
| 178 | } |
| 179 | // The list type is immutable on Cloudflare's side. |
| 180 | const oldType = output?.type ?? (olds as ListProps).type; |
| 181 | if (oldType !== undefined && oldType !== news.type) { |
| 182 | return { action: "replace" } as const; |
| 183 | } |
| 184 | return undefined; |
| 185 | }), |
| 186 | |
| 187 | read: Effect.fn(function* ({ id, output, olds }) { |
| 188 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 189 | const acct = output?.accountId ?? accountId; |
| 190 | |
| 191 | // Owned path — refresh by the cached list id. |
| 192 | if (output?.listId) { |
| 193 | const observed = yield* getList(acct, output.listId); |
| 194 | if (observed) return toAttributes(observed, acct); |
| 195 | } |
| 196 | |
| 197 | // Cold read — locate by deterministic name. Gateway lists carry no |
| 198 | // ownership markers, so report the match as Unowned to gate adoption. |
| 199 | const name = yield* resolveName(id, olds?.name ?? output?.name); |
| 200 | const match = yield* findByName(acct, name); |
| 201 | if (match?.id) { |
| 202 | const observed = yield* getList(acct, match.id); |
| 203 | if (observed) return Unowned(toAttributes(observed, acct)); |
| 204 | } |
| 205 | return undefined; |
| 206 | }), |
| 207 | |
| 208 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 209 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 210 | const name = yield* resolveName(id, news.name); |
| 211 | const desiredItems = news.items ?? []; |
| 212 | |
| 213 | // 1. Observe — the cached id is a hint, not a guarantee; fall back |
| 214 | // to a name scan so out-of-band deletes / lost state converge. |
| 215 | let observed = output?.listId ? yield* getList(accountId, output.listId) : undefined; |
| 216 | if (!observed) { |
| 217 | const match = yield* findByName(accountId, name); |
| 218 | if (match?.id) observed = yield* getList(accountId, match.id); |
| 219 | } |
| 220 | |
| 221 | // 2. Ensure — create with the full desired body when missing. Names |
| 222 | // are not unique on Cloudflare's side, so there is no |
| 223 | // AlreadyExists race to tolerate. |
| 224 | if (!observed) { |
| 225 | const created = yield* zeroTrust.createGatewayList({ |
| 226 | accountId, |
| 227 | name, |
| 228 | type: news.type, |
| 229 | description: news.description, |
| 230 | items: desiredItems, |
| 231 | }); |
| 232 | if (!created.id) { |
| 233 | return yield* new ListUnexpectedResponse({ |
| 234 | message: "Cloudflare did not return an id for the Gateway list", |
| 235 | }); |
| 236 | } |
| 237 | // Create echoes items without count — re-read for a full shape. |
| 238 | const fresh = yield* getList(accountId, created.id); |
| 239 | return toAttributes(fresh ?? { ...created, count: desiredItems.length }, accountId); |
| 240 | } |
| 241 | |
| 242 | // 3. Sync — diff observed name/description/items against desired; |
| 243 | // the update API is a PUT of the full mutable state, so skip the |
| 244 | // call entirely on a no-op. Items compare as an unordered set of |
| 245 | // values (the API may reorder). |
| 246 | const observedItems = (observed.items ?? []).map((i) => ({ |
| 247 | value: i.value ?? "", |
| 248 | ...(i.description != null ? { description: i.description } : {}), |
| 249 | })); |
| 250 | const dirty = |
| 251 | observed.name !== name || |
| 252 | (news.description !== undefined && (observed.description ?? "") !== news.description) || |
| 253 | !sameItems(observedItems, desiredItems); |
| 254 | if (dirty) { |
| 255 | yield* zeroTrust.updateGatewayList({ |
| 256 | accountId, |
| 257 | listId: observed.id!, |
| 258 | name, |
| 259 | description: news.description ?? observed.description ?? undefined, |
| 260 | items: desiredItems, |
| 261 | }); |
| 262 | // PUT echoes count but not items — re-read for the full shape. |
| 263 | const fresh = yield* getList(accountId, observed.id!); |
| 264 | if (fresh) return toAttributes(fresh, accountId); |
| 265 | } |
| 266 | |
| 267 | return toAttributes(observed, accountId); |
| 268 | }), |
| 269 | |
| 270 | delete: Effect.fn(function* ({ output }) { |
| 271 | // Lists still referenced by Gateway rules can fail deletion — rules |
| 272 | // that reference the list id as an Input get correct destroy |
| 273 | // ordering. A missing list (GatewayListNotFound, code 2218) means |
| 274 | // we're done. |
| 275 | yield* zeroTrust |
| 276 | .deleteGatewayList({ |
| 277 | accountId: output.accountId, |
| 278 | listId: output.listId, |
| 279 | }) |
| 280 | .pipe(Effect.catchTag("GatewayListNotFound", () => Effect.void)); |
| 281 | }), |
| 282 | }); |
| 283 | |
| 284 | type ObservedList = zeroTrust.GetGatewayListResponse; |
| 285 | |
| 286 | /** |
| 287 | * Read a list by id, mapping "gone" (`GatewayListNotFound`, Cloudflare |
| 288 | * error code 2218) to `undefined`. |
| 289 | */ |
| 290 | const getList = (accountId: string, listId: string) => |
| 291 | zeroTrust.getGatewayList({ accountId, listId }).pipe( |
| 292 | Effect.map((l): ObservedList | undefined => l), |
| 293 | Effect.catchTag("GatewayListNotFound", () => Effect.undefined), |
| 294 | ); |
| 295 | |
| 296 | /** |
| 297 | * Find a list by exact name. Names are not unique on Cloudflare's side; |
| 298 | * pick the oldest match for determinism. |
| 299 | */ |
| 300 | const findByName = (accountId: string, name: string) => |
| 301 | zeroTrust.listGatewayLists.items({ accountId }).pipe( |
| 302 | Stream.filter((l) => l.name === name), |
| 303 | Stream.runCollect, |
| 304 | Effect.map((chunk) => |
| 305 | Array.from(chunk) |
| 306 | .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")) |
| 307 | .at(0), |
| 308 | ), |
| 309 | ); |
| 310 | |
| 311 | const resolveName = (id: string, name: string | undefined) => |
| 312 | Effect.gen(function* () { |
| 313 | if (name) return name; |
| 314 | return yield* createPhysicalName({ id, lowercase: true }); |
| 315 | }); |
| 316 | |
| 317 | const sameItems = (observed: ReadonlyArray<ListItem>, desired: ReadonlyArray<ListItem>): boolean => |
| 318 | arrayEqualsUnordered( |
| 319 | observed.map((i) => `${i.value} |