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

main
ts 442 lines 14.6 KB
Raw
1 import * as magicTransit from "@distilled.cloud/cloudflare/magic-transit";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Predicate from "effect/Predicate";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 export class SiteLanUnexpectedResponse extends Data.TaggedError("SiteLanUnexpectedResponse")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 const TypeId = "Cloudflare.MagicTransit.SiteLan" as const;
20 type TypeId = typeof TypeId;
21
22 /**
23 * NAT configuration for a Magic WAN site LAN.
24 */
25 export interface MagicSiteLanNat {
26 /** A valid CIDR notation representing an IP range. */
27 staticPrefix?: string;
28 }
29
30 /**
31 * A subnet routed behind a Magic WAN site LAN.
32 */
33 export interface MagicSiteLanRoutedSubnet {
34 /** A valid IPv4 address for the subnet's next hop. */
35 nextHop: string;
36 /** A valid CIDR notation representing an IP range. */
37 prefix: string;
38 /** Optional NAT configuration for the routed subnet. */
39 nat?: MagicSiteLanNat;
40 }
41
42 /**
43 * Static addressing configuration for a Magic WAN site LAN. If the site is
44 * not in high availability mode this is optional (DHCP is used when
45 * omitted); in HA mode it is required along with a secondary address.
46 */
47 export interface MagicSiteLanStaticAddressing {
48 /** A valid CIDR notation representing the LAN address. */
49 address: string;
50 /** Secondary address, required when the site is in HA mode. */
51 secondaryAddress?: string;
52 /** Virtual address shared by HA connector pairs. */
53 virtualAddress?: string;
54 /** DHCP relay configuration. */
55 dhcpRelay?: {
56 /** List of DHCP server addresses. */
57 serverAddresses?: string[];
58 };
59 /** DHCP server configuration. */
60 dhcpServer?: {
61 /** End of the DHCP address pool. */
62 dhcpPoolEnd?: string;
63 /** Start of the DHCP address pool. */
64 dhcpPoolStart?: string;
65 /** A single DNS server address. */
66 dnsServer?: string;
67 /** DNS server addresses. */
68 dnsServers?: string[];
69 /** Mapping of MAC addresses to IP addresses. */
70 reservations?: Record<string, unknown>;
71 };
72 }
73
74 export interface MagicSiteLanProps {
75 /**
76 * The site this LAN belongs to. Changing it triggers a replacement.
77 */
78 siteId: string;
79 /**
80 * The physical port number on the connector this LAN is attached to.
81 */
82 physport: number;
83 /**
84 * The name of the LAN. If omitted, a unique name is generated from the
85 * app, stage, and logical ID.
86 * @default ${app}-${stage}-${id}
87 */
88 name?: string;
89 /**
90 * VLAN ID. Use zero for untagged.
91 * @default 0
92 */
93 vlanTag?: number;
94 /**
95 * Mark true to use this LAN for HA probing. Only works for sites with
96 * HA turned on; only one LAN can be the ha_link. Create-only — changing
97 * it triggers a replacement.
98 */
99 haLink?: boolean;
100 /**
101 * Mark true to use this LAN for source-based breakout traffic.
102 */
103 isBreakout?: boolean;
104 /**
105 * Mark true to use this LAN for source-based prioritized traffic.
106 */
107 isPrioritized?: boolean;
108 /**
109 * NAT configuration for the LAN.
110 */
111 nat?: MagicSiteLanNat;
112 /**
113 * Subnets routed behind this LAN.
114 */
115 routedSubnets?: MagicSiteLanRoutedSubnet[];
116 /**
117 * Static addressing configuration; omit to use DHCP.
118 */
119 staticAddressing?: MagicSiteLanStaticAddressing;
120 /**
121 * Bond identifier when the LAN is part of a link bond.
122 */
123 bondId?: number;
124 }
125
126 export interface MagicSiteLanAttributes {
127 /** Cloudflare-assigned identifier of the LAN. */
128 lanId: string;
129 /** The site the LAN belongs to. */
130 siteId: string;
131 /** The Cloudflare account the LAN belongs to. */
132 accountId: string;
133 /** The name of the LAN. */
134 name: string;
135 /** The physical port number. */
136 physport: number | undefined;
137 /** The VLAN ID (zero for untagged). */
138 vlanTag: number | undefined;
139 /** Whether this LAN is the HA probing link. */
140 haLink: boolean | undefined;
141 }
142
143 export type MagicSiteLan = Resource<
144 TypeId,
145 MagicSiteLanProps,
146 MagicSiteLanAttributes,
147 never,
148 Providers
149 >;
150
151 /**
152 * A LAN attached to a Magic WAN site — describes a local network segment
153 * behind a Magic WAN Connector port (VLAN, addressing, routed subnets,
154 * NAT).
155 *
156 * Requires a Magic WAN subscription — accounts without it receive a typed
157 * `MagicWanUnauthorized` error (Cloudflare code 1025) or `MagicWanNotEnabled`
158 * (code 1101, "forbidden: feature not enabled").
159 *
160 * `siteId` and `haLink` are create-only — changing either triggers a
161 * replacement. Everything else is updated in place.
162 * ### Creating a LAN
163 * **Example:** Untagged LAN with DHCP
164 * ```typescript
165 * const lan = yield* Cloudflare.MagicTransit.MagicSiteLan("hq-lan", {
166 * siteId: site.siteId,
167 * physport: 2,
168 * vlanTag: 0,
169 * });
170 * ```
171 *
172 * **Example:** LAN with static addressing and a routed subnet
173 * ```typescript
174 * const lan = yield* Cloudflare.MagicTransit.MagicSiteLan("hq-lan", {
175 * siteId: site.siteId,
176 * physport: 2,
177 * vlanTag: 10,
178 * staticAddressing: { address: "192.168.10.1/24" },
179 * routedSubnets: [
180 * { prefix: "10.10.0.0/24", nextHop: "192.168.10.254" },
181 * ],
182 * });
183 * ```
184 *
185 * @see https://developers.cloudflare.com/magic-wan/configuration/connector/
186 *
187 * @resource
188 * @product Magic Transit
189 * @category Network
190 */
191 export const MagicSiteLan = Resource<MagicSiteLan>(TypeId);
192
193 /**
194 * Returns true if the given value is a MagicSiteLan resource.
195 */
196 export const isMagicSiteLan = (value: unknown): value is MagicSiteLan =>
197 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
198
199 export const MagicSiteLanProvider = () =>
200 Provider.succeed(MagicSiteLan, {
201 stables: ["lanId", "siteId", "accountId"],
202
203 diff: Effect.fn(function* ({ olds, news }) {
204 if (!isResolved(news)) return undefined;
205 if (olds === undefined) return undefined;
206 // LANs cannot move between sites.
207 if (
208 typeof olds.siteId === "string" &&
209 typeof news.siteId === "string" &&
210 olds.siteId !== news.siteId
211 ) {
212 return { action: "replace" } as const;
213 }
214 // ha_link is create-only — the update API has no such field.
215 if ((olds.haLink ?? false) !== (news.haLink ?? false)) {
216 return { action: "replace" } as const;
217 }
218 return undefined;
219 }),
220
221 read: Effect.fn(function* ({ id, output, olds }) {
222 const { accountId } = yield* yield* CloudflareEnvironment;
223 const acct = output?.accountId ?? accountId;
224 const siteId = output?.siteId ?? (typeof olds?.siteId === "string" ? olds.siteId : undefined);
225 if (!siteId) return undefined;
226
227 if (output?.lanId) {
228 const observed = yield* getLan(acct, siteId, output.lanId);
229 if (observed) return toAttributes(observed, siteId, acct);
230 }
231 // Cold read — match the deterministic physical name. LANs carry no
232 // ownership markers; report as Unowned so takeover is gated behind
233 // the adopt policy.
234 const name = yield* createLanName(id, olds?.name);
235 const observed = yield* findByName(acct, siteId, name);
236 if (observed) return Unowned(toAttributes(observed, siteId, acct));
237 return undefined;
238 }),
239
240 reconcile: Effect.fn(function* ({ id, news, output }) {
241 const { accountId } = yield* yield* CloudflareEnvironment;
242 // Inputs have been resolved to concrete strings by Plan.
243 const siteId = news.siteId as string;
244 const name = yield* createLanName(id, news.name);
245
246 // Observe — the id on `output` is a hint; fall back to a name scan.
247 let observed = output?.lanId ? yield* getLan(accountId, siteId, output.lanId) : undefined;
248 if (!observed) {
249 observed = yield* findByName(accountId, siteId, name);
250 }
251
252 // Ensure — create when missing. The create API returns the site's
253 // LAN list; pick the created LAN by name.
254 if (!observed) {
255 const created = yield* magicTransit.createSiteLan({
256 accountId,
257 siteId,
258 name,
259 physport: news.physport,
260 vlanTag: news.vlanTag,
261 haLink: news.haLink,
262 isBreakout: news.isBreakout,
263 isPrioritized: news.isPrioritized,
264 nat: news.nat,
265 routedSubnets: news.routedSubnets,
266 staticAddressing: news.staticAddressing,
267 bondId: news.bondId,
268 });
269 observed = created.result.find((lan) => lan.name === name) ?? created.result.at(0);
270 if (!observed) {
271 // Defensive: converge via the list if the create response shape
272 // is unexpected.
273 observed = yield* findByName(accountId, siteId, name);
274 }
275 if (observed) return toAttributes(observed, siteId, accountId);
276 return yield* new SiteLanUnexpectedResponse({
277 message: `Magic WAN site LAN ${name} not visible after create`,
278 });
279 }
280
281 // Sync — the update API is a PUT; send the full desired state, but
282 // skip the call entirely on a no-op of the observable fields.
283 const dirty =
284 (observed.name ?? undefined) !== name ||
285 (observed.physport ?? undefined) !== news.physport ||
286 (news.vlanTag !== undefined && (observed.vlanTag ?? undefined) !== news.vlanTag) ||
287 (news.isBreakout !== undefined && (observed.isBreakout ?? false) !== news.isBreakout) ||
288 (news.isPrioritized !== undefined &&
289 (observed.isPrioritized ?? false) !== news.isPrioritized) ||
290 (news.nat !== undefined &&
291 (observed.nat?.staticPrefix ?? undefined) !== news.nat.staticPrefix) ||
292 (news.routedSubnets !== undefined &&
293 !sameRoutedSubnets(observed.routedSubnets, news.routedSubnets)) ||
294 (news.staticAddressing !== undefined &&
295 (observed.staticAddressing?.address ?? undefined) !== news.staticAddressing.address) ||
296 (news.bondId !== undefined && (observed.bondId ?? undefined) !== news.bondId);
297 if (dirty) {
298 const updated = yield* magicTransit.updateSiteLan({
299 accountId,
300 siteId,
301 lanId: observed.id!,
302 name,
303 physport: news.physport,
304 vlanTag: news.vlanTag,
305 isBreakout: news.isBreakout,
306 isPrioritized: news.isPrioritized,
307 nat: news.nat,
308 routedSubnets: news.routedSubnets,
309 staticAddressing: news.staticAddressing,
310 bondId: news.bondId,
311 });
312 observed = { ...updated, id: updated.id ?? observed.id };
313 }
314
315 return toAttributes(observed, siteId, accountId);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 yield* magicTransit
320 .deleteSiteLan({
321 accountId: output.accountId,
322 siteId: output.siteId,
323 lanId: output.lanId,
324 })
325 .pipe(Effect.catchTag("SiteLanNotFound", () => Effect.void));
326 }),
327
328 // LANs are sub-resources keyed by their parent Magic WAN site, which is
329 // not enumerable by LAN. Fan out: list every account-scoped site, then
330 // exhaustively paginate the LANs of each site (bounded concurrency) and
331 // hydrate into the same Attributes shape `read` returns. Accounts (or
332 // individual sites) without Magic WAN entitlement reject with the typed
333 // `MagicWanUnauthorized` (code 1025) or `MagicWanNotEnabled` (code 1101) — nothing to enumerate,
334 // so skip → [].
335 list: Effect.fn(function* () {
336 const { accountId } = yield* yield* CloudflareEnvironment;
337
338 const siteIds = yield* magicTransit.listSites.pages({ accountId }).pipe(
339 Stream.runCollect,
340 Effect.map((chunk) =>
341 Array.from(chunk).flatMap((page) =>
342 (page.result ?? [])
343 .map((site) => site.id)
344 .filter((id): id is string => typeof id === "string"),
345 ),
346 ),
347 Effect.catchTag(["MagicWanUnauthorized", "MagicWanNotEnabled"], () =>
348 Effect.succeed([] as string[]),
349 ),
350 );
351
352 const rows = yield* Effect.forEach(
353 siteIds,
354 (siteId) =>
355 magicTransit.listSiteLans.pages({ accountId, siteId }).pipe(
356 Stream.runCollect,
357 Effect.map((chunk) =>
358 Array.from(chunk).flatMap((page) =>
359 (page.result ?? []).map((lan) => toAttributes(lan, siteId, accountId)),
360 ),
361 ),
362 Effect.catchTag(["MagicWanUnauthorized", "MagicWanNotEnabled"], () =>
363 Effect.succeed([] as MagicSiteLanAttributes[]),
364 ),
365 ),
366 { concurrency: 10 },
367 );
368
369 return rows.flat();
370 }),
371 });
372
373 interface ObservedLan {
374 id?: string | null;
375 name?: string | null;
376 physport?: number | null;
377 vlanTag?: number | null;
378 haLink?: boolean | null;
379 isBreakout?: boolean | null;
380 isPrioritized?: boolean | null;
381 nat?: { staticPrefix?: string | null } | null;
382 routedSubnets?:
383 | {
384 nextHop: string;
385 prefix: string;
386 nat?: { staticPrefix?: string | null } | null;
387 }[]
388 | null;
389 staticAddressing?: { address: string } | null;
390 bondId?: number | null;
391 }
392
393 /**
394 * Read a LAN by id, mapping "gone" (`SiteLanNotFound`, HTTP 404) to
395 * `undefined`.
396 */
397 const getLan = (accountId: string, siteId: string, lanId: string) =>
398 magicTransit.getSiteLan({ accountId, siteId, lanId }).pipe(
399 Effect.map((lan): ObservedLan | undefined => lan),
400 Effect.catchTag("SiteLanNotFound", () => Effect.undefined),
401 );
402
403 /**
404 * Find a LAN by exact name within a site. Names are not enforced unique;
405 * pick the first match deterministically by id.
406 */
407 const findByName = (accountId: string, siteId: string, name: string) =>
408 magicTransit.listSiteLans({ accountId, siteId }).pipe(
409 Effect.map((r): ObservedLan | undefined =>
410 r.result
411 .filter((lan) => lan.name === name)
412 .sort((a, b) => (a.id ?? "").localeCompare(b.id ?? ""))
413 .at(0),
414 ),
415 );
416
417 const createLanName = (id: string, name: string | undefined) =>
418 Effect.gen(function* () {
419 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
420 });
421
422 const sameRoutedSubnets = (
423 observed: ObservedLan["routedSubnets"],
424 desired: MagicSiteLanRoutedSubnet[],
425 ): boolean => {
426 const key = (s: { prefix: string; nextHop: string }) => `${s.prefix}>${s.nextHop}`;
427 return [...(observed ?? [])].map(key).sort().join(",") === [...desired].map(key).sort().join(",");
428 };
429
430 const toAttributes = (
431 lan: ObservedLan,
432 siteId: string,
433 accountId: string,
434 ): MagicSiteLanAttributes => ({
435 lanId: lan.id ?? "",
436 siteId,
437 accountId,
438 name: lan.name ?? "",
439 physport: lan.physport ?? undefined,
440 vlanTag: lan.vlanTag ?? undefined,
441 haLink: lan.haLink ?? undefined,
442 });