The best way to control Claude Code, Codex and more from any computer or phone

main
ts 406 lines 14.4 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import * as Stream from "effect/Stream";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9
10 /**
11 * Per-origin connection tuning the cloudflared daemon applies when
12 * forwarding requests upstream. Re-exports distilled's shape so every
13 * server-recognised knob (TLS verify, keep-alives, HTTP/2, Access-protected
14 * origin, etc.) is available without re-declaring the struct.
15 */
16 export type OriginRequest = NonNullable<
17 NonNullable<zeroTrust.PutTunnelCloudflaredConfigurationRequest["config"]>["originRequest"]
18 >;
19
20 /**
21 * One ingress rule in the tunnel's routing list. cloudflared matches each
22 * incoming connection against these in order; the first match wins.
23 *
24 * Omit `hostname` (and `path`) on the *final* rule to make it the catch-all
25 * — by convention a `service: "http_status:404"` entry. If you don't author
26 * a catch-all, the provider appends one for you so the tunnel config stays
27 * valid (Cloudflare rejects PUTs whose last rule has a hostname).
28 */
29 export interface IngressRule {
30 /**
31 * Public or private hostname this rule matches. Omit for the catch-all
32 * rule (which must be last in the list).
33 */
34 hostname?: string;
35 /**
36 * Upstream URL or pseudo-service. Common values:
37 * - `http://service.namespace.svc.cluster.local:80` — forward to a K8s Service
38 * - `https://10.0.0.5:8443` — forward to a private IP
39 * - `http_status:404` — return a literal status code (used for the catch-all)
40 * - `hello_world` — cloudflared's built-in test page
41 */
42 service: string;
43 /**
44 * Optional URL path prefix the rule matches. When omitted, the rule
45 * matches every path for the hostname.
46 */
47 path?: string;
48 /**
49 * Per-rule origin tuning. Merges with (and overrides) the resource-level
50 * `originRequest` defaults.
51 */
52 originRequest?: OriginRequest;
53 }
54
55 export interface ConfigurationProps {
56 /**
57 * UUID of the `cfd_tunnel` this configuration belongs to. Each tunnel
58 * has a single configuration document, so this both identifies the
59 * resource and gates lifecycle operations.
60 *
61 * Stable — changing the tunnel triggers replacement.
62 *
63 * Declared as plain `string` (not `string`) so it is statically
64 * knowable inside `diff` for the replacement check.
65 */
66 tunnelId: string;
67 /**
68 * Ordered ingress rules. cloudflared evaluates them top-down and the
69 * first match wins. The catch-all rule is appended automatically — do
70 * not include a trailing `{ service: "http_status:404" }` here unless
71 * you want it to land mid-list.
72 */
73 ingress: ReadonlyArray<IngressRule>;
74 /**
75 * Default origin-request tuning applied to every rule that doesn't set
76 * its own. Equivalent to the top-level `originRequest` block in a
77 * cloudflared YAML config.
78 */
79 originRequest?: OriginRequest;
80 /**
81 * Service for the auto-appended catch-all rule. cloudflared requires
82 * the last rule to omit `hostname`; this controls what it returns when
83 * no earlier rule matches.
84 *
85 * @default "http_status:404"
86 */
87 catchAllService?: string;
88 }
89
90 export interface ConfigurationAttributes {
91 /** The tunnel this configuration belongs to. */
92 tunnelId: string;
93 /** Account that owns the tunnel. */
94 accountId: string;
95 /**
96 * Cloudflare-side config version. Bumped on every PUT, even when the
97 * payload is unchanged — surface it so downstream consumers can wait
98 * on a specific revision if needed.
99 */
100 version: number | undefined;
101 }
102
103 export type Configuration = Resource<
104 "Cloudflare.Tunnel.Configuration",
105 ConfigurationProps,
106 ConfigurationAttributes,
107 never,
108 Providers
109 >;
110
111 /**
112 * Routing configuration for a remotely-managed Cloudflare Tunnel.
113 *
114 * Cloudflare exposes the cfd_tunnel configuration as a single PUT-style
115 * document per tunnel — `ingress` rules in order, plus optional default
116 * `originRequest` settings. This resource owns that document; it is the
117 * declarative equivalent of editing a tunnel's Public Hostname or Private
118 * Hostname rules in the Zero Trust dashboard.
119 *
120 * The catch-all rule (final ingress entry with no hostname) is appended
121 * automatically — Cloudflare rejects PUTs whose last rule has a hostname,
122 * and forgetting it is a common foot-gun. Override the auto-appended
123 * service via {@link ConfigurationProps.catchAllService}.
124 * ### Routing a private hostname through a tunnel
125 * **Example:** Map an internal admin UI through a Cloudflare Tunnel to a K8s Service
126 * ```typescript
127 * yield* Cloudflare.Tunnel.Configuration("AdminIngress", {
128 * tunnelId: tunnel.tunnelId,
129 * ingress: [
130 * {
131 * hostname: "cluster-admin.microagi",
132 * service: "http://research-ui.admin.svc.cluster.local:80",
133 * },
134 * ],
135 * });
136 * ```
137 *
138 * ### Multiple hostnames + custom catch-all
139 * **Example:** Two services on one tunnel, returning 503 for unknown hosts
140 * ```typescript
141 * yield* Cloudflare.Tunnel.Configuration("Ingress", {
142 * tunnelId: tunnel.tunnelId,
143 * ingress: [
144 * { hostname: "ui.internal", service: "http://ui.app.svc.cluster.local:80" },
145 * { hostname: "api.internal", service: "http://api.app.svc.cluster.local:8080" },
146 * ],
147 * catchAllService: "http_status:503",
148 * });
149 * ```
150 *
151 * @resource
152 * @product Tunnels
153 * @category Cloudflare One (Zero Trust)
154 */
155 export const Configuration = Resource<Configuration>("Cloudflare.Tunnel.Configuration");
156
157 // ---------------------------------------------------------------------------
158 // Observed-state types
159 // ---------------------------------------------------------------------------
160
161 interface ObservedIngressRule {
162 readonly hostname?: string;
163 readonly service?: string;
164 readonly path?: string;
165 readonly originRequest?: Record<string, unknown>;
166 }
167
168 interface ObservedConfig {
169 readonly ingress?: ReadonlyArray<ObservedIngressRule>;
170 readonly originRequest?: Record<string, unknown>;
171 readonly version?: number;
172 }
173
174 const undef = <T>(v: T | null | undefined): T | undefined => (v == null ? undefined : v);
175
176 const stripNulls = (v: unknown): unknown => {
177 if (Array.isArray(v)) return v.map(stripNulls);
178 if (v !== null && typeof v === "object") {
179 const out: Record<string, unknown> = {};
180 for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
181 if (val === null || val === undefined) continue;
182 out[k] = stripNulls(val);
183 }
184 return out;
185 }
186 return v;
187 };
188
189 const narrowConfig = (raw: {
190 config?: {
191 ingress?: ReadonlyArray<{
192 hostname?: string | null;
193 service?: string;
194 path?: string | null;
195 originRequest?: Record<string, unknown> | null;
196 }> | null;
197 originRequest?: Record<string, unknown> | null;
198 } | null;
199 version?: number | null;
200 }): ObservedConfig => ({
201 ingress:
202 raw.config?.ingress == null
203 ? undefined
204 : raw.config.ingress.map((r) => ({
205 hostname: undef(r.hostname),
206 service: r.service,
207 path: undef(r.path),
208 originRequest: undef(r.originRequest),
209 })),
210 originRequest: undef(raw.config?.originRequest),
211 version: undef(raw.version),
212 });
213
214 // ---------------------------------------------------------------------------
215 // Body construction
216 // ---------------------------------------------------------------------------
217
218 const DEFAULT_CATCH_ALL_SERVICE = "http_status:404";
219
220 const buildIngress = (
221 rules: ReadonlyArray<IngressRule>,
222 catchAllService: string,
223 ): Array<IngressRule> => {
224 const out: Array<IngressRule> = [];
225 for (const r of rules) {
226 // Drop any catch-all the caller threaded into the middle — we always
227 // append exactly one trailing catch-all of our own, and a mid-list
228 // catch-all would short-circuit every following rule anyway.
229 if (r.hostname === undefined && r.path === undefined) continue;
230 out.push(r);
231 }
232 out.push({ service: catchAllService });
233 return out;
234 };
235
236 // ---------------------------------------------------------------------------
237 // Drift detection
238 //
239 // Cloudflare echoes back a config object with every optional field filled in
240 // (often as `null`). Strip nulls before comparing so a server-supplied
241 // `path: null` doesn't endlessly diff against an unset desired `path`.
242 // ---------------------------------------------------------------------------
243
244 const configsEqual = (
245 desiredIngress: ReadonlyArray<IngressRule>,
246 desiredOrigin: OriginRequest | undefined,
247 observed: ObservedConfig,
248 ): boolean => {
249 const left = stripNulls({
250 ingress: desiredIngress,
251 originRequest: desiredOrigin,
252 });
253 const right = stripNulls({
254 ingress: observed.ingress ?? [],
255 originRequest: observed.originRequest,
256 });
257 return JSON.stringify(left) === JSON.stringify(right);
258 };
259
260 // ---------------------------------------------------------------------------
261 // Provider
262 // ---------------------------------------------------------------------------
263
264 export const ConfigurationProvider = () =>
265 Provider.effect(
266 Configuration,
267 Effect.gen(function* () {
268 const env = yield* CloudflareEnvironment;
269
270 const getConfig = yield* zeroTrust.getTunnelCloudflaredConfiguration;
271 const putConfig = yield* zeroTrust.putTunnelCloudflaredConfiguration;
272
273 const observe = (accountId: string, tunnelId: string) =>
274 Effect.gen(function* () {
275 // A tunnel with no configuration yet surfaces as the tagged
276 // `TunnelConfigurationNotFound` (code 1055) — swallow into "missing".
277 const r = yield* getConfig({ accountId, tunnelId }).pipe(
278 Effect.catchTag("TunnelConfigurationNotFound", () => Effect.undefined),
279 );
280 if (r === undefined) return undefined;
281 return narrowConfig(r as Parameters<typeof narrowConfig>[0]);
282 });
283
284 return {
285 stables: ["tunnelId", "accountId"],
286
287 diff: Effect.fn(function* ({ olds = {}, news }) {
288 // tunnelId is statically declared as Input<string>; by reconcile
289 // time both sides resolve to strings. A change replaces because
290 // a tunnel's configuration is keyed by tunnelId in the URL.
291 const oldId = (olds as ConfigurationProps).tunnelId;
292 const newId = (news as ConfigurationProps).tunnelId;
293 if (typeof oldId === "string" && typeof newId === "string" && oldId !== newId) {
294 return { action: "replace" } as const;
295 }
296 }),
297
298 reconcile: Effect.fn(function* ({ news }) {
299 const { accountId } = yield* env;
300 // Inputs have been resolved to concrete strings by the Plan layer.
301 const tunnelId = news.tunnelId as string;
302 const catchAllService = news.catchAllService ?? DEFAULT_CATCH_ALL_SERVICE;
303 const desiredIngress = buildIngress(news.ingress, catchAllService);
304
305 // Observe — falls through to a PUT if the tunnel has no config yet.
306 let observed = yield* observe(accountId, tunnelId);
307
308 // Sync — skip the PUT entirely when observed equals desired.
309 if (
310 observed === undefined ||
311 !configsEqual(desiredIngress, news.originRequest, observed)
312 ) {
313 const updated = yield* putConfig({
314 accountId,
315 tunnelId,
316 config: {
317 ingress: desiredIngress.map((r) => ({
318 hostname: r.hostname,
319 service: r.service,
320 path: r.path,
321 originRequest: r.originRequest,
322 })),
323 originRequest: news.originRequest,
324 },
325 });
326 observed = narrowConfig(updated as Parameters<typeof narrowConfig>[0]);
327 }
328
329 return {
330 tunnelId,
331 accountId,
332 version: observed.version,
333 } satisfies ConfigurationAttributes;
334 }),
335
336 delete: Effect.fn(function* ({ output }) {
337 // Cloudflare's API has no DELETE for the configuration document —
338 // PUT the catch-all-only shape so the tunnel stops routing
339 // anything and idempotently converges.
340 yield* putConfig({
341 accountId: output.accountId,
342 tunnelId: output.tunnelId,
343 config: {
344 ingress: [{ service: DEFAULT_CATCH_ALL_SERVICE }],
345 },
346 }).pipe(Effect.catch(() => Effect.void));
347 }),
348
349 read: Effect.fn(function* ({ output }) {
350 if (!output) return undefined;
351 const observed = yield* observe(output.accountId, output.tunnelId);
352 if (observed === undefined) return undefined;
353 return {
354 tunnelId: output.tunnelId,
355 accountId: output.accountId,
356 version: observed.version,
357 } satisfies ConfigurationAttributes;
358 }),
359
360 // The configuration is a per-tunnel singleton with no account-wide
361 // enumeration API — fan out from the parent. Enumerate every
362 // (non-deleted) cfd_tunnel in the account, then read each tunnel's
363 // configuration document with bounded concurrency. Tunnels without a
364 // config (`TunnelConfigurationNotFound`, handled inside `observe`) are
365 // skipped, exactly mirroring `read`.
366 list: () =>
367 Effect.gen(function* () {
368 const { accountId } = yield* env;
369
370 const tunnelIds = yield* zeroTrust.listTunnelCloudflareds
371 .pages({ accountId, isDeleted: false })
372 .pipe(
373 Stream.runCollect,
374 Effect.map((chunk) =>
375 Array.from(chunk).flatMap((page) =>
376 (page.result ?? []).flatMap((t) =>
377 t.id != null && t.deletedAt == null ? [t.id] : [],
378 ),
379 ),
380 ),
381 );
382
383 const rows = yield* Effect.forEach(
384 tunnelIds,
385 (tunnelId) =>
386 observe(accountId, tunnelId).pipe(
387 Effect.map((observed) =>
388 observed === undefined
389 ? undefined
390 : ({
391 tunnelId,
392 accountId,
393 version: observed.version,
394 } satisfies ConfigurationAttributes),
395 ),
396 ),
397 { concurrency: 10 },
398 );
399
400 return rows.filter((row): row is ConfigurationAttributes => row !== undefined);
401 }),
402 };
403 }),
404 );
405
406 void Option.none;