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 { 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 Effect from "effect/Effect"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Redacted from "effect/Redacted"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export type TunnelProps = { |
| 15 | /** |
| 16 | * Name for the tunnel. If omitted, a unique name will be generated. |
| 17 | * |
| 18 | * Tunnel names are immutable -- changing the name triggers replacement. |
| 19 | * |
| 20 | * @default ${app}-${stage}-${id} |
| 21 | */ |
| 22 | name?: string; |
| 23 | /** |
| 24 | * Secret used by the tunnel connector. If omitted, Cloudflare generates one. |
| 25 | * Must be at least 32 bytes encoded as base64. |
| 26 | */ |
| 27 | tunnelSecret?: Redacted.Redacted<string>; |
| 28 | /** |
| 29 | * Where the tunnel configuration lives. |
| 30 | * - `"cloudflare"` - managed remotely via the API (default) |
| 31 | * - `"local"` - managed via a YAML file on the origin |
| 32 | * |
| 33 | * @default "cloudflare" |
| 34 | */ |
| 35 | configSrc?: "cloudflare" | "local"; |
| 36 | /** |
| 37 | * Ingress rules describing how requests are routed. Must end with a |
| 38 | * catch-all rule (e.g. `{ service: "http_status:404" }`). Only honored when |
| 39 | * `configSrc` is `"cloudflare"`. |
| 40 | */ |
| 41 | ingress?: Tunnel.IngressRule[]; |
| 42 | /** |
| 43 | * Origin request configuration applied to all rules. Only honored when |
| 44 | * `configSrc` is `"cloudflare"`. |
| 45 | */ |
| 46 | originRequest?: Tunnel.OriginRequestConfig; |
| 47 | /** |
| 48 | * Whether to adopt an existing tunnel with the same name when create fails. |
| 49 | * |
| 50 | * @default false |
| 51 | */ |
| 52 | adopt?: boolean; |
| 53 | }; |
| 54 | |
| 55 | export declare namespace Tunnel { |
| 56 | /** |
| 57 | * Ingress rule describing how a hostname or path is routed. |
| 58 | */ |
| 59 | export interface IngressRule { |
| 60 | hostname?: string; |
| 61 | service: string; |
| 62 | path?: string; |
| 63 | originRequest?: OriginRequestConfig; |
| 64 | } |
| 65 | /** |
| 66 | * Origin request configuration applied per-rule or globally. |
| 67 | */ |
| 68 | export interface OriginRequestConfig { |
| 69 | connectTimeout?: number; |
| 70 | tlsTimeout?: number; |
| 71 | tcpKeepAlive?: number; |
| 72 | noHappyEyeballs?: boolean; |
| 73 | keepAliveConnections?: number; |
| 74 | keepAliveTimeout?: number; |
| 75 | http2Origin?: boolean; |
| 76 | httpHostHeader?: string; |
| 77 | caPool?: string; |
| 78 | noTLSVerify?: boolean; |
| 79 | disableChunkedEncoding?: boolean; |
| 80 | proxyType?: string; |
| 81 | matchSNItoHost?: boolean; |
| 82 | originServerName?: string; |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | export type Tunnel = Resource< |
| 87 | "Cloudflare.Tunnel.Tunnel", |
| 88 | TunnelProps, |
| 89 | { |
| 90 | tunnelId: string; |
| 91 | tunnelName: string; |
| 92 | accountTag: string | undefined; |
| 93 | accountId: string; |
| 94 | createdAt: string | undefined; |
| 95 | deletedAt: string | undefined; |
| 96 | configSrc: "cloudflare" | "local"; |
| 97 | token: Redacted.Redacted<string>; |
| 98 | }, |
| 99 | never, |
| 100 | Providers |
| 101 | >; |
| 102 | |
| 103 | /** |
| 104 | * A Cloudflare Tunnel that establishes a secure connection from your origin to |
| 105 | * Cloudflare's edge. |
| 106 | * ### Creating a Tunnel |
| 107 | * **Example:** Basic tunnel |
| 108 | * ```typescript |
| 109 | * const tunnel = yield* Cloudflare.Tunnel.Tunnel("MyTunnel"); |
| 110 | * // Run the connector with: cloudflared tunnel run --token <Redacted.value(tunnel.token)> |
| 111 | * ``` |
| 112 | * |
| 113 | * **Example:** Tunnel with ingress rules |
| 114 | * ```typescript |
| 115 | * const tunnel = yield* Cloudflare.Tunnel.Tunnel("Web", { |
| 116 | * ingress: [ |
| 117 | * { hostname: "app.example.com", service: "http://localhost:3000" }, |
| 118 | * { service: "http_status:404" }, |
| 119 | * ], |
| 120 | * }); |
| 121 | * ``` |
| 122 | * |
| 123 | * ### Managing Tunnels at Runtime |
| 124 | * The `Tunnel` resource manages a single, statically-declared tunnel as part of |
| 125 | * a stack. To create, read, update, or delete tunnels *on the fly* from inside |
| 126 | * a deployed Worker, bind one of the runtime tunnel clients instead. Each |
| 127 | * provisions a least-privilege {@link AccountApiToken} and injects it into the |
| 128 | * Worker: |
| 129 | * |
| 130 | * - {@link ReadTunnel} — read-only (`get`, `list`, `getToken`, |
| 131 | * `getConfiguration`); scoped to `Cloudflare Tunnel Read`. |
| 132 | * - {@link WriteTunnel} — mutating (`create`, `update`, `delete`, |
| 133 | * `putConfiguration`); scoped to `Cloudflare Tunnel Write`. |
| 134 | * - {@link ReadWriteTunnel} — the full CRUD surface; scoped to both. |
| 135 | * |
| 136 | * **Example:** Create a tunnel on demand from a Worker |
| 137 | * ```typescript |
| 138 | * // init |
| 139 | * const tunnels = yield* Cloudflare.Tunnel.ReadWriteTunnel(); |
| 140 | * |
| 141 | * return { |
| 142 | * fetch: Effect.gen(function* () { |
| 143 | * const tunnel = yield* tunnels.create({ name: "on-demand-tunnel" }); |
| 144 | * const token = yield* tunnels.getToken(tunnel.id!); |
| 145 | * return HttpServerResponse.json({ id: tunnel.id, token }); |
| 146 | * }), |
| 147 | * }; |
| 148 | * ``` |
| 149 | * |
| 150 | * @resource |
| 151 | * @product Tunnels |
| 152 | * @category Cloudflare One (Zero Trust) |
| 153 | */ |
| 154 | export const Tunnel = Resource<Tunnel>("Cloudflare.Tunnel.Tunnel", { |
| 155 | aliases: ["Cloudflare.Tunnel"], |
| 156 | }); |
| 157 | |
| 158 | export const TunnelProvider = () => |
| 159 | Provider.succeed(Tunnel, { |
| 160 | stables: ["tunnelId", "accountTag", "accountId"], |
| 161 | // Account collection: enumerate every cfd_tunnel in the account, skip |
| 162 | // deleted tunnels (match `read`/`findTunnelByName`), exhaustively |
| 163 | // paginate, then hydrate each into the exact `read` Attributes shape. |
| 164 | // The token is fetched per-tunnel with bounded concurrency; a tunnel |
| 165 | // whose token is gone is dropped (typed per-item not-found). |
| 166 | list: Effect.fn(function* () { |
| 167 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 168 | const tunnels = yield* zeroTrust.listTunnels |
| 169 | .pages({ accountId, isDeleted: false, tunTypes: ["cfd_tunnel"] }) |
| 170 | .pipe( |
| 171 | Stream.runCollect, |
| 172 | Effect.map((chunk) => |
| 173 | Array.from(chunk).flatMap((page) => |
| 174 | (page.result ?? []).filter( |
| 175 | (t): t is typeof t & { id: string } => !!t.id && !t.deletedAt, |
| 176 | ), |
| 177 | ), |
| 178 | ), |
| 179 | ); |
| 180 | const rows = yield* Effect.forEach( |
| 181 | tunnels, |
| 182 | (t) => |
| 183 | zeroTrust.getTunnelCloudflaredToken({ accountId, tunnelId: t.id }).pipe( |
| 184 | Effect.map((token): Tunnel["Attributes"] => ({ |
| 185 | tunnelId: t.id, |
| 186 | tunnelName: t.name ?? t.id, |
| 187 | accountTag: t.accountTag ?? undefined, |
| 188 | accountId, |
| 189 | createdAt: t.createdAt ?? undefined, |
| 190 | deletedAt: t.deletedAt ?? undefined, |
| 191 | configSrc: ((t as { configSrc?: "cloudflare" | "local" | null }).configSrc ?? |
| 192 | "cloudflare") as "cloudflare" | "local", |
| 193 | token: Redacted.make(token), |
| 194 | })), |
| 195 | Effect.catchTag("TunnelTokenNotFound", () => Effect.undefined), |
| 196 | ), |
| 197 | { concurrency: 10 }, |
| 198 | ); |
| 199 | return rows.filter((row): row is Tunnel["Attributes"] => row !== undefined); |
| 200 | }), |
| 201 | diff: Effect.fn(function* ({ id, olds = {}, news, output }) { |
| 202 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 203 | if (!isResolved(news)) return undefined; |
| 204 | if ((output?.accountId ?? accountId) !== accountId) { |
| 205 | return { action: "replace" } as const; |
| 206 | } |
| 207 | const oldName = output?.tunnelName ?? (yield* createTunnelName(id, olds.name)); |
| 208 | // Auto-generated names are engine-owned: the deployed name stays |
| 209 | // authoritative even if the generator would name this id differently |
| 210 | // today. Only an explicit user-provided name can force a replace. |
| 211 | const name = news.name ?? oldName; |
| 212 | if (name !== oldName) { |
| 213 | return { action: "replace" } as const; |
| 214 | } |
| 215 | const oldSecret = olds.tunnelSecret ? Redacted.value(olds.tunnelSecret) : undefined; |
| 216 | const newSecret = news.tunnelSecret ? Redacted.value(news.tunnelSecret) : undefined; |
| 217 | if (oldSecret !== newSecret) { |
| 218 | return { action: "replace" } as const; |
| 219 | } |
| 220 | if ((olds.configSrc ?? "cloudflare") !== (news.configSrc ?? "cloudflare")) { |
| 221 | return { action: "replace" } as const; |
| 222 | } |
| 223 | }), |
| 224 | reconcile: Effect.fn(function* ({ id, news = {}, output }) { |
| 225 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 226 | // Prefer the deployed name: regenerating would target a different |
| 227 | // resource if the generator's output for this id ever drifts. |
| 228 | const name = yield* createTunnelName(id, news.name ?? output?.tunnelName); |
| 229 | const configSrc = news.configSrc ?? output?.configSrc ?? "cloudflare"; |
| 230 | const tunnelSecret = news.tunnelSecret ? Redacted.value(news.tunnelSecret) : undefined; |
| 231 | const acct = output?.accountId ?? accountId; |
| 232 | |
| 233 | // Observe — re-fetch the cached tunnel; fall back to a name |
| 234 | // lookup so we recover from out-of-band deletes or partial |
| 235 | // state-persistence failures. |
| 236 | let observed: |
| 237 | | { |
| 238 | id?: string | null; |
| 239 | name?: string | null; |
| 240 | accountTag?: string | null; |
| 241 | createdAt?: string | null; |
| 242 | deletedAt?: string | null; |
| 243 | } |
| 244 | | undefined; |
| 245 | if (output?.tunnelId) { |
| 246 | observed = yield* zeroTrust |
| 247 | .getTunnelCloudflared({ |
| 248 | accountId: acct, |
| 249 | tunnelId: output.tunnelId, |
| 250 | }) |
| 251 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 252 | } |
| 253 | if (!observed) { |
| 254 | observed = yield* findTunnelByName(name); |
| 255 | } |
| 256 | |
| 257 | // Ensure — create if missing. Cloudflare rejects a duplicate |
| 258 | // name with a generic error; tolerate by adopting the |
| 259 | // existing tunnel when the caller opted into adoption. |
| 260 | if (!observed || !observed.id) { |
| 261 | observed = yield* zeroTrust |
| 262 | .createTunnelCloudflared({ |
| 263 | accountId: acct, |
| 264 | name, |
| 265 | configSrc, |
| 266 | tunnelSecret, |
| 267 | }) |
| 268 | .pipe( |
| 269 | Effect.catch((err) => |
| 270 | Effect.gen(function* () { |
| 271 | if (!news.adopt) return yield* err; |
| 272 | const existing = yield* findTunnelByName(name); |
| 273 | if (!existing || !existing.id) { |
| 274 | return yield* err; |
| 275 | } |
| 276 | return existing; |
| 277 | }), |
| 278 | ), |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | // Sync — when the tunnel is managed in Cloudflare, push the |
| 283 | // desired ingress + originRequest configuration. The PUT is |
| 284 | // idempotent: equal payloads converge to the same state, so we |
| 285 | // always push to apply drift. |
| 286 | if (configSrc !== "local") { |
| 287 | yield* writeConfiguration(observed.id!, news.ingress, news.originRequest); |
| 288 | } |
| 289 | |
| 290 | const token = yield* zeroTrust.getTunnelCloudflaredToken({ |
| 291 | accountId: acct, |
| 292 | tunnelId: observed.id!, |
| 293 | }); |
| 294 | |
| 295 | return { |
| 296 | tunnelId: observed.id!, |
| 297 | tunnelName: observed.name ?? name, |
| 298 | accountTag: observed.accountTag ?? undefined, |
| 299 | accountId: acct, |
| 300 | createdAt: observed.createdAt ?? undefined, |
| 301 | deletedAt: observed.deletedAt ?? undefined, |
| 302 | configSrc, |
| 303 | token: Redacted.make(token), |
| 304 | }; |
| 305 | }), |
| 306 | delete: Effect.fn(function* ({ output }) { |
| 307 | // Observe — an already-(soft-)deleted tunnel means nothing to do. |
| 308 | const observed = yield* zeroTrust |
| 309 | .getTunnelCloudflared({ |
| 310 | accountId: output.accountId, |
| 311 | tunnelId: output.tunnelId, |
| 312 | }) |
| 313 | .pipe(Effect.catchTag("TunnelNotFound", () => Effect.undefined)); |
| 314 | if (observed === undefined || observed.deletedAt != null) return; |
| 315 | // Delete — sibling route/config deletions propagate asynchronously and |
| 316 | // Cloudflare transiently rejects the tunnel delete while they drain. |
| 317 | // Retry bounded and let a persistent failure surface: a swallowed |
| 318 | // failure silently leaks the tunnel. |
| 319 | yield* zeroTrust |
| 320 | .deleteTunnelCloudflared({ |
| 321 | accountId: output.accountId, |
| 322 | tunnelId: output.tunnelId, |
| 323 | }) |
| 324 | .pipe( |
| 325 | Effect.retry({ |
| 326 | schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(10)]), |
| 327 | }), |
| 328 | ); |
| 329 | }), |
| 330 | read: Effect.fn(function* ({ id, output, olds }) { |
| 331 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 332 | if (output?.tunnelId) { |
| 333 | return yield* zeroTrust |
| 334 | .getTunnelCloudflared({ |
| 335 | accountId: output.accountId, |
| 336 | tunnelId: output.tunnelId, |
| 337 | }) |
| 338 | .pipe( |
| 339 | Effect.flatMap((t) => |
| 340 | zeroTrust |
| 341 | .getTunnelCloudflaredToken({ |
| 342 | accountId: output.accountId, |
| 343 | tunnelId: output.tunnelId, |
| 344 | }) |
| 345 | .pipe( |
| 346 | Effect.map((token) => ({ |
| 347 | tunnelId: t.id ?? output.tunnelId, |
| 348 | tunnelName: t.name ?? output.tunnelName, |
| 349 | accountTag: t.accountTag ?? output.accountTag, |
| 350 | accountId: output.accountId, |
| 351 | createdAt: t.createdAt ?? output.createdAt, |
| 352 | deletedAt: t.deletedAt ?? output.deletedAt, |
| 353 | configSrc: ((t as { configSrc?: "cloudflare" | "local" | null }).configSrc ?? |
| 354 | output.configSrc ?? |
| 355 | "cloudflare") as "cloudflare" | "local", |
| 356 | token: Redacted.make(token), |
| 357 | })), |
| 358 | ), |
| 359 | ), |
| 360 | Effect.orElseSucceed(() => undefined), |
| 361 | ); |
| 362 | } |
| 363 | const name = yield* createTunnelName(id, olds?.name); |
| 364 | const existing = yield* findTunnelByName(name); |
| 365 | if (!existing || !existing.id) return undefined; |
| 366 | |
| 367 | const token = yield* zeroTrust.getTunnelCloudflaredToken({ |
| 368 | accountId, |
| 369 | tunnelId: existing.id, |
| 370 | }); |
| 371 | return { |
| 372 | tunnelId: existing.id, |
| 373 | tunnelName: existing.name ?? name, |
| 374 | accountTag: existing.accountTag ?? undefined, |
| 375 | accountId, |
| 376 | createdAt: existing.createdAt ?? undefined, |
| 377 | deletedAt: existing.deletedAt ?? undefined, |
| 378 | configSrc: ((existing as { configSrc?: "cloudflare" | "local" | null }).configSrc ?? |
| 379 | "cloudflare") as "cloudflare" | "local", |
| 380 | token: Redacted.make(token), |
| 381 | }; |
| 382 | }), |
| 383 | }); |
| 384 | |
| 385 | const createTunnelName = (id: string, name: string | undefined) => |
| 386 | Effect.gen(function* () { |
| 387 | if (name) return name; |
| 388 | return yield* createPhysicalName({ id }); |
| 389 | }); |
| 390 | |
| 391 | const writeConfiguration = ( |
| 392 | tunnelId: string, |
| 393 | ingress: Tunnel.IngressRule[] | undefined, |
| 394 | originRequest: Tunnel.OriginRequestConfig | undefined, |
| 395 | ) => |
| 396 | Effect.gen(function* () { |
| 397 | if (!ingress && !originRequest) return; |
| 398 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 399 | yield* zeroTrust.putTunnelCloudflaredConfiguration({ |
| 400 | accountId, |
| 401 | tunnelId, |
| 402 | config: { ingress, originRequest }, |
| 403 | }); |
| 404 | }); |
| 405 | |
| 406 | const findTunnelByName = Effect.fn(function* (name: string) { |
| 407 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 408 | return yield* zeroTrust.listTunnels |
| 409 | .items({ |
| 410 | accountId, |
| 411 | name, |
| 412 | isDeleted: false, |
| 413 | tunTypes: ["cfd_tunnel"], |
| 414 | }) |
| 415 | .pipe( |
| 416 | Stream.filter((t) => t.name === name && !t.deletedAt), |
| 417 | Stream.runHead, |
| 418 | Effect.map(Option.getOrUndefined), |
| 419 | ); |
| 420 | }); |