@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 344 lines 11.1 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
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 Option from "effect/Option";
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
12 const TypeId = "Cloudflare.Access.InfrastructureTarget" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * IPv4/IPv6 address details for an infrastructure target. At least one
17 * of `ipv4` / `ipv6` must be provided.
18 */
19 export interface InfrastructureTargetIp {
20 /** IPv4 address of the target, optionally scoped to a virtual network. */
21 ipv4?: {
22 /** The IPv4 address (e.g. `10.0.0.5`). */
23 ipAddr: string;
24 /**
25 * Virtual network the address lives in. Defaults to the account's
26 * default virtual network.
27 */
28 virtualNetworkId?: string;
29 };
30 /** IPv6 address of the target, optionally scoped to a virtual network. */
31 ipv6?: {
32 /** The IPv6 address. */
33 ipAddr: string;
34 /**
35 * Virtual network the address lives in. Defaults to the account's
36 * default virtual network.
37 */
38 virtualNetworkId?: string;
39 };
40 }
41
42 export interface InfrastructureTargetProps {
43 /**
44 * Hostname identifying the target. Non-unique, case-insensitive, max
45 * 255 characters; supports dashes and periods, no spaces. Mutable —
46 * updated in place via PUT.
47 */
48 hostname: string;
49 /**
50 * The IPv4/IPv6 address that identifies where to reach the target. At
51 * least one of `ipv4` / `ipv6` is required. Mutable — updated in
52 * place via PUT.
53 */
54 ip: InfrastructureTargetIp;
55 }
56
57 export interface InfrastructureTargetAttributes {
58 /** UUID of the infrastructure target, assigned by Cloudflare. */
59 targetId: string;
60 /** Cloudflare account that owns the target. */
61 accountId: string;
62 /** Hostname identifying the target. */
63 hostname: string;
64 /** Resolved IPv4/IPv6 addresses of the target. */
65 ip: {
66 ipv4?: { ipAddr?: string; virtualNetworkId?: string };
67 ipv6?: { ipAddr?: string; virtualNetworkId?: string };
68 };
69 /** RFC 3339 timestamp of when the target was created. */
70 createdAt: string;
71 /** RFC 3339 timestamp of when the target was last modified. */
72 modifiedAt: string;
73 }
74
75 export type InfrastructureTarget = Resource<
76 TypeId,
77 InfrastructureTargetProps,
78 InfrastructureTargetAttributes,
79 never,
80 Providers
81 >;
82
83 /**
84 * A Cloudflare Access Infrastructure Target — a server (hostname +
85 * IPv4/IPv6 address) protected by Access for Infrastructure (SSH).
86 *
87 * Targets are referenced by infrastructure Access applications, which
88 * attach SSH access policies to them. Hostname and IP are both mutable
89 * in place; the target's identity is its Cloudflare-assigned UUID.
90 * ### Creating a Target
91 * **Example:** Basic IPv4 target
92 * ```typescript
93 * const target = yield* Cloudflare.Access.InfrastructureTarget("Bastion", {
94 * hostname: "bastion.internal",
95 * ip: { ipv4: { ipAddr: "10.0.0.5" } },
96 * });
97 * ```
98 *
99 * **Example:** Target scoped to a virtual network
100 * ```typescript
101 * const vnet = yield* Cloudflare.Tunnel.VirtualNetwork("Staging", {});
102 * const target = yield* Cloudflare.Access.InfrastructureTarget("DbHost", {
103 * hostname: "db.staging.internal",
104 * ip: {
105 * ipv4: {
106 * ipAddr: "10.4.0.10",
107 * virtualNetworkId: vnet.virtualNetworkId,
108 * },
109 * },
110 * });
111 * ```
112 *
113 * ### Updating
114 * **Example:** Re-point the target at a new address
115 * ```typescript
116 * // Hostname and IP update in place — same targetId, no replacement.
117 * const target = yield* Cloudflare.Access.InfrastructureTarget("Bastion", {
118 * hostname: "bastion.internal",
119 * ip: { ipv4: { ipAddr: "10.0.0.6" } },
120 * });
121 * ```
122 *
123 * @see https://developers.cloudflare.com/cloudflare-one/applications/non-http/infrastructure-apps/
124 *
125 * @resource
126 * @product Access
127 * @category Cloudflare One (Zero Trust)
128 */
129 export const InfrastructureTarget = Resource<InfrastructureTarget>(TypeId);
130
131 /**
132 * Returns true if the given value is an InfrastructureTarget resource.
133 */
134 export const isInfrastructureTarget = (value: unknown): value is InfrastructureTarget =>
135 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
136
137 export const InfrastructureTargetProvider = () =>
138 Provider.succeed(InfrastructureTarget, {
139 stables: ["targetId", "accountId", "createdAt"],
140
141 list: Effect.fn(function* () {
142 const { accountId } = yield* yield* CloudflareEnvironment;
143 return yield* zeroTrust.listAccessInfrastructureTargets.pages({ accountId }).pipe(
144 Stream.runCollect,
145 Effect.map((chunk) =>
146 Array.from(chunk).flatMap((page) =>
147 (page.result ?? []).map((t) => toAttributes(t, accountId)),
148 ),
149 ),
150 );
151 }),
152
153 diff: Effect.fn(function* ({ output }) {
154 const { accountId } = yield* yield* CloudflareEnvironment;
155 if ((output?.accountId ?? accountId) !== accountId) {
156 return { action: "replace" } as const;
157 }
158 // hostname / ip both converge via PUT.
159 return undefined;
160 }),
161
162 read: Effect.fn(function* ({ output, olds }) {
163 const { accountId } = yield* yield* CloudflareEnvironment;
164 const acct = output?.accountId ?? accountId;
165
166 // Owned path — refresh by the cached id.
167 if (output?.targetId) {
168 const observed = yield* getTarget(acct, output.targetId);
169 if (observed) return toAttributes(observed, acct);
170 }
171
172 // Cold read — hostnames are non-unique, so only an exact
173 // hostname + address match identifies the target. Targets carry no
174 // ownership markers, so gate adoption behind Unowned.
175 const hostname = olds?.hostname ?? output?.hostname;
176 if (!hostname) return undefined;
177 // `olds.ip` may be `undefined` when a `creating` row was persisted
178 // before upstream Outputs resolved — fall back to the output hint.
179 const desiredIp = olds?.ip !== undefined ? resolvedIp(olds.ip) : output?.ip;
180 const match = yield* findByIdentity(acct, hostname, desiredIp);
181 if (match) return Unowned(toAttributes(match, acct));
182 return undefined;
183 }),
184
185 reconcile: Effect.fn(function* ({ news, output }) {
186 const { accountId } = yield* yield* CloudflareEnvironment;
187 const desired = { hostname: news.hostname, ip: resolvedIp(news.ip) };
188
189 // 1. Observe — the cached id is a hint, not a guarantee.
190 let observed = output?.targetId ? yield* getTarget(accountId, output.targetId) : undefined;
191 if (!observed) {
192 observed = yield* findByIdentity(accountId, desired.hostname, desired.ip);
193 }
194
195 // 2. Ensure — create when missing.
196 if (!observed) {
197 observed = yield* zeroTrust.createAccessInfrastructureTarget({
198 accountId,
199 hostname: desired.hostname,
200 ip: desired.ip,
201 });
202 }
203
204 // 3. Sync — PUT the full desired state only when the observed
205 // hostname or addresses differ; skip the call on a no-op.
206 const dirty =
207 observed.hostname !== desired.hostname || !ipEquals(observedIp(observed), desired.ip);
208 if (dirty) {
209 observed = yield* zeroTrust.updateAccessInfrastructureTarget({
210 accountId,
211 targetId: observed.id,
212 hostname: desired.hostname,
213 ip: desired.ip,
214 });
215 }
216
217 return toAttributes(observed, accountId);
218 }),
219
220 delete: Effect.fn(function* ({ output }) {
221 // A missing target (404) means we're done.
222 yield* zeroTrust
223 .deleteAccessInfrastructureTarget({
224 accountId: output.accountId,
225 targetId: output.targetId,
226 })
227 .pipe(Effect.catchTag("TargetNotFound", () => Effect.void));
228 }),
229 });
230
231 type ObservedTarget = zeroTrust.GetAccessInfrastructureTargetResponse;
232
233 type ResolvedIp = {
234 ipv4?: { ipAddr?: string; virtualNetworkId?: string };
235 ipv6?: { ipAddr?: string; virtualNetworkId?: string };
236 };
237
238 /**
239 * Read a target by id, mapping "gone" (404) to `undefined`.
240 */
241 const getTarget = (accountId: string, targetId: string) =>
242 zeroTrust
243 .getAccessInfrastructureTarget({ accountId, targetId })
244 .pipe(Effect.catchTag("TargetNotFound", () => Effect.undefined));
245
246 /**
247 * Find a target by exact hostname + address match. Hostnames are
248 * non-unique, so the addresses disambiguate.
249 */
250 const findByIdentity = (accountId: string, hostname: string, ip: ResolvedIp | undefined) =>
251 zeroTrust.listAccessInfrastructureTargets.items({ accountId, hostname }).pipe(
252 Stream.filter(
253 (t) => t.hostname === hostname && (ip === undefined || ipEquals(observedIp(t), ip)),
254 ),
255 Stream.runHead,
256 Effect.map(Option.getOrUndefined),
257 );
258
259 /**
260 * Narrow the props' `ip` (whose virtualNetworkIds are `Input`s already
261 * resolved to strings by Plan) to the concrete wire shape.
262 */
263 const resolvedIp = (ip: InfrastructureTargetIp): ResolvedIp => ({
264 ...(ip.ipv4
265 ? {
266 ipv4: {
267 ipAddr: ip.ipv4.ipAddr,
268 ...(typeof ip.ipv4.virtualNetworkId === "string"
269 ? { virtualNetworkId: ip.ipv4.virtualNetworkId }
270 : {}),
271 },
272 }
273 : {}),
274 ...(ip.ipv6
275 ? {
276 ipv6: {
277 ipAddr: ip.ipv6.ipAddr,
278 ...(typeof ip.ipv6.virtualNetworkId === "string"
279 ? { virtualNetworkId: ip.ipv6.virtualNetworkId }
280 : {}),
281 },
282 }
283 : {}),
284 });
285
286 const observedIp = (t: {
287 ip: {
288 ipv4?: { ipAddr?: string | null; virtualNetworkId?: string | null } | null;
289 ipv6?: { ipAddr?: string | null; virtualNetworkId?: string | null } | null;
290 };
291 }): ResolvedIp => ({
292 ...(t.ip.ipv4
293 ? {
294 ipv4: {
295 ipAddr: t.ip.ipv4.ipAddr ?? undefined,
296 ...(t.ip.ipv4.virtualNetworkId ? { virtualNetworkId: t.ip.ipv4.virtualNetworkId } : {}),
297 },
298 }
299 : {}),
300 ...(t.ip.ipv6
301 ? {
302 ipv6: {
303 ipAddr: t.ip.ipv6.ipAddr ?? undefined,
304 ...(t.ip.ipv6.virtualNetworkId ? { virtualNetworkId: t.ip.ipv6.virtualNetworkId } : {}),
305 },
306 }
307 : {}),
308 });
309
310 /**
311 * Compare two address blocks. A `virtualNetworkId` left undefined in the
312 * desired state matches any observed value (Cloudflare fills in the
313 * account's default virtual network).
314 */
315 const ipEquals = (observed: ResolvedIp, desired: ResolvedIp): boolean =>
316 familyEquals(observed.ipv4, desired.ipv4) && familyEquals(observed.ipv6, desired.ipv6);
317
318 const familyEquals = (
319 observed: { ipAddr?: string; virtualNetworkId?: string } | undefined,
320 desired: { ipAddr?: string; virtualNetworkId?: string } | undefined,
321 ): boolean => {
322 if (desired === undefined) return observed === undefined;
323 if (observed === undefined) return false;
324 if (observed.ipAddr !== desired.ipAddr) return false;
325 if (
326 desired.virtualNetworkId !== undefined &&
327 observed.virtualNetworkId !== desired.virtualNetworkId
328 ) {
329 return false;
330 }
331 return true;
332 };
333
334 const toAttributes = (
335 target: ObservedTarget,
336 accountId: string,
337 ): InfrastructureTargetAttributes => ({
338 targetId: target.id,
339 accountId,
340 hostname: target.hostname,
341 ip: observedIp(target),
342 createdAt: target.createdAt,
343 modifiedAt: target.modifiedAt,
344 });