@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 280 lines 11 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { canonicalCidr } from "alchemy/Util/ip-address";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import type { ClientVpnEndpointId } from "./ClientVpnEndpoint.ts";
11 import { retryClientVpn } from "./ClientVpnWait.ts";
12 import type { SubnetId } from "./Subnet.ts";
13
14 /** Immutable settings for a manually added VPC-based Client VPN route. */
15 export interface ClientVpnRouteProps {
16 /** The Client VPN endpoint. Changing this replaces the route. */
17 clientVpnEndpointId: ClientVpnEndpointId;
18 /** The destination IPv4 CIDR. Changing this replaces the route. */
19 destinationCidrBlock: string;
20 /**
21 * The associated target subnet. Pass ClientVpnTargetNetworkAssociation.subnetId
22 * to order creation and deletion after and before the association respectively.
23 * Changing this replaces the route.
24 */
25 targetVpcSubnetId: SubnetId;
26 /** A description of the route. Changing this replaces the route. */
27 description?: string;
28 }
29
30 /** A manually added route in a Client VPN endpoint's route table. */
31 export interface ClientVpnRoute extends Resource<
32 "AWS.EC2.ClientVpnRoute",
33 ClientVpnRouteProps,
34 {
35 /** The Client VPN endpoint containing the route. */
36 clientVpnEndpointId: ClientVpnEndpointId;
37 /** The canonical destination network CIDR. */
38 destinationCidrBlock: string;
39 /** The associated subnet through which traffic is routed. */
40 targetVpcSubnetId: SubnetId;
41 /** The observed route description. */
42 description: string | undefined;
43 /** How AWS created the route: add-route for manual routes, associate for automatic routes. */
44 origin: string | undefined;
45 /** The observed route type. */
46 type: string | undefined;
47 /** The current route state. */
48 status: ec2.ClientVpnRouteStatusCode;
49 /** Additional information about the route state. */
50 statusMessage: string | undefined;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * Adds a destination route through a Client VPN target subnet. The target must
58 * already be associated; reference the association's subnetId output, not the
59 * subnet resource directly, to preserve deployment and teardown ordering.
60 * Authorization rules are configured separately and are also required for access.
61 *
62 * All property changes require replacement. Description-only changes delete the
63 * old route first because AWS has no modify-route API. AWS-created local routes
64 * cannot be managed or deleted with this resource. This resource manages the
65 * declared endpoint/destination/subnet identity, including an existing manual
66 * route discovered without cached state. Routes have no independent ownership
67 * markers.
68 *
69 * Readiness waits default to 30 minutes. Set `AWS_CLIENT_VPN_TIMEOUT` to a
70 * positive finite duration, such as `45 minutes`, to override this deadline.
71 *
72 * ### Routing Client Traffic
73 * **Example:** Route internet traffic through an associated subnet
74 * ```typescript
75 * const target = yield* AWS.EC2.ClientVpnTargetNetworkAssociation("VpnTarget", {
76 * clientVpnEndpointId: endpoint.clientVpnEndpointId,
77 * subnetId: publicSubnet.subnetId,
78 * });
79 * const route = yield* AWS.EC2.ClientVpnRoute("VpnInternetRoute", {
80 * clientVpnEndpointId: target.clientVpnEndpointId,
81 * targetVpcSubnetId: target.subnetId,
82 * destinationCidrBlock: "0.0.0.0/0",
83 * description: "Internet egress",
84 * });
85 * ```
86 *
87 * The subnet's VPC routing must provide the required egress path. For multiple
88 * target associations, add the same destination through each target subnet so
89 * clients have consistent access regardless of which association serves them.
90 *
91 * @resource
92 */
93 export const ClientVpnRoute = Resource<ClientVpnRoute>("AWS.EC2.ClientVpnRoute");
94
95 class ClientVpnRoutePending extends Data.TaggedError("ClientVpnRoutePending")<{
96 message: string;
97 }> {}
98
99 class ClientVpnRouteFailed extends Data.TaggedError("ClientVpnRouteFailed")<{
100 message: string;
101 }> {}
102
103 const routes = (clientVpnEndpointId: ClientVpnEndpointId) =>
104 ec2.describeClientVpnRoutes.items({ ClientVpnEndpointId: clientVpnEndpointId }).pipe(
105 Stream.runCollect,
106 Effect.map((items) => items.filter((route) => route.Status?.Code !== "deleted")),
107 Effect.catchTag("InvalidClientVpnEndpointId.NotFound", () =>
108 Effect.succeed([] as ec2.ClientVpnRoute[]),
109 ),
110 );
111
112 const findRoute = (props: ClientVpnRouteProps) =>
113 routes(props.clientVpnEndpointId).pipe(
114 Effect.map((items) =>
115 items.find(
116 (route) =>
117 canonicalCidr(route.DestinationCidr) === canonicalCidr(props.destinationCidrBlock) &&
118 route.TargetSubnet === props.targetVpcSubnetId,
119 ),
120 ),
121 );
122
123 const toAttributes = (
124 clientVpnEndpointId: ClientVpnEndpointId,
125 route: ec2.ClientVpnRoute,
126 ): ClientVpnRoute["Attributes"] => ({
127 clientVpnEndpointId,
128 destinationCidrBlock: route.DestinationCidr!,
129 targetVpcSubnetId: route.TargetSubnet as SubnetId,
130 description: route.Description,
131 origin: route.Origin,
132 type: route.Type,
133 status: route.Status?.Code ?? "creating",
134 statusMessage: route.Status?.Message,
135 });
136
137 const requireManualRoute = (route: ec2.ClientVpnRoute) =>
138 route.Origin === "add-route"
139 ? Effect.void
140 : Effect.fail(
141 new ClientVpnRouteFailed({
142 message: `Client VPN route ${route.DestinationCidr} has origin ${route.Origin ?? "unknown"}; only manually added routes can be managed.`,
143 }),
144 );
145
146 const waitForRoute = (props: ClientVpnRouteProps, deleted: boolean) =>
147 Effect.gen(function* () {
148 const route = yield* findRoute(props);
149 if (deleted && !route) return undefined;
150 if (route) yield* requireManualRoute(route);
151 if (!deleted && route?.Status?.Code === "active") return route;
152 if (!deleted && route?.Status?.Code === "failed") {
153 return yield* new ClientVpnRouteFailed({
154 message: route.Status.Message ?? "Client VPN route creation failed",
155 });
156 }
157 return yield* new ClientVpnRoutePending({
158 message: `Client VPN route ${props.destinationCidrBlock} is ${route?.Status?.Code ?? "not visible"}; waiting for ${deleted ? "deletion" : "active"}`,
159 });
160 }).pipe((effect) => retryClientVpn(effect, (error) => error._tag === "ClientVpnRoutePending"));
161
162 const removeRoute = Effect.fn(function* (props: ClientVpnRouteProps) {
163 const route = yield* findRoute(props);
164 if (!route) return;
165 yield* requireManualRoute(route);
166 if (route.Status?.Code !== "deleting") {
167 yield* ec2
168 .deleteClientVpnRoute({
169 ClientVpnEndpointId: props.clientVpnEndpointId,
170 DestinationCidrBlock: canonicalCidr(props.destinationCidrBlock),
171 TargetVpcSubnetId: props.targetVpcSubnetId,
172 })
173 .pipe(
174 Effect.catchTag(
175 ["InvalidClientVpnEndpointId.NotFound", "InvalidClientVpnRouteNotFound"],
176 () => Effect.void,
177 ),
178 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
179 );
180 }
181 yield* waitForRoute(props, true);
182 });
183
184 /** Live AWS provider for ClientVpnRoute. */
185 export const ClientVpnRouteProvider = () =>
186 Provider.effect(
187 ClientVpnRoute,
188 Effect.gen(function* () {
189 return {
190 stables: ["clientVpnEndpointId", "destinationCidrBlock", "targetVpcSubnetId"],
191 nuke: {
192 dependsOn: ["AWS.EC2.ClientVpnTargetNetworkAssociation", "AWS.EC2.ClientVpnEndpoint"],
193 },
194 list: Effect.fn(function* () {
195 const endpoints = yield* ec2.describeClientVpnEndpoints.items({}).pipe(Stream.runCollect);
196 const items = yield* Effect.forEach(endpoints, (endpoint) =>
197 routes(endpoint.ClientVpnEndpointId as ClientVpnEndpointId).pipe(
198 Effect.map((items) =>
199 items
200 .filter(
201 (route) =>
202 route.Origin === "add-route" && route.TargetSubnet?.startsWith("subnet-"),
203 )
204 .map((route) =>
205 toAttributes(endpoint.ClientVpnEndpointId as ClientVpnEndpointId, route),
206 ),
207 ),
208 ),
209 );
210 return items.flat();
211 }),
212 read: Effect.fn(function* ({ olds, output }) {
213 const props = output ?? olds;
214 const route = yield* findRoute(props);
215 if (!route) return undefined;
216 yield* requireManualRoute(route);
217 return toAttributes(props.clientVpnEndpointId, route);
218 }),
219 diff: Effect.fn(function* ({ olds, news }) {
220 if (!isResolved(news)) {
221 return { action: "replace", deleteFirst: true };
222 }
223 const sameKey =
224 news.clientVpnEndpointId === olds.clientVpnEndpointId &&
225 canonicalCidr(news.destinationCidrBlock) === canonicalCidr(olds.destinationCidrBlock) &&
226 news.targetVpcSubnetId === olds.targetVpcSubnetId;
227 if (
228 !sameKey ||
229 news.destinationCidrBlock !== olds.destinationCidrBlock ||
230 news.description !== olds.description
231 ) {
232 return { action: "replace", deleteFirst: sameKey };
233 }
234 const route = yield* findRoute(news);
235 if (!route) return { action: "update" };
236 yield* requireManualRoute(route);
237 if (
238 (route.Description ?? "") !== (news.description ?? "") ||
239 route.Status?.Code === "failed"
240 ) {
241 return { action: "replace", deleteFirst: true };
242 }
243 if (route.Status?.Code !== "active") return { action: "update" };
244 }),
245 reconcile: Effect.fn(function* ({ news }) {
246 let route = yield* findRoute(news);
247 if (route) yield* requireManualRoute(route);
248 if (
249 route &&
250 (route.Status?.Code === "deleting" ||
251 (route.Description ?? "") !== (news.description ?? ""))
252 ) {
253 yield* removeRoute(news);
254 route = undefined;
255 }
256 if (!route) {
257 // Do not replay a completed create token after out-of-band deletion.
258 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
259 yield* ec2
260 .createClientVpnRoute({
261 ClientVpnEndpointId: news.clientVpnEndpointId,
262 DestinationCidrBlock: canonicalCidr(news.destinationCidrBlock),
263 TargetVpcSubnetId: news.targetVpcSubnetId,
264 Description: news.description,
265 ClientToken: clientToken,
266 })
267 .pipe(
268 Effect.catchTag("InvalidClientVpnDuplicateRoute", () => Effect.void),
269 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
270 );
271 }
272 const active = yield* waitForRoute(news, false);
273 return toAttributes(news.clientVpnEndpointId, active!);
274 }),
275 delete: Effect.fn(function* ({ output }) {
276 yield* removeRoute(output);
277 }),
278 };
279 }),
280 );