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

main
ts 520 lines 18.2 KB
Raw
1 import * as spectrum from "@distilled.cloud/cloudflare/spectrum";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { listAllZones } from "../Zone/lookup.ts";
12
13 const TypeId = "Cloudflare.Spectrum.Application" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * How data travels from Cloudflare's edge to the origin. `direct` sends
18 * traffic straight to the origin; `http`/`https` apply HTTP(S) processing
19 * (Enterprise only).
20 */
21 export type TrafficType = "direct" | "http" | "https";
22
23 /**
24 * The type of TLS termination at the edge for a Spectrum application.
25 */
26 export type Tls = "off" | "flexible" | "full" | "strict";
27
28 /**
29 * PROXY Protocol mode for origin connections.
30 */
31 export type ProxyProtocol = "off" | "v1" | "v2" | "simple";
32
33 /**
34 * The edge DNS record Spectrum creates for the application — the hostname
35 * clients connect to. Must live inside the application's zone.
36 */
37 export interface Dns {
38 /**
39 * The fully-qualified edge hostname, e.g. `ssh.example.com`. Together
40 * with `protocol`, this is the user-visible identity of the application
41 * within a zone.
42 */
43 name: string;
44 /**
45 * The kind of edge DNS record Spectrum manages: `CNAME` (dynamic edge
46 * IPs) or `ADDRESS` (static BYOIP edge IPs, Enterprise only).
47 */
48 type: "CNAME" | "ADDRESS";
49 }
50
51 /**
52 * Origin lookup via DNS instead of fixed addresses. Requires `originPort`.
53 */
54 export interface OriginDns {
55 /**
56 * The hostname of the origin server.
57 */
58 name?: string;
59 /**
60 * TTL of the origin DNS lookup, in seconds.
61 */
62 ttl?: number;
63 /**
64 * The DNS record type to resolve: `A`, `AAAA`, `SRV`, or `""` to let
65 * Cloudflare pick.
66 */
67 type?: "" | "A" | "AAAA" | "SRV";
68 }
69
70 /**
71 * The anycast edge IP configuration for the application's hostname.
72 */
73 export interface EdgeIps {
74 /**
75 * `dynamic` (default) lets Cloudflare assign edge IPs; `static` pins the
76 * application to BYOIP addresses listed in `ips` (Enterprise only).
77 * @default "dynamic"
78 */
79 type?: "dynamic" | "static";
80 /**
81 * IP-version reachability of the dynamic edge IPs.
82 * @default "all"
83 */
84 connectivity?: "all" | "ipv4" | "ipv6";
85 /**
86 * Static BYOIP edge addresses (only with `type: "static"`).
87 */
88 ips?: string[];
89 }
90
91 export interface ApplicationProps {
92 /**
93 * Zone the application is created in. Stable — moving an application to
94 * a different zone triggers a replacement.
95 */
96 zoneId: string;
97 /**
98 * The edge DNS record (hostname + record type) for the application.
99 * Mutable — the PUT update accepts a new `dns`, but note `dns.name` +
100 * `protocol` is the identity used for cold-state recovery.
101 */
102 dns: Dns;
103 /**
104 * The edge port configuration, e.g. `"tcp/22"`, `"udp/53"`, or a range
105 * `"tcp/1000-2000"`. Arbitrary ports, ranges, and UDP require an
106 * Enterprise plan with Spectrum; Pro zones get `tcp/22` and `tcp/25565`.
107 */
108 protocol: string;
109 /**
110 * How traffic travels to the origin. `http`/`https` are Enterprise only.
111 * @default "direct"
112 */
113 trafficType?: TrafficType;
114 /**
115 * Fixed origin addresses, e.g. `["tcp://203.0.113.1:22"]`. Provide
116 * either `originDirect` or `originDns` + `originPort`.
117 */
118 originDirect?: string[];
119 /**
120 * Origin lookup via DNS. Must be combined with `originPort`.
121 */
122 originDns?: OriginDns;
123 /**
124 * The destination port at the origin (only with `originDns`). A range
125 * string (e.g. `"1000-2000"`) is Enterprise only.
126 */
127 originPort?: number | string;
128 /**
129 * TLS termination at the edge. Only meaningful for `http`/`https`
130 * traffic types — Cloudflare rejects the field on `direct` TCP apps, so
131 * leave it unset for those.
132 */
133 tls?: Tls;
134 /**
135 * Enables Argo Smart Routing (TCP + `direct` traffic type only).
136 * @default false
137 */
138 argoSmartRouting?: boolean;
139 /**
140 * Enables IP Access rules for this application (TCP only).
141 * @default false
142 */
143 ipFirewall?: boolean;
144 /**
145 * Enables PROXY Protocol to the origin.
146 * @default "off"
147 */
148 proxyProtocol?: ProxyProtocol;
149 /**
150 * The anycast edge IP configuration. Static BYOIP addresses are
151 * Enterprise only.
152 * @default { type: "dynamic", connectivity: "all" }
153 */
154 edgeIps?: EdgeIps;
155 /**
156 * UUID of a tunnel virtual network to route origin traffic through.
157 */
158 virtualNetworkId?: string;
159 }
160
161 export interface ApplicationAttributes {
162 /** Cloudflare-assigned identifier of the Spectrum application. */
163 appId: string;
164 /** Zone the application belongs to. */
165 zoneId: string;
166 /** The edge hostname clients connect to. */
167 dnsName: string;
168 /** The kind of edge DNS record (`CNAME` or `ADDRESS`). */
169 dnsType: "CNAME" | "ADDRESS";
170 /** The edge port configuration, e.g. `tcp/22`. */
171 protocol: string;
172 /** How traffic travels to the origin. */
173 trafficType: TrafficType;
174 /** Fixed origin addresses, if configured. */
175 originDirect: string[] | undefined;
176 /** Origin DNS lookup configuration, if configured. */
177 originDns: OriginDns | undefined;
178 /** The destination port at the origin, if configured. */
179 originPort: number | string | undefined;
180 /** TLS termination at the edge, if reported. */
181 tls: Tls | undefined;
182 /** Whether Argo Smart Routing is enabled. */
183 argoSmartRouting: boolean;
184 /** Whether IP Access rules are enabled. */
185 ipFirewall: boolean;
186 /** PROXY Protocol mode to the origin. */
187 proxyProtocol: ProxyProtocol;
188 /** ISO8601 creation timestamp. */
189 createdOn: string;
190 /** ISO8601 last-modified timestamp. */
191 modifiedOn: string;
192 }
193
194 export type Application = Resource<
195 TypeId,
196 ApplicationProps,
197 ApplicationAttributes,
198 never,
199 Providers
200 >;
201
202 /**
203 * A Cloudflare Spectrum application — DDoS protection and proxying for
204 * arbitrary TCP/UDP services (SSH, Minecraft, RDP, custom protocols), not
205 * just HTTP.
206 *
207 * An application is identified by its auto-assigned `appId`; its
208 * user-visible identity within a zone is the edge hostname (`dns.name`) +
209 * `protocol` pair. All configuration is mutable in place via PUT — only
210 * `zoneId` forces a replacement.
211 *
212 * Spectrum is plan-gated: Pro zones get SSH (`tcp/22`) and Minecraft
213 * (`tcp/25565`), Business adds RDP, and Enterprise unlocks arbitrary
214 * ports/ranges, UDP, static edge IPs, and PROXY Protocol. On unentitled
215 * zones every create fails with the typed `SpectrumProtocolNotAvailable`
216 * error.
217 *
218 * Safety: Spectrum applications carry no ownership markers. When there is
219 * no prior state, `read` scans the zone for an application with the same
220 * `dns.name` + `protocol` and reports it as `Unowned`, so the engine
221 * refuses to take it over unless `--adopt` (or `adopt(true)`) is set.
222 * ### Proxying SSH
223 * **Example:** SSH on a fixed origin address
224 * ```typescript
225 * const ssh = yield* Cloudflare.Spectrum.Application("Ssh", {
226 * zoneId: zone.zoneId,
227 * dns: { type: "CNAME", name: "ssh.example.com" },
228 * protocol: "tcp/22",
229 * originDirect: ["tcp://203.0.113.1:22"],
230 * });
231 * ```
232 *
233 * ### Origin via DNS
234 * **Example:** Resolve the origin by hostname
235 * ```typescript
236 * yield* Cloudflare.Spectrum.Application("Minecraft", {
237 * zoneId: zone.zoneId,
238 * dns: { type: "CNAME", name: "mc.example.com" },
239 * protocol: "tcp/25565",
240 * originDns: { name: "origin.example.com" },
241 * originPort: 25565,
242 * });
243 * ```
244 *
245 * ### Enterprise features
246 * **Example:** UDP with IP firewall and PROXY protocol
247 * ```typescript
248 * // Arbitrary ports/protocols, UDP, and proxyProtocol require an
249 * // Enterprise plan with Spectrum.
250 * yield* Cloudflare.Spectrum.Application("Dns", {
251 * zoneId: zone.zoneId,
252 * dns: { type: "CNAME", name: "dns.example.com" },
253 * protocol: "udp/53",
254 * originDirect: ["udp://203.0.113.1:53"],
255 * ipFirewall: true,
256 * proxyProtocol: "simple",
257 * });
258 * ```
259 *
260 * @see https://developers.cloudflare.com/spectrum/
261 *
262 * @resource
263 * @product Spectrum
264 * @category Network
265 */
266 export const Application = Resource<Application>(TypeId);
267
268 /**
269 * Returns true if the given value is a Application resource.
270 */
271 export const isApplication = (value: unknown): value is Application =>
272 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
273
274 export const ApplicationProvider = () =>
275 Provider.succeed(Application, {
276 stables: ["appId", "zoneId", "createdOn"],
277
278 diff: Effect.fn(function* ({ olds, news }) {
279 // `news` may still contain unresolved plan-time expressions — defer
280 // to the engine's default update logic until everything is concrete.
281 if (!isResolved(news)) return undefined;
282 // Everything is mutable through the PUT update except the zone the
283 // application lives in (a path parameter).
284 if (
285 typeof olds?.zoneId === "string" &&
286 typeof news.zoneId === "string" &&
287 olds.zoneId !== news.zoneId
288 ) {
289 return { action: "replace" } as const;
290 }
291 return undefined;
292 }),
293
294 read: Effect.fn(function* ({ output, olds }) {
295 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
296 if (zoneId === undefined) return undefined;
297
298 // Owned path: refresh by our persisted application id.
299 if (output?.appId) {
300 const observed = yield* getApp(zoneId, output.appId);
301 return observed ? toAttributes(observed, zoneId) : undefined;
302 }
303
304 // Adoption path: an application with this hostname + protocol may
305 // already exist in the zone. Spectrum apps carry no ownership
306 // markers, so we cannot prove we created it — brand it `Unowned` so
307 // the engine refuses to take over unless `adopt` is set.
308 const dnsName = output?.dnsName ?? olds?.dns.name;
309 const protocol = output?.protocol ?? olds?.protocol;
310 if (dnsName !== undefined && protocol !== undefined) {
311 const observed = yield* findByIdentity(zoneId, dnsName, protocol);
312 if (observed) return Unowned(toAttributes(observed, zoneId));
313 }
314 return undefined;
315 }),
316
317 reconcile: Effect.fn(function* ({ news, output }) {
318 // Inputs have been resolved to concrete strings by Plan.
319 const zoneId = news.zoneId as string;
320
321 // 1. Observe — the app id cached on `output` is a hint, not a
322 // guarantee: a missing application falls through to the identity
323 // scan and then to create.
324 let observed = output?.appId ? yield* getApp(zoneId, output.appId) : undefined;
325
326 // 2. Fall back to scanning the zone for a hostname + protocol match.
327 // Ownership has already been verified upstream — `read` reports
328 // existing applications as `Unowned` and the engine gates
329 // takeover behind the adopt policy before reconcile ever runs.
330 if (!observed) {
331 observed = yield* findByIdentity(zoneId, news.dns.name, news.protocol);
332 }
333
334 // 3. Ensure — create when missing.
335 if (!observed) {
336 const created = yield* spectrum.createApp({
337 zoneId,
338 ...toRequestBody(news),
339 });
340 return toAttributes(created, zoneId);
341 }
342
343 // 4. Sync — diff observed cloud state against desired; the update
344 // API is a PUT that requires the full body, so send everything,
345 // but skip the call entirely on a no-op.
346 if (!isDirty(observed, news)) {
347 return toAttributes(observed, zoneId);
348 }
349 const updated = yield* spectrum.updateApp({
350 zoneId,
351 appId: observed.id,
352 ...toRequestBody(news),
353 });
354 return toAttributes(updated, zoneId);
355 }),
356
357 delete: Effect.fn(function* ({ output }) {
358 // Deleting the app also removes the Spectrum-managed edge DNS
359 // record. An already-gone app answers with the typed
360 // `SpectrumAppNotFound` (Cloudflare code 10006) — idempotent.
361 yield* spectrum
362 .deleteApp({ zoneId: output.zoneId, appId: output.appId })
363 .pipe(Effect.catchTag("SpectrumAppNotFound", () => Effect.void));
364 }),
365
366 // Zone-scoped collection: Spectrum applications live inside a zone and
367 // are listed per-zone (`/zones/{zone_id}/spectrum/apps`). Enumerate every
368 // zone, exhaustively paginate each zone's apps, and hydrate into the same
369 // `Attributes` shape `read` returns. Zones without Spectrum entitlement
370 // reject the route with the typed `Forbidden` tag — skip them.
371 list: Effect.fn(function* () {
372 const { accountId } = yield* yield* CloudflareEnvironment;
373 const zones = yield* listAllZones(accountId);
374 const rows = yield* Effect.forEach(
375 zones,
376 (zone) =>
377 spectrum.listApps.pages({ zoneId: zone.id }).pipe(
378 Stream.runCollect,
379 Effect.map((chunk) =>
380 Array.from(chunk).flatMap((page) =>
381 (page.result ?? []).map((app) => toAttributes(app, zone.id)),
382 ),
383 ),
384 Effect.catchTag("Forbidden", () => Effect.succeed([] as ApplicationAttributes[])),
385 ),
386 { concurrency: 10 },
387 );
388 return rows.flat();
389 }),
390 });
391
392 // ---------------------------------------------------------------------------
393 // API helpers
394 // ---------------------------------------------------------------------------
395
396 type ObservedApp = spectrum.GetAppResponse;
397
398 /**
399 * Distilled types `getApp`/`listApps` results as a union whose second
400 * variant omits the optional configuration fields — normalize to a single
401 * partial shape.
402 */
403 type FullApp = Extract<ObservedApp, { trafficType: unknown }>;
404 type AnyApp = ObservedApp | spectrum.CreateAppResponse | spectrum.UpdateAppResponse;
405 const asFull = (app: AnyApp): Partial<FullApp> & AnyApp => app;
406
407 /**
408 * Read an application by id, mapping "gone" (`SpectrumAppNotFound`,
409 * Cloudflare error code 10006) to `undefined`.
410 */
411 const getApp = (zoneId: string, appId: string) =>
412 spectrum.getApp({ zoneId, appId }).pipe(
413 Effect.map((app): ObservedApp | undefined => app),
414 Effect.catchTag("SpectrumAppNotFound", () => Effect.undefined),
415 );
416
417 /**
418 * Find an application by exact `dns.name` + `protocol` within the zone —
419 * the pair is the application's user-visible identity.
420 */
421 const findByIdentity = (zoneId: string, dnsName: string, protocol: string) =>
422 spectrum.listApps.items({ zoneId }).pipe(
423 Stream.filter((app) => app.dns.name === dnsName && app.protocol === protocol),
424 Stream.take(1),
425 Stream.runCollect,
426 Effect.map((chunk): ObservedApp | undefined => Array.from(chunk)[0]),
427 );
428
429 /**
430 * The full PUT/POST body derived from the desired props. Optional fields
431 * the user did not set are omitted so the API applies its defaults — in
432 * particular `tls`, which Cloudflare rejects on `direct` TCP apps.
433 */
434 const toRequestBody = (news: ApplicationProps) => ({
435 dns: { name: news.dns.name, type: news.dns.type },
436 protocol: news.protocol,
437 trafficType: news.trafficType,
438 originDirect: news.originDirect,
439 originDns: news.originDns,
440 originPort: news.originPort,
441 tls: news.tls,
442 argoSmartRouting: news.argoSmartRouting,
443 ipFirewall: news.ipFirewall,
444 proxyProtocol: news.proxyProtocol,
445 edgeIps: news.edgeIps,
446 virtualNetworkId: news.virtualNetworkId as string | undefined,
447 });
448
449 /**
450 * Compare observed cloud state against the desired props. Fields the user
451 * left unset are only considered dirty when the observed value differs
452 * from the API default, so a no-op deploy skips the PUT entirely.
453 */
454 const isDirty = (observed: ObservedApp, news: ApplicationProps): boolean => {
455 const o = asFull(observed);
456 return (
457 o.dns.name !== news.dns.name ||
458 o.dns.type !== news.dns.type ||
459 o.protocol !== news.protocol ||
460 (o.trafficType ?? "direct") !== (news.trafficType ?? "direct") ||
461 !sameList(o.originDirect ?? [], news.originDirect ?? []) ||
462 (o.originDns?.name ?? undefined) !== news.originDns?.name ||
463 (o.originPort ?? undefined) !== news.originPort ||
464 (news.tls !== undefined && o.tls !== news.tls) ||
465 (o.argoSmartRouting ?? false) !== (news.argoSmartRouting ?? false) ||
466 (o.ipFirewall ?? false) !== (news.ipFirewall ?? false) ||
467 (o.proxyProtocol ?? "off") !== (news.proxyProtocol ?? "off") ||
468 (news.edgeIps !== undefined && edgeIpsDirty(o, news.edgeIps)) ||
469 (news.virtualNetworkId !== undefined &&
470 (o.virtualNetworkId ?? undefined) !== news.virtualNetworkId)
471 );
472 };
473
474 const edgeIpsDirty = (o: Partial<FullApp>, desired: EdgeIps): boolean => {
475 const observed = o.edgeIps ?? {};
476 const observedIps = "ips" in observed ? ((observed.ips ?? []) as readonly string[]) : [];
477 const observedConnectivity =
478 "connectivity" in observed ? (observed.connectivity ?? "all") : ("all" as const);
479 return (
480 (observed.type ?? "dynamic") !== (desired.type ?? "dynamic") ||
481 (desired.connectivity !== undefined && observedConnectivity !== desired.connectivity) ||
482 (desired.ips !== undefined && !sameList(observedIps, desired.ips))
483 );
484 };
485
486 const sameList = (observed: readonly string[], desired: readonly string[]) =>
487 observed.length === desired.length &&
488 [...observed].sort().join(",") === [...desired].sort().join(",");
489
490 const toAttributes = (
491 app: ObservedApp | spectrum.CreateAppResponse | spectrum.UpdateAppResponse,
492 zoneId: string,
493 ): ApplicationAttributes => {
494 const a = asFull(app);
495 return {
496 appId: a.id,
497 zoneId,
498 // Cloudflare always echoes both dns fields for a persisted app —
499 // distilled just types them as optional/nullable.
500 dnsName: a.dns.name ?? "",
501 dnsType: (a.dns.type ?? "CNAME") as "CNAME" | "ADDRESS",
502 protocol: a.protocol,
503 trafficType: (a.trafficType ?? "direct") as TrafficType,
504 originDirect: a.originDirect ? [...a.originDirect] : undefined,
505 originDns: a.originDns
506 ? {
507 name: a.originDns.name ?? undefined,
508 ttl: a.originDns.ttl ?? undefined,
509 type: (a.originDns.type ?? undefined) as OriginDns["type"] | undefined,
510 }
511 : undefined,
512 originPort: a.originPort ?? undefined,
513 tls: (a.tls ?? undefined) as Tls | undefined,
514 argoSmartRouting: a.argoSmartRouting ?? false,
515 ipFirewall: a.ipFirewall ?? false,
516 proxyProtocol: (a.proxyProtocol ?? "off") as ProxyProtocol,
517 createdOn: a.createdOn,
518 modifiedOn: a.modifiedOn,
519 };
520 };