@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 455 lines 15.8 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 * 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 Redacted from "effect/Redacted";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.MagicTransit.GreTunnel" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Health-check configuration for a Magic Transit tunnel.
17 */
18 export interface MagicTunnelHealthCheck {
19 /**
20 * Whether tunnel health checks are enabled.
21 * @default true
22 */
23 enabled?: boolean;
24 /**
25 * Direction of the health check: `unidirectional` (default for Magic
26 * Transit) probes only Cloudflare-to-customer, `bidirectional` probes
27 * both directions.
28 */
29 direction?: "unidirectional" | "bidirectional";
30 /**
31 * Rate at which health checks are sent.
32 * @default "mid"
33 */
34 rate?: "low" | "mid" | "high";
35 /**
36 * Health-check type: `reply` (default) expects ICMP replies, `request`
37 * sends ICMP requests only.
38 */
39 type?: "reply" | "request";
40 /**
41 * The customer IP the health check targets. Defaults to
42 * `customer_gre_endpoint` when omitted.
43 */
44 target?: string;
45 }
46
47 /**
48 * BGP configuration for a Magic Transit tunnel.
49 */
50 export interface MagicTunnelBgp {
51 /**
52 * ASN used on the customer end of the BGP session.
53 */
54 customerAsn: number;
55 /**
56 * Prefixes advertised in addition to the account's Magic prefixes.
57 */
58 extraPrefixes?: string[];
59 /**
60 * MD5 key to use for session authentication. Write-only.
61 */
62 md5Key?: Redacted.Redacted<string>;
63 }
64
65 export interface GreTunnelProps {
66 /**
67 * The name of the tunnel. Cannot contain spaces or special characters,
68 * must be 15 characters or less, and cannot share a name with another GRE
69 * tunnel. Immutable in practice — changing it triggers a replacement.
70 */
71 name: string;
72 /**
73 * The IP address assigned to the Cloudflare side of the GRE tunnel (a
74 * Cloudflare anycast IP allocated to the account).
75 */
76 cloudflareGreEndpoint: string;
77 /**
78 * The IP address assigned to the customer side of the GRE tunnel.
79 */
80 customerGreEndpoint: string;
81 /**
82 * A 31-bit prefix (/31 in CIDR notation) from RFC1918 private space; one
83 * host for each side of the tunnel.
84 */
85 interfaceAddress: string;
86 /**
87 * A /127 IPv6 prefix from within the account's `virtual_subnet6` space.
88 */
89 interfaceAddress6?: string;
90 /**
91 * An optional description of the GRE tunnel.
92 */
93 description?: string;
94 /**
95 * Time To Live (TTL) in number of hops of the GRE tunnel.
96 * @default 64
97 */
98 ttl?: number;
99 /**
100 * Maximum Transmission Unit (MTU) in bytes for the GRE tunnel. Minimum
101 * value is 576.
102 * @default 1476
103 */
104 mtu?: number;
105 /**
106 * Tunnel health-check configuration.
107 */
108 healthCheck?: MagicTunnelHealthCheck;
109 /**
110 * BGP configuration. The update API cannot change BGP settings —
111 * changing this triggers a replacement.
112 */
113 bgp?: MagicTunnelBgp;
114 /**
115 * True if automatic stateful return routing should be enabled. Requires
116 * the `coupler_integration` account flag.
117 * @default false
118 */
119 automaticReturnRouting?: boolean;
120 }
121
122 export interface GreTunnelAttributes {
123 /** Cloudflare-assigned identifier of the GRE tunnel. */
124 tunnelId: string;
125 /** The Cloudflare account the tunnel belongs to. */
126 accountId: string;
127 /** The name of the tunnel. */
128 name: string;
129 /** The IP address on the Cloudflare side of the tunnel. */
130 cloudflareGreEndpoint: string;
131 /** The IP address on the customer side of the tunnel. */
132 customerGreEndpoint: string;
133 /** The /31 interface address of the tunnel. */
134 interfaceAddress: string;
135 /** The /127 IPv6 interface address, if configured. */
136 interfaceAddress6: string | undefined;
137 /** The tunnel description, if set. */
138 description: string | undefined;
139 /** Time To Live (TTL) in number of hops. */
140 ttl: number | undefined;
141 /** Maximum Transmission Unit (MTU) in bytes. */
142 mtu: number | undefined;
143 /** ISO8601 creation timestamp. */
144 createdOn: string | undefined;
145 /** ISO8601 last-modified timestamp. */
146 modifiedOn: string | undefined;
147 }
148
149 export type GreTunnel = Resource<TypeId, GreTunnelProps, GreTunnelAttributes, never, Providers>;
150
151 /**
152 * A Magic Transit / Magic WAN GRE tunnel between Cloudflare and a customer
153 * router.
154 *
155 * Requires a Magic Transit or Magic WAN subscription on the account —
156 * accounts that are not onboarded receive a typed
157 * `MagicTransitNotOnboarded` error (Cloudflare code 1012).
158 *
159 * The tunnel `name` is its routing identity (unique, ≤15 chars) — changing
160 * it triggers a replacement, as does changing `bgp` (the update API cannot
161 * modify BGP settings). Everything else is updated in place via PUT.
162 * ### Creating a GRE tunnel
163 * **Example:** Basic tunnel
164 * ```typescript
165 * const tunnel = yield* Cloudflare.MagicTransit.GreTunnel("office", {
166 * name: "office-gre-1",
167 * cloudflareGreEndpoint: "203.0.113.1",
168 * customerGreEndpoint: "198.51.100.1",
169 * interfaceAddress: "10.213.0.8/31",
170 * });
171 * ```
172 *
173 * **Example:** Tunnel with health checks and MTU
174 * ```typescript
175 * const tunnel = yield* Cloudflare.MagicTransit.GreTunnel("office", {
176 * name: "office-gre-1",
177 * cloudflareGreEndpoint: "203.0.113.1",
178 * customerGreEndpoint: "198.51.100.1",
179 * interfaceAddress: "10.213.0.8/31",
180 * mtu: 1476,
181 * ttl: 64,
182 * healthCheck: { enabled: true, rate: "mid", type: "reply" },
183 * });
184 * ```
185 *
186 * ### Routing traffic over the tunnel
187 * **Example:** Static route via the tunnel interface
188 * ```typescript
189 * yield* Cloudflare.MagicTransit.MagicStaticRoute("office-route", {
190 * prefix: "10.100.0.0/24",
191 * nexthop: "10.213.0.9",
192 * priority: 100,
193 * });
194 * ```
195 *
196 * @see https://developers.cloudflare.com/magic-transit/
197 *
198 * @resource
199 * @product Magic Transit
200 * @category Network
201 */
202 export const GreTunnel = Resource<GreTunnel>(TypeId);
203
204 /**
205 * Returns true if the given value is a GreTunnel resource.
206 */
207 export const isGreTunnel = (value: unknown): value is GreTunnel =>
208 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
209
210 export const GreTunnelProvider = () =>
211 Provider.succeed(GreTunnel, {
212 stables: ["tunnelId", "accountId", "createdOn"],
213
214 diff: Effect.fn(function* ({ olds, news }) {
215 if (!isResolved(news)) return undefined;
216 if (olds === undefined) return undefined;
217 // The tunnel name is its routing identity; renames are rejected.
218 if (olds.name !== news.name) return { action: "replace" } as const;
219 // The update API has no `bgp` field — BGP changes require recreate.
220 if (!sameBgp(olds.bgp, news.bgp)) return { action: "replace" } as const;
221 return undefined;
222 }),
223
224 read: Effect.fn(function* ({ output, olds }) {
225 const { accountId } = yield* yield* CloudflareEnvironment;
226 const acct = output?.accountId ?? accountId;
227
228 if (output?.tunnelId) {
229 const observed = yield* getTunnel(acct, output.tunnelId);
230 if (observed) return toAttributes(observed, acct);
231 }
232 // Cold read — tunnel names are unique per account, so an exact name
233 // match identifies the tunnel. Tunnels carry no ownership markers;
234 // report as Unowned so takeover is gated behind the adopt policy.
235 const name = output?.name ?? olds?.name;
236 if (name) {
237 const observed = yield* findByName(acct, name);
238 if (observed) return Unowned(toAttributes(observed, acct));
239 }
240 return undefined;
241 }),
242
243 reconcile: Effect.fn(function* ({ news, output }) {
244 const { accountId } = yield* yield* CloudflareEnvironment;
245
246 // Observe — the id on `output` is a hint; fall through to the
247 // unique-name lookup when it is gone.
248 let observed = output?.tunnelId ? yield* getTunnel(accountId, output.tunnelId) : undefined;
249 if (!observed) {
250 observed = yield* findByName(accountId, news.name);
251 }
252
253 // Ensure — create when missing.
254 if (!observed) {
255 const created = yield* magicTransit.createGreTunnel({
256 accountId,
257 xMagicNewHcTarget: true,
258 name: news.name,
259 cloudflareGreEndpoint: news.cloudflareGreEndpoint,
260 customerGreEndpoint: news.customerGreEndpoint,
261 interfaceAddress: news.interfaceAddress,
262 interfaceAddress6: news.interfaceAddress6,
263 description: news.description,
264 ttl: news.ttl,
265 mtu: news.mtu,
266 automaticReturnRouting: news.automaticReturnRouting,
267 bgp: news.bgp
268 ? {
269 customerAsn: news.bgp.customerAsn,
270 extraPrefixes: news.bgp.extraPrefixes,
271 md5Key: news.bgp.md5Key ? Redacted.value(news.bgp.md5Key) : undefined,
272 }
273 : undefined,
274 healthCheck: news.healthCheck
275 ? {
276 enabled: news.healthCheck.enabled,
277 target: news.healthCheck.target ? { saved: news.healthCheck.target } : undefined,
278 }
279 : undefined,
280 });
281 observed = created;
282 }
283
284 // Sync — diff observed cloud state against desired; the update API
285 // is a full PUT, so send everything, but skip the call on a no-op.
286 // This also converges health-check fields the create API does not
287 // accept (direction/rate/type).
288 if (dirty(observed, news)) {
289 const updated = yield* magicTransit.updateGreTunnel({
290 accountId,
291 greTunnelId: observed.id,
292 xMagicNewHcTarget: true,
293 name: news.name,
294 cloudflareGreEndpoint: news.cloudflareGreEndpoint,
295 customerGreEndpoint: news.customerGreEndpoint,
296 interfaceAddress: news.interfaceAddress,
297 interfaceAddress6: news.interfaceAddress6,
298 description: news.description,
299 ttl: news.ttl,
300 mtu: news.mtu,
301 automaticReturnRouting: news.automaticReturnRouting,
302 healthCheck: news.healthCheck
303 ? {
304 enabled: news.healthCheck.enabled,
305 direction: news.healthCheck.direction,
306 rate: news.healthCheck.rate,
307 type: news.healthCheck.type,
308 target: news.healthCheck.target ? { saved: news.healthCheck.target } : undefined,
309 }
310 : undefined,
311 });
312 if (updated.modifiedGreTunnel) {
313 observed = updated.modifiedGreTunnel;
314 } else {
315 // Defensive: re-read when the PUT response omits the tunnel.
316 observed = (yield* getTunnel(accountId, observed.id)) ?? observed;
317 }
318 }
319
320 return toAttributes(observed, accountId);
321 }),
322
323 delete: Effect.fn(function* ({ output }) {
324 yield* magicTransit
325 .deleteGreTunnel({
326 accountId: output.accountId,
327 greTunnelId: output.tunnelId,
328 xMagicNewHcTarget: true,
329 })
330 .pipe(Effect.catchTag("GreTunnelNotFound", () => Effect.void));
331 }),
332
333 // Account-scoped collection. `listGreTunnels` returns the full set in one
334 // (non-paginated) call, so there is nothing to paginate. Accounts without
335 // a Magic Transit subscription reject with the typed
336 // `MagicTransitNotOnboarded` tag (code 1012) — and, depending on token
337 // scope, a typed `Forbidden` (403). Both mean the account cannot enumerate
338 // Magic Transit, so treat them as non-listable → [].
339 list: Effect.fn(function* () {
340 const { accountId } = yield* yield* CloudflareEnvironment;
341 return yield* magicTransit.listGreTunnels({ accountId, xMagicNewHcTarget: true }).pipe(
342 Effect.map((r): GreTunnelAttributes[] =>
343 (r.greTunnels ?? []).map((tunnel) => toAttributes(tunnel, accountId)),
344 ),
345 Effect.catchTag(["MagicTransitNotOnboarded", "Forbidden"], () =>
346 Effect.succeed<GreTunnelAttributes[]>([]),
347 ),
348 );
349 }),
350 });
351
352 interface ObservedGreTunnel {
353 id: string;
354 name: string;
355 cloudflareGreEndpoint: string;
356 customerGreEndpoint: string;
357 interfaceAddress: string;
358 interfaceAddress6?: string | null;
359 description?: string | null;
360 ttl?: number | null;
361 mtu?: number | null;
362 healthCheck?: {
363 direction?: string | null;
364 enabled?: boolean | null;
365 rate?: string | null;
366 target?: { effective?: string | null; saved?: string | null } | string | null;
367 type?: string | null;
368 } | null;
369 createdOn?: string | null;
370 modifiedOn?: string | null;
371 }
372
373 /**
374 * Read a tunnel by id, mapping "gone" (`GreTunnelNotFound`, Cloudflare
375 * error code 1029) to `undefined`.
376 */
377 const getTunnel = (accountId: string, greTunnelId: string) =>
378 magicTransit.getGreTunnel({ accountId, greTunnelId, xMagicNewHcTarget: true }).pipe(
379 Effect.map((r): ObservedGreTunnel | undefined => r.greTunnel ?? undefined),
380 Effect.catchTag("GreTunnelNotFound", () => Effect.undefined),
381 );
382
383 /**
384 * Find a tunnel by exact name. Names are unique per account, so at most
385 * one tunnel can match.
386 */
387 const findByName = (accountId: string, name: string) =>
388 magicTransit
389 .listGreTunnels({ accountId, xMagicNewHcTarget: true })
390 .pipe(
391 Effect.map((r): ObservedGreTunnel | undefined =>
392 (r.greTunnels ?? []).find((t) => t.name === name),
393 ),
394 );
395
396 const observedHealthTarget = (
397 healthCheck: ObservedGreTunnel["healthCheck"],
398 ): string | undefined => {
399 const target = healthCheck?.target;
400 if (typeof target === "string") return target;
401 return target?.saved ?? undefined;
402 };
403
404 const dirty = (observed: ObservedGreTunnel, news: GreTunnelProps): boolean =>
405 observed.cloudflareGreEndpoint !== news.cloudflareGreEndpoint ||
406 observed.customerGreEndpoint !== news.customerGreEndpoint ||
407 observed.interfaceAddress !== news.interfaceAddress ||
408 (news.interfaceAddress6 !== undefined &&
409 (observed.interfaceAddress6 ?? undefined) !== news.interfaceAddress6) ||
410 (news.description !== undefined && (observed.description ?? undefined) !== news.description) ||
411 (news.ttl !== undefined && (observed.ttl ?? undefined) !== news.ttl) ||
412 (news.mtu !== undefined && (observed.mtu ?? undefined) !== news.mtu) ||
413 healthCheckDirty(observed, news.healthCheck);
414
415 const healthCheckDirty = (
416 observed: ObservedGreTunnel,
417 desired: MagicTunnelHealthCheck | undefined,
418 ): boolean => {
419 if (desired === undefined) return false;
420 const hc = observed.healthCheck ?? {};
421 return (
422 (desired.enabled !== undefined && (hc.enabled ?? undefined) !== desired.enabled) ||
423 (desired.direction !== undefined && (hc.direction ?? undefined) !== desired.direction) ||
424 (desired.rate !== undefined && (hc.rate ?? undefined) !== desired.rate) ||
425 (desired.type !== undefined && (hc.type ?? undefined) !== desired.type) ||
426 (desired.target !== undefined && observedHealthTarget(hc) !== desired.target)
427 );
428 };
429
430 const sameBgp = (a: MagicTunnelBgp | undefined, b: MagicTunnelBgp | undefined): boolean => {
431 if (a === undefined && b === undefined) return true;
432 if (a === undefined || b === undefined) return false;
433 const aKey = a.md5Key ? Redacted.value(a.md5Key) : undefined;
434 const bKey = b.md5Key ? Redacted.value(b.md5Key) : undefined;
435 return (
436 a.customerAsn === b.customerAsn &&
437 aKey === bKey &&
438 (a.extraPrefixes ?? []).join(",") === (b.extraPrefixes ?? []).join(",")
439 );
440 };
441
442 const toAttributes = (tunnel: ObservedGreTunnel, accountId: string): GreTunnelAttributes => ({
443 tunnelId: tunnel.id,
444 accountId,
445 name: tunnel.name,
446 cloudflareGreEndpoint: tunnel.cloudflareGreEndpoint,
447 customerGreEndpoint: tunnel.customerGreEndpoint,
448 interfaceAddress: tunnel.interfaceAddress,
449 interfaceAddress6: tunnel.interfaceAddress6 ?? undefined,
450 description: tunnel.description ?? undefined,
451 ttl: tunnel.ttl ?? undefined,
452 mtu: tunnel.mtu ?? undefined,
453 createdOn: tunnel.createdOn ?? undefined,
454 modifiedOn: tunnel.modifiedOn ?? undefined,
455 });