@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, 04:45 UTC

main
ts 239 lines 7.61 KB
Raw
1 import * as magicTransit from "@distilled.cloud/cloudflare/magic-transit";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.MagicTransit.App" as const;
12 type TypeId = typeof TypeId;
13
14 export interface MagicAppProps {
15 /**
16 * Display name for the app.
17 */
18 name: string;
19 /**
20 * Category of the app, e.g. `"Collaboration"`.
21 */
22 type: string;
23 /**
24 * FQDNs to associate with traffic decisions.
25 */
26 hostnames?: string[];
27 /**
28 * IPv4 CIDRs to associate with traffic decisions. (IPv6 CIDRs are
29 * currently unsupported.)
30 */
31 ipSubnets?: string[];
32 }
33
34 export interface MagicAppAttributes {
35 /** Magic account app ID. */
36 appId: string;
37 /** The Cloudflare account the app belongs to. */
38 accountId: string;
39 /** Display name for the app. */
40 name: string;
41 /** Category of the app. */
42 type: string;
43 /** FQDNs associated with traffic decisions, if set. */
44 hostnames: string[] | undefined;
45 /** IPv4 CIDRs associated with traffic decisions, if set. */
46 ipSubnets: string[] | undefined;
47 }
48
49 export type MagicApp = Resource<TypeId, MagicAppProps, MagicAppAttributes, never, Providers>;
50
51 /**
52 * A custom Magic WAN app — a named set of hostnames and/or IP subnets used
53 * for traffic steering and policy decisions, complementing Cloudflare's
54 * managed app definitions.
55 *
56 * Requires a Magic WAN subscription — accounts without it receive a typed
57 * `MagicWanUnauthorized` error (Cloudflare code 1025) or `MagicWanNotEnabled`
58 * (code 1101, "forbidden: feature not enabled").
59 *
60 * All properties are mutable in place via PATCH.
61 * ### Creating an app
62 * **Example:** App matching hostnames
63 * ```typescript
64 * const app = yield* Cloudflare.MagicTransit.MagicApp("crm", {
65 * name: "Internal CRM",
66 * type: "Business",
67 * hostnames: ["crm.example.com"],
68 * });
69 * ```
70 *
71 * **Example:** App matching IP subnets
72 * ```typescript
73 * const app = yield* Cloudflare.MagicTransit.MagicApp("voip", {
74 * name: "VoIP",
75 * type: "Communication",
76 * ipSubnets: ["192.0.2.0/24", "198.51.100.0/24"],
77 * });
78 * ```
79 *
80 * @see https://developers.cloudflare.com/magic-wan/configuration/apps/
81 *
82 * @resource
83 * @product Magic Transit
84 * @category Network
85 */
86 export const MagicApp = Resource<MagicApp>(TypeId);
87
88 /**
89 * Returns true if the given value is a MagicApp resource.
90 */
91 export const isMagicApp = (value: unknown): value is MagicApp =>
92 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
93
94 export const MagicAppProvider = () =>
95 Provider.succeed(MagicApp, {
96 stables: ["appId", "accountId"],
97
98 read: Effect.fn(function* ({ output, olds }) {
99 const { accountId } = yield* yield* CloudflareEnvironment;
100 const acct = output?.accountId ?? accountId;
101
102 if (output?.appId) {
103 const observed = yield* getApp(acct, output.appId);
104 if (observed) return toAttributes(observed, acct);
105 }
106 // Cold read — match by name. Apps carry no ownership markers;
107 // report as Unowned so takeover is gated behind the adopt policy.
108 const name = output?.name ?? olds?.name;
109 if (name) {
110 const observed = yield* findByName(acct, name);
111 if (observed) return Unowned(toAttributes(observed, acct));
112 }
113 return undefined;
114 }),
115
116 reconcile: Effect.fn(function* ({ news, output }) {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118
119 // Observe — there is no getApp endpoint; scan the list by cached id
120 // first, then by name.
121 let observed = output?.appId ? yield* getApp(accountId, output.appId) : undefined;
122 if (!observed) {
123 observed = yield* findByName(accountId, news.name);
124 }
125
126 // Ensure — create when missing.
127 if (!observed) {
128 const created = yield* magicTransit.createApp({
129 accountId,
130 name: news.name,
131 type: news.type,
132 hostnames: news.hostnames,
133 ipSubnets: news.ipSubnets,
134 });
135 return toAttributes(created, accountId);
136 }
137
138 // Sync — diff observed cloud state against desired; PATCH only on a
139 // real delta.
140 const dirty =
141 (observed.name ?? undefined) !== news.name ||
142 (observed.type ?? undefined) !== news.type ||
143 (news.hostnames !== undefined && !sameList(observed.hostnames, news.hostnames)) ||
144 (news.ipSubnets !== undefined && !sameList(observed.ipSubnets, news.ipSubnets));
145 if (dirty) {
146 const updated = yield* magicTransit.patchApp({
147 accountId,
148 accountAppId: observed.accountAppId,
149 name: news.name,
150 type: news.type,
151 hostnames: news.hostnames,
152 ipSubnets: news.ipSubnets,
153 });
154 observed = updated;
155 }
156
157 return toAttributes(observed, accountId);
158 }),
159
160 delete: Effect.fn(function* ({ output }) {
161 yield* magicTransit
162 .deleteApp({
163 accountId: output.accountId,
164 accountAppId: output.appId,
165 })
166 .pipe(Effect.catchTag("AppNotFound", () => Effect.void));
167 }),
168
169 // Account collection — exhaustively paginate the account-scoped apps list
170 // and hydrate each account app into the `read` Attributes shape. Magic WAN
171 // is entitlement-gated; unentitled accounts reject with a typed error, in
172 // which case there are no apps to enumerate → [].
173 list: Effect.fn(function* () {
174 const { accountId } = yield* yield* CloudflareEnvironment;
175 return yield* magicTransit.listApps.pages({ accountId }).pipe(
176 Stream.runCollect,
177 Effect.map((chunk) =>
178 Array.from(chunk).flatMap((page) =>
179 (page.result ?? []).filter(isAccountApp).map((app) => toAttributes(app, accountId)),
180 ),
181 ),
182 Effect.catchTag(["MagicWanUnauthorized", "MagicWanNotEnabled", "Forbidden"], () =>
183 Effect.succeed([] as MagicAppAttributes[]),
184 ),
185 );
186 }),
187 });
188
189 interface ObservedApp {
190 accountAppId: string;
191 name?: string | null;
192 type?: string | null;
193 hostnames?: string[] | null;
194 ipSubnets?: string[] | null;
195 }
196
197 const isAccountApp = (app: magicTransit.ListAppsResponse["result"][number]): app is ObservedApp =>
198 "accountAppId" in app;
199
200 /**
201 * Read an account app by id via the list endpoint (there is no getApp).
202 */
203 const getApp = (accountId: string, appId: string) =>
204 magicTransit
205 .listApps({ accountId })
206 .pipe(
207 Effect.map((r): ObservedApp | undefined =>
208 r.result.filter(isAccountApp).find((app) => app.accountAppId === appId),
209 ),
210 );
211
212 /**
213 * Find an account app by exact name. Names are not enforced unique; pick
214 * the first match deterministically by id.
215 */
216 const findByName = (accountId: string, name: string) =>
217 magicTransit.listApps({ accountId }).pipe(
218 Effect.map((r): ObservedApp | undefined =>
219 r.result
220 .filter(isAccountApp)
221 .filter((app) => app.name === name)
222 .sort((a, b) => a.accountAppId.localeCompare(b.accountAppId))
223 .at(0),
224 ),
225 );
226
227 const sameList = (
228 a: readonly string[] | null | undefined,
229 b: readonly string[] | undefined,
230 ): boolean => [...(a ?? [])].sort().join(",") === [...(b ?? [])].sort().join(",");
231
232 const toAttributes = (app: ObservedApp, accountId: string): MagicAppAttributes => ({
233 appId: app.accountAppId,
234 accountId,
235 name: app.name ?? "",
236 type: app.type ?? "",
237 hostnames: app.hostnames ?? undefined,
238 ipSubnets: app.ipSubnets ?? undefined,
239 });