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

main
ts 297 lines 10.8 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { Unowned } from "alchemy/AdoptPolicy";
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 Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.Tunnel.VirtualNetwork" as const;
14 type TypeId = typeof TypeId;
15
16 export interface VirtualNetworkProps {
17 /**
18 * User-friendly name for the virtual network. Names are unique per
19 * account, which makes the name the resource's identity during adoption
20 * and state recovery. If omitted, a unique name is generated from the
21 * app, stage, and logical ID.
22 *
23 * @default ${app}-${stage}-${id}
24 */
25 name?: string;
26 /**
27 * Optional remark describing the virtual network. Mutable — patched
28 * in place.
29 *
30 * @default ""
31 */
32 comment?: string;
33 /**
34 * If `true`, this virtual network is the default for the account. Only
35 * one default exists per account — promoting a network demotes the
36 * previous default. Mutable — patched in place.
37 *
38 * @default false
39 */
40 isDefaultNetwork?: boolean;
41 }
42
43 export interface VirtualNetworkAttributes {
44 /** UUID of the virtual network, assigned by Cloudflare. */
45 virtualNetworkId: string;
46 /** Cloudflare account that owns the virtual network. */
47 accountId: string;
48 /** User-friendly name of the virtual network. */
49 name: string;
50 /** Remark describing the virtual network. */
51 comment: string;
52 /** Whether this virtual network is the account default. */
53 isDefaultNetwork: boolean;
54 /** RFC 3339 timestamp of when the virtual network was created. */
55 createdAt: string;
56 }
57
58 export type VirtualNetwork = Resource<
59 TypeId,
60 VirtualNetworkProps,
61 VirtualNetworkAttributes,
62 never,
63 Providers
64 >;
65
66 /**
67 * A Cloudflare Zero Trust Virtual Network — an isolated routing namespace
68 * for Cloudflare Tunnel private networks.
69 *
70 * Virtual networks let you run overlapping CIDR ranges side by side: each
71 * {@link Route} can target a `virtualNetworkId`, and WARP clients
72 * switch between virtual networks to choose which copy of `10.0.0.0/8`
73 * they see. Every account starts with a single `default` virtual network.
74 *
75 * Name and comment are mutable in place. Deleting a virtual network
76 * requires that no routes reference it — express that relationship by
77 * passing `vnet.virtualNetworkId` into your `Route`s so destroy
78 * ordering is correct.
79 * ### Creating a Virtual Network
80 * **Example:** Basic virtual network
81 * ```typescript
82 * const vnet = yield* Cloudflare.Tunnel.VirtualNetwork("Staging", {
83 * comment: "staging private network",
84 * });
85 * ```
86 *
87 * **Example:** Route a tunnel CIDR through the virtual network
88 * ```typescript
89 * const tunnel = yield* Cloudflare.Tunnel.Tunnel("MyTunnel");
90 * yield* Cloudflare.Tunnel.Route("StagingNet", {
91 * tunnelId: tunnel.tunnelId,
92 * network: "10.4.0.0/16",
93 * virtualNetworkId: vnet.virtualNetworkId,
94 * });
95 * ```
96 *
97 * ### Default network
98 * **Example:** Promote a virtual network to the account default
99 * ```typescript
100 * // Only one default per account — promoting demotes the previous one.
101 * const vnet = yield* Cloudflare.Tunnel.VirtualNetwork("Primary", {
102 * isDefaultNetwork: true,
103 * });
104 * ```
105 *
106 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/private-net/cloudflared/tunnel-virtual-networks/
107 *
108 * @resource
109 * @product Tunnels
110 * @category Cloudflare One (Zero Trust)
111 */
112 export const VirtualNetwork = Resource<VirtualNetwork>(TypeId);
113
114 /**
115 * Returns true if the given value is a VirtualNetwork resource.
116 */
117 export const isVirtualNetwork = (value: unknown): value is VirtualNetwork =>
118 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
119
120 export const VirtualNetworkProvider = () =>
121 Provider.succeed(VirtualNetwork, {
122 stables: ["virtualNetworkId", "accountId", "createdAt"],
123
124 diff: Effect.fn(function* ({ output }) {
125 const { accountId } = yield* yield* CloudflareEnvironment;
126 if ((output?.accountId ?? accountId) !== accountId) {
127 return { action: "replace" } as const;
128 }
129 // name / comment / isDefaultNetwork all converge via PATCH.
130 return undefined;
131 }),
132
133 read: Effect.fn(function* ({ id, output, olds }) {
134 const { accountId } = yield* yield* CloudflareEnvironment;
135 const acct = output?.accountId ?? accountId;
136
137 // Owned path — refresh by the cached id.
138 if (output?.virtualNetworkId) {
139 const observed = yield* getVnet(acct, output.virtualNetworkId);
140 if (observed) return toAttributes(observed, acct);
141 }
142
143 // Cold read — names are unique per account, so an exact name match
144 // is the resource's identity. Virtual networks carry no ownership
145 // markers, so report the match as Unowned to gate adoption.
146 const name = yield* resolveName(id, olds?.name ?? output?.name);
147 const match = yield* findByName(acct, name);
148 if (match) return Unowned(toAttributes(match, acct));
149 return undefined;
150 }),
151
152 reconcile: Effect.fn(function* ({ id, news, output }) {
153 const { accountId } = yield* yield* CloudflareEnvironment;
154 const name = yield* resolveName(id, news.name);
155
156 // 1. Observe — the cached id is a hint, not a guarantee.
157 let observed = output?.virtualNetworkId
158 ? yield* getVnet(accountId, output.virtualNetworkId)
159 : undefined;
160 if (!observed) {
161 observed = yield* findByName(accountId, name);
162 }
163
164 // 2. Ensure — create when missing. Names are unique per account, so
165 // a racing create surfaces as VirtualNetworkConflict (code 1014):
166 // converge by re-reading the network that won the race.
167 if (!observed) {
168 const created = yield* zeroTrust
169 .createNetworkVirtualNetwork({
170 accountId,
171 name,
172 comment: news.comment,
173 isDefaultNetwork: news.isDefaultNetwork,
174 })
175 .pipe(
176 Effect.catchTag("VirtualNetworkConflict", (error) =>
177 findByName(accountId, name).pipe(
178 Effect.flatMap((existing) =>
179 existing ? Effect.succeed(existing) : Effect.fail(error),
180 ),
181 ),
182 ),
183 );
184 observed = created;
185 }
186
187 // 3. Sync — diff observed cloud state against desired and PATCH only
188 // the delta; skip the call entirely on a no-op. `isDefaultNetwork`
189 // is never patched to false here — demotion happens implicitly
190 // when another network is promoted (Cloudflare rejects an explicit
191 // demote of the only default).
192 const desired = {
193 name,
194 comment: news.comment ?? observed.comment,
195 isDefaultNetwork: news.isDefaultNetwork ?? observed.isDefaultNetwork,
196 };
197 const dirty =
198 observed.name !== desired.name ||
199 observed.comment !== desired.comment ||
200 observed.isDefaultNetwork !== desired.isDefaultNetwork;
201 if (dirty) {
202 observed = yield* zeroTrust.patchNetworkVirtualNetwork({
203 accountId,
204 virtualNetworkId: observed.id,
205 name: desired.name,
206 comment: desired.comment,
207 // Only send the promote; never an explicit demote.
208 ...(desired.isDefaultNetwork && !observed.isDefaultNetwork
209 ? { isDefaultNetwork: true }
210 : {}),
211 });
212 }
213
214 return toAttributes(observed, accountId);
215 }),
216
217 delete: Effect.fn(function* ({ output }) {
218 // Deleting a vnet with routes still attached fails — routes that
219 // reference `virtualNetworkId` as an Input get correct destroy
220 // ordering, so by the time we run the routes are gone. A missing
221 // vnet (VirtualNetworkNotFound, code 1046) means we're done.
222 yield* zeroTrust
223 .deleteNetworkVirtualNetwork({
224 accountId: output.accountId,
225 virtualNetworkId: output.virtualNetworkId,
226 })
227 .pipe(Effect.catchTag("VirtualNetworkNotFound", () => Effect.void));
228 }),
229
230 // Account-scoped collection: virtual networks are listed per account.
231 // Exhaustively paginate and filter out soft-deleted networks to match
232 // `read`/`findByName`, hydrating each into the `read` Attributes shape.
233 list: Effect.fn(function* () {
234 const { accountId } = yield* yield* CloudflareEnvironment;
235 return yield* zeroTrust.listNetworkVirtualNetworks
236 .pages({ accountId, isDeleted: false })
237 .pipe(
238 Stream.runCollect,
239 Effect.map((chunk) =>
240 Array.from(chunk).flatMap((page) =>
241 (page.result ?? [])
242 .filter((v) => !v.deletedAt)
243 // The account's default virtual network can't be deleted
244 // ("it is the default virtual network"); never enumerate it
245 // for account-wide teardown.
246 .filter((v) => !v.isDefaultNetwork)
247 .map((v): VirtualNetworkAttributes => ({
248 virtualNetworkId: v.id,
249 accountId,
250 name: v.name,
251 comment: v.comment,
252 isDefaultNetwork: v.isDefaultNetwork,
253 createdAt: v.createdAt,
254 })),
255 ),
256 ),
257 );
258 }),
259 });
260
261 type ObservedVnet = zeroTrust.GetNetworkVirtualNetworkResponse;
262
263 /**
264 * Read a virtual network by id, mapping "gone" (`VirtualNetworkNotFound`,
265 * Cloudflare error code 1046) and soft-deleted networks to `undefined`.
266 */
267 const getVnet = (accountId: string, virtualNetworkId: string) =>
268 zeroTrust.getNetworkVirtualNetwork({ accountId, virtualNetworkId }).pipe(
269 Effect.map((v): ObservedVnet | undefined => (v.deletedAt ? undefined : v)),
270 Effect.catchTag("VirtualNetworkNotFound", () => Effect.undefined),
271 );
272
273 /**
274 * Find a live virtual network by exact name. Names are unique per account
275 * so at most one live network can match.
276 */
277 const findByName = (accountId: string, name: string) =>
278 zeroTrust.listNetworkVirtualNetworks.items({ accountId, name, isDeleted: false }).pipe(
279 Stream.filter((v): v is ObservedVnet => v.name === name && !v.deletedAt),
280 Stream.runHead,
281 Effect.map(Option.getOrUndefined),
282 );
283
284 const resolveName = (id: string, name: string | undefined) =>
285 Effect.gen(function* () {
286 if (name) return name;
287 return yield* createPhysicalName({ id, lowercase: true });
288 });
289
290 const toAttributes = (vnet: ObservedVnet, accountId: string): VirtualNetworkAttributes => ({
291 virtualNetworkId: vnet.id,
292 accountId,
293 name: vnet.name,
294 comment: vnet.comment,
295 isDefaultNetwork: vnet.isDefaultNetwork,
296 createdAt: vnet.createdAt,
297 });