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 * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Stream from "effect/Stream"; |
| 8 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | |
| 11 | export type RouteProps = { |
| 12 | /** |
| 13 | * UUID of the `cfd_tunnel` this route attaches to. |
| 14 | * |
| 15 | * Stable -- changing the tunnel triggers replacement. |
| 16 | */ |
| 17 | tunnelId: string; |
| 18 | /** |
| 19 | * Private IPv4 or IPv6 range exposed through the tunnel, in CIDR notation |
| 20 | * (e.g. `10.4.0.0/16`). |
| 21 | * |
| 22 | * Stable -- changing the CIDR triggers replacement. |
| 23 | * |
| 24 | * Declared as a plain `string` (not `string`) so it is statically |
| 25 | * knowable inside `diff`. |
| 26 | */ |
| 27 | network: string; |
| 28 | /** |
| 29 | * Optional human-readable note attached to the route. |
| 30 | * |
| 31 | * Mutable -- changes are applied in place via PATCH. |
| 32 | */ |
| 33 | comment?: string; |
| 34 | /** |
| 35 | * Optional Tunnel Virtual Network UUID. Use to disambiguate overlapping |
| 36 | * CIDRs that live in separate virtual networks. |
| 37 | * |
| 38 | * Stable -- changing the virtual network triggers replacement. |
| 39 | */ |
| 40 | virtualNetworkId?: string; |
| 41 | /** |
| 42 | * Whether to adopt an existing route with the same network (and virtual |
| 43 | * network, when set) on the same tunnel if one is already present. |
| 44 | * |
| 45 | * @default false |
| 46 | */ |
| 47 | adopt?: boolean; |
| 48 | }; |
| 49 | |
| 50 | export type Route = Resource< |
| 51 | "Cloudflare.Tunnel.Route", |
| 52 | RouteProps, |
| 53 | { |
| 54 | /** |
| 55 | * UUID of the route, assigned by Cloudflare. |
| 56 | */ |
| 57 | routeId: string; |
| 58 | /** |
| 59 | * The CIDR exposed through the tunnel. |
| 60 | */ |
| 61 | network: string; |
| 62 | /** |
| 63 | * UUID of the tunnel this route attaches to. |
| 64 | */ |
| 65 | tunnelId: string; |
| 66 | /** |
| 67 | * Cloudflare account that owns the route. |
| 68 | */ |
| 69 | accountId: string; |
| 70 | /** |
| 71 | * Human-readable note attached to the route, if any. |
| 72 | */ |
| 73 | comment: string | undefined; |
| 74 | /** |
| 75 | * UUID of the Tunnel Virtual Network the route lives in, if any. |
| 76 | */ |
| 77 | virtualNetworkId: string | undefined; |
| 78 | /** |
| 79 | * RFC 3339 timestamp of when the route was created (as reported by |
| 80 | * Cloudflare), if available. |
| 81 | */ |
| 82 | createdAt: string | undefined; |
| 83 | }, |
| 84 | never, |
| 85 | Providers |
| 86 | >; |
| 87 | |
| 88 | /** |
| 89 | * A Cloudflare Tunnel Route attaches a private CIDR to a `cfd_tunnel` so that |
| 90 | * WARP clients (and other Zero Trust egress paths) can reach private IPs |
| 91 | * through the tunnel. |
| 92 | * ### Creating a Route |
| 93 | * **Example:** Basic route |
| 94 | * ```typescript |
| 95 | * const tunnel = yield* Cloudflare.Tunnel.Tunnel("MyTunnel"); |
| 96 | * const route = yield* Cloudflare.Tunnel.Route("PrivateNet", { |
| 97 | * tunnelId: tunnel.tunnelId, |
| 98 | * network: "10.4.0.0/16", |
| 99 | * }); |
| 100 | * ``` |
| 101 | * |
| 102 | * **Example:** Route with a comment and explicit virtual network |
| 103 | * ```typescript |
| 104 | * const route = yield* Cloudflare.Tunnel.Route("DcRoute", { |
| 105 | * tunnelId: tunnel.tunnelId, |
| 106 | * network: "10.50.0.0/16", |
| 107 | * comment: "Datacenter A private subnet", |
| 108 | * virtualNetworkId: vnet.id, |
| 109 | * adopt: true, |
| 110 | * }); |
| 111 | * ``` |
| 112 | * |
| 113 | * @resource |
| 114 | * @product Tunnels |
| 115 | * @category Cloudflare One (Zero Trust) |
| 116 | */ |
| 117 | export const Route = Resource<Route>("Cloudflare.Tunnel.Route", { |
| 118 | aliases: ["Cloudflare.TunnelRoute"], |
| 119 | }); |
| 120 | |
| 121 | export const RouteProvider = () => |
| 122 | Provider.succeed(Route, { |
| 123 | stables: ["routeId", "accountId", "tunnelId", "network", "virtualNetworkId"], |
| 124 | diff: Effect.fn(function* ({ olds = {}, news, output }) { |
| 125 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 126 | |
| 127 | if (!isResolved(news)) return undefined; |
| 128 | const acct = output?.accountId ?? accountId; |
| 129 | if (acct !== accountId) { |
| 130 | return { action: "replace" } as const; |
| 131 | } |
| 132 | if (output?.network !== undefined && output.network !== news.network) { |
| 133 | return { action: "replace" } as const; |
| 134 | } |
| 135 | if (olds.network !== undefined && olds.network !== news.network) { |
| 136 | return { action: "replace" } as const; |
| 137 | } |
| 138 | const oldTunnelId = output?.tunnelId ?? olds.tunnelId; |
| 139 | if (oldTunnelId !== undefined && oldTunnelId !== news.tunnelId) { |
| 140 | return { action: "replace" } as const; |
| 141 | } |
| 142 | // virtualNetworkId is auto-assigned by Cloudflare when omitted |
| 143 | // (every account has a "default" virtual network that absorbs |
| 144 | // routes without an explicit assignment). If the caller didn't |
| 145 | // ask for a specific vnet (`news.virtualNetworkId === undefined`), |
| 146 | // they're delegating to CF — don't force a replace just because |
| 147 | // CF auto-assigned one. Only mark replace when the caller has |
| 148 | // EXPLICITLY chosen a vnet and it differs from what's deployed. |
| 149 | if ( |
| 150 | news.virtualNetworkId !== undefined && |
| 151 | (output?.virtualNetworkId ?? olds.virtualNetworkId) !== news.virtualNetworkId |
| 152 | ) { |
| 153 | return { action: "replace" } as const; |
| 154 | } |
| 155 | }), |
| 156 | reconcile: Effect.fn(function* ({ news, output }) { |
| 157 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 158 | |
| 159 | const acct = output?.accountId ?? accountId; |
| 160 | const tunnelId = news.tunnelId; |
| 161 | const network = news.network; |
| 162 | const virtualNetworkId = news.virtualNetworkId; |
| 163 | |
| 164 | // Observe — cached id first, then an account-wide list scan by |
| 165 | // network so we recover from out-of-band deletes, partial state |
| 166 | // writes, or a route left attached to another tunnel. |
| 167 | let observed = yield* observe(acct, network, virtualNetworkId, output?.routeId); |
| 168 | |
| 169 | // Ensure — create when missing. Cloudflare returns a generic |
| 170 | // conflict on duplicate (network, tunnel, vnet) tuples; on any |
| 171 | // such race re-observe and either adopt or rethrow. |
| 172 | if (!observed) { |
| 173 | // Cloudflare returns an untagged generic error on a |
| 174 | // duplicate (network, tunnel, vnet) tuple. distilled |
| 175 | // surfaces it as the untyped Cloudflare error bucket, |
| 176 | // so we can't `catchTag` -- we narrow by re-observing |
| 177 | // and only swallowing the error when adoption is |
| 178 | // requested AND a matching route actually exists. |
| 179 | const createdOrAdopted = yield* zeroTrust |
| 180 | .createNetworkRoute({ |
| 181 | accountId: acct, |
| 182 | network, |
| 183 | tunnelId, |
| 184 | comment: news.comment, |
| 185 | virtualNetworkId, |
| 186 | }) |
| 187 | .pipe( |
| 188 | Effect.catch((err) => |
| 189 | Effect.gen(function* () { |
| 190 | if (!news.adopt) return yield* err; |
| 191 | const existing = yield* observe(acct, network, virtualNetworkId, undefined); |
| 192 | if (!existing) return yield* err; |
| 193 | // Sentinel: undefined means "adoption path; use re-observed value". |
| 194 | return undefined; |
| 195 | }), |
| 196 | ), |
| 197 | ); |
| 198 | observed = createdOrAdopted |
| 199 | ? toObserved(createdOrAdopted) |
| 200 | : yield* observe(acct, network, virtualNetworkId, undefined); |
| 201 | } |
| 202 | |
| 203 | if (!observed) { |
| 204 | return yield* Effect.die( |
| 205 | `Route create returned no id for network ${network} on tunnel ${tunnelId}`, |
| 206 | ); |
| 207 | } |
| 208 | |
| 209 | // Sync — `comment` is mutable, and an adopted route may be |
| 210 | // attached to a different tunnel (the account-wide network |
| 211 | // uniqueness means we adopt whatever route owns the CIDR) so we |
| 212 | // repoint `tunnelId` too. Skip the PATCH entirely on no-op so we |
| 213 | // avoid churn on every reconcile. Clearing a comment must send |
| 214 | // `""` explicitly — omitting every body field produces an empty |
| 215 | // PATCH body which Cloudflare rejects with a JSON parse error. |
| 216 | const desiredComment = news.comment ?? ""; |
| 217 | const needsComment = (observed.comment ?? "") !== desiredComment; |
| 218 | const needsTunnel = observed.tunnelId !== tunnelId; |
| 219 | if (needsComment || needsTunnel) { |
| 220 | const patched = yield* zeroTrust.patchNetworkRoute({ |
| 221 | accountId: acct, |
| 222 | routeId: observed.id, |
| 223 | ...(needsComment ? { comment: desiredComment } : {}), |
| 224 | ...(needsTunnel ? { tunnelId } : {}), |
| 225 | }); |
| 226 | observed = { |
| 227 | id: patched.id ?? observed.id, |
| 228 | network: normalize(patched.network) ?? observed.network, |
| 229 | tunnelId: normalize(patched.tunnelId) ?? observed.tunnelId, |
| 230 | virtualNetworkId: normalize(patched.virtualNetworkId) ?? observed.virtualNetworkId, |
| 231 | comment: normalize(patched.comment), |
| 232 | createdAt: normalize(patched.createdAt) ?? observed.createdAt, |
| 233 | }; |
| 234 | } |
| 235 | |
| 236 | return { |
| 237 | routeId: observed.id, |
| 238 | network: observed.network ?? network, |
| 239 | tunnelId: observed.tunnelId ?? tunnelId, |
| 240 | accountId: acct, |
| 241 | comment: observed.comment, |
| 242 | virtualNetworkId: observed.virtualNetworkId ?? virtualNetworkId, |
| 243 | createdAt: observed.createdAt, |
| 244 | }; |
| 245 | }), |
| 246 | delete: Effect.fn(function* ({ output }) { |
| 247 | yield* zeroTrust |
| 248 | .deleteNetworkRoute({ |
| 249 | accountId: output.accountId, |
| 250 | routeId: output.routeId, |
| 251 | }) |
| 252 | .pipe( |
| 253 | // Idempotent delete: distilled doesn't tag NotFound on |
| 254 | // teamnet/routes/{id}, so we swallow read-side failure |
| 255 | // wholesale. A "delete a deleted route" is not an error. |
| 256 | Effect.orElseSucceed(() => undefined), |
| 257 | ); |
| 258 | }), |
| 259 | list: Effect.fn(function* () { |
| 260 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 261 | // Account-scoped collection: enumerate every Zero Trust network |
| 262 | // route in the account, exhaustively paginating. Drop soft-deleted |
| 263 | // routes and anything missing an id, then hydrate into the exact |
| 264 | // `read` Attributes shape so each element is delete-ready. |
| 265 | return yield* zeroTrust.listNetworkRoutes.pages({ accountId, isDeleted: false }).pipe( |
| 266 | Stream.runCollect, |
| 267 | Effect.map((chunk) => |
| 268 | Array.from(chunk).flatMap((page) => |
| 269 | (page.result ?? []) |
| 270 | .filter((r): r is typeof r & { id: string } => r.id != null && !r.deletedAt) |
| 271 | .map((r) => ({ |
| 272 | routeId: r.id, |
| 273 | network: normalize(r.network) ?? "", |
| 274 | tunnelId: normalize(r.tunnelId) ?? "", |
| 275 | accountId, |
| 276 | comment: normalize(r.comment), |
| 277 | virtualNetworkId: normalize(r.virtualNetworkId), |
| 278 | createdAt: normalize(r.createdAt), |
| 279 | })), |
| 280 | ), |
| 281 | ), |
| 282 | ); |
| 283 | }), |
| 284 | read: Effect.fn(function* ({ olds, output }) { |
| 285 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 286 | |
| 287 | const acct = output?.accountId ?? accountId; |
| 288 | const tunnelId = output?.tunnelId ?? olds?.tunnelId; |
| 289 | const network = output?.network ?? olds?.network; |
| 290 | const virtualNetworkId = output?.virtualNetworkId ?? olds?.virtualNetworkId; |
| 291 | if (!tunnelId || !network) return undefined; |
| 292 | const observed = yield* observe(acct, network, virtualNetworkId, output?.routeId); |
| 293 | if (!observed) return undefined; |
| 294 | return { |
| 295 | routeId: observed.id, |
| 296 | network: observed.network ?? network, |
| 297 | tunnelId: observed.tunnelId ?? tunnelId, |
| 298 | accountId: acct, |
| 299 | comment: observed.comment, |
| 300 | virtualNetworkId: observed.virtualNetworkId ?? virtualNetworkId, |
| 301 | createdAt: observed.createdAt, |
| 302 | }; |
| 303 | }), |
| 304 | }); |
| 305 | |
| 306 | // Route networks are unique per virtual network across the WHOLE |
| 307 | // account (Cloudflare rejects a duplicate CIDR with a Conflict no |
| 308 | // matter which tunnel it's attached to), so the scan must NOT be |
| 309 | // scoped to a tunnel — otherwise a route left on another tunnel is |
| 310 | // invisible to observation and the create Conflict is unrecoverable. |
| 311 | const findRouteByNetwork = ( |
| 312 | accountId: string, |
| 313 | network: string, |
| 314 | virtualNetworkId: string | undefined, |
| 315 | ) => |
| 316 | zeroTrust.listNetworkRoutes |
| 317 | .items({ |
| 318 | accountId, |
| 319 | isDeleted: false, |
| 320 | // subset + superset of the same CIDR == exact match |
| 321 | networkSubset: network, |
| 322 | networkSuperset: network, |
| 323 | }) |
| 324 | .pipe( |
| 325 | Stream.filter( |
| 326 | (r) => |
| 327 | !r.deletedAt && |
| 328 | r.network === network && |
| 329 | (virtualNetworkId === undefined || r.virtualNetworkId === virtualNetworkId), |
| 330 | ), |
| 331 | Stream.runHead, |
| 332 | Effect.map(Option.getOrUndefined), |
| 333 | // The distilled cloudflare SDK only tags transport-shaped |
| 334 | // errors (Unauthorized / 5xx / TooManyRequests / parse |
| 335 | // errors) on this endpoint -- there's no `NotFound` or |
| 336 | // `Forbidden` tag to discriminate on. Mirror the |
| 337 | // canonical `Tunnel.ts` template: swallow read-side |
| 338 | // errors so observation falls through to "missing" and |
| 339 | // the ensure step can recover. |
| 340 | Effect.orElseSucceed(() => undefined), |
| 341 | ); |
| 342 | |
| 343 | const toObserved = (r: { |
| 344 | id?: string | null; |
| 345 | network?: string | null; |
| 346 | tunnelId?: string | null; |
| 347 | virtualNetworkId?: string | null; |
| 348 | comment?: string | null; |
| 349 | createdAt?: string | null; |
| 350 | deletedAt?: string | null; |
| 351 | }): ObservedRoute | undefined => |
| 352 | r.id |
| 353 | ? { |
| 354 | id: r.id, |
| 355 | network: normalize(r.network), |
| 356 | tunnelId: normalize(r.tunnelId), |
| 357 | virtualNetworkId: normalize(r.virtualNetworkId), |
| 358 | comment: normalize(r.comment), |
| 359 | createdAt: normalize(r.createdAt), |
| 360 | } |
| 361 | : undefined; |
| 362 | |
| 363 | const observe = Effect.fn(function* ( |
| 364 | acct: string, |
| 365 | network: string, |
| 366 | virtualNetworkId: string | undefined, |
| 367 | routeId: string | undefined, |
| 368 | ) { |
| 369 | if (routeId) { |
| 370 | // See `findRouteByNetwork` -- distilled doesn't tag |
| 371 | // NotFound on this endpoint, so we tolerate any read |
| 372 | // error and fall through to the list scan. |
| 373 | const raw = yield* zeroTrust |
| 374 | .getNetworkRoute({ accountId: acct, routeId }) |
| 375 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 376 | const got = raw ? toObserved(raw) : undefined; |
| 377 | if (got) return got; |
| 378 | } |
| 379 | const match = yield* findRouteByNetwork(acct, network, virtualNetworkId); |
| 380 | if (!match) return undefined; |
| 381 | return toObserved(match); |
| 382 | }); |
| 383 | |
| 384 | type ObservedRoute = { |
| 385 | id: string; |
| 386 | network: string | undefined; |
| 387 | tunnelId: string | undefined; |
| 388 | virtualNetworkId: string | undefined; |
| 389 | comment: string | undefined; |
| 390 | createdAt: string | undefined; |
| 391 | }; |
| 392 | |
| 393 | const normalize = (v: string | null | undefined): string | undefined => (v == null ? undefined : v); |