@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 304 lines 11 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import {
3 amazonLinux2023,
4 AuthorizeSecurityGroupIngress,
5 AuthorizeSecurityGroupIngressHttp,
6 consumeInstanceStateEvents,
7 CreateSnapshot,
8 CreateSnapshotHttp,
9 DescribeInstance,
10 DescribeInstanceHttp,
11 DescribeInstanceStatus,
12 DescribeInstanceStatusHttp,
13 GetConsoleOutput,
14 GetConsoleOutputHttp,
15 GetPasswordData,
16 GetPasswordDataHttp,
17 Instance,
18 RebootInstance,
19 RebootInstanceHttp,
20 RevokeSecurityGroupIngress,
21 RevokeSecurityGroupIngressHttp,
22 SecurityGroup,
23 StartInstance,
24 StartInstanceHttp,
25 StopInstance,
26 StopInstanceHttp,
27 Subnet,
28 Volume,
29 Vpc,
30 } from "@alchemy.run/aws/EC2";
31 import type * as ec2 from "@distilled.cloud/aws/ec2";
32 import * as Context from "effect/Context";
33 import * as Duration from "effect/Duration";
34 import * as Effect from "effect/Effect";
35 import { HttpServerRequest } from "effect/http/HttpServerRequest";
36 import * as HttpServerResponse from "effect/http/HttpServerResponse";
37 import * as Layer from "effect/Layer";
38 import * as Redacted from "effect/Redacted";
39 import * as Schedule from "effect/Schedule";
40 import * as Stream from "effect/Stream";
41
42 type BindingError =
43 | ec2.DescribeInstancesError
44 | ec2.DescribeInstanceStatusError
45 | ec2.StartInstancesError
46 | ec2.StopInstancesError
47 | ec2.RebootInstancesError
48 | ec2.GetConsoleOutputError
49 | ec2.GetPasswordDataError
50 | ec2.CreateSnapshotError
51 | ec2.AuthorizeSecurityGroupIngressError
52 | ec2.RevokeSecurityGroupIngressError;
53
54 const authorizationResult = <A, E extends BindingError, R>(operation: Effect.Effect<A, E, R>) =>
55 operation.pipe(
56 Effect.retry({
57 while: (error) => error._tag === "UnauthorizedOperation",
58 schedule: Schedule.spaced("3 seconds"),
59 times: 8,
60 }),
61 // Return a typed timeout before Lambda's 30-second invocation limit.
62 Effect.timeout("25 seconds"),
63 Effect.result,
64 );
65
66 /** The dynamic-allowlisting rule the authorize/revoke routes add and remove. */
67 export const testIngressRule = {
68 IpProtocol: "tcp",
69 FromPort: 443,
70 ToPort: 443,
71 CidrIp: "203.0.113.0/24",
72 } as const;
73
74 export class Ec2BindingsFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
75 "Ec2BindingsFunction",
76 ) {}
77
78 /**
79 * Shared fleet for the bindings E2E: a dedicated VPC/subnet (the testing
80 * account has no default VPC), a t3.micro instance, a 1 GiB volume, and an
81 * empty security group. The AMI is an `Output` resolved at deploy time only,
82 * so this composition is safe to re-execute inside the deployed Lambda
83 * without runtime guards.
84 */
85 export class BindingsFleet extends Context.Service<
86 BindingsFleet,
87 { instance: Instance; group: SecurityGroup; volume: Volume }
88 >()("Ec2BindingsFleet") {}
89
90 export const BindingsFleetLive = Layer.effect(
91 BindingsFleet,
92 Effect.gen(function* () {
93 const imageId = amazonLinux2023();
94
95 const vpc = yield* Vpc("BindingsVpc", { cidrBlock: "10.61.0.0/16" });
96 const subnet = yield* Subnet("BindingsSubnet", {
97 vpcId: vpc.vpcId,
98 cidrBlock: "10.61.1.0/24",
99 });
100 const group = yield* SecurityGroup("BindingsSecurityGroup", {
101 vpcId: vpc.vpcId,
102 description: "EC2 bindings test group",
103 });
104 const volume = yield* Volume("BindingsVolume", {
105 availabilityZone: subnet.availabilityZone,
106 size: 1,
107 });
108 const instance = yield* Instance("BindingsInstance", {
109 imageId,
110 instanceType: "t3.micro",
111 subnetId: subnet.subnetId,
112 });
113 return { instance, group, volume };
114 }),
115 );
116
117 export default Ec2BindingsFunction.make(
118 {
119 main: import.meta.url,
120 functionUrl: true,
121 // The AWS defaults (128 MB / 3s) are too tight for the EC2 client:
122 // cold routes time out at 3s (502 from the function URL) with memory
123 // pegged against the 128 MB floor.
124 timeout: Duration.seconds(30),
125 memorySize: 512,
126 },
127 Effect.gen(function* () {
128 const { instance, group, volume } = yield* BindingsFleet;
129
130 const describeInstance = yield* DescribeInstance(instance);
131 const describeStatus = yield* DescribeInstanceStatus(instance);
132 const startInstance = yield* StartInstance(instance);
133 const stopInstance = yield* StopInstance(instance);
134 const rebootInstance = yield* RebootInstance(instance);
135 const getConsoleOutput = yield* GetConsoleOutput(instance);
136 const getPasswordData = yield* GetPasswordData(instance);
137 const createSnapshot = yield* CreateSnapshot(volume);
138 const authorizeIngress = yield* AuthorizeSecurityGroupIngress(group);
139 const revokeIngress = yield* RevokeSecurityGroupIngress(group);
140
141 // Subscribe to instance stop/terminate transitions (creates the
142 // EventBridge rule at deploy time).
143 yield* consumeInstanceStateEvents(instance, { states: ["stopped", "terminated"] }, (events) =>
144 Stream.runForEach(events, (event) =>
145 Effect.log(`${event.detail["instance-id"]} is now ${event.detail.state}`),
146 ),
147 );
148
149 return {
150 fetch: Effect.gen(function* () {
151 const request = yield* HttpServerRequest;
152 const pathname = new URL(request.originalUrl).pathname;
153
154 if (request.method === "GET" && pathname === "/health") {
155 return yield* HttpServerResponse.json({ ok: true });
156 }
157
158 if (request.method === "GET" && pathname === "/describe") {
159 const result = yield* describeInstance().pipe(authorizationResult);
160 return yield* HttpServerResponse.json({
161 ok: result._tag === "Success",
162 tag: result._tag === "Failure" ? result.failure._tag : "Success",
163 state: result._tag === "Success" ? result.success?.State?.Name : undefined,
164 });
165 }
166
167 if (request.method === "GET" && pathname === "/status") {
168 const result = yield* describeStatus({
169 IncludeAllInstances: true,
170 }).pipe(authorizationResult);
171 return yield* HttpServerResponse.json({
172 ok: result._tag === "Success",
173 tag: result._tag === "Failure" ? result.failure._tag : "Success",
174 count:
175 result._tag === "Success"
176 ? (result.success.InstanceStatuses ?? []).length
177 : undefined,
178 });
179 }
180
181 if (request.method === "GET" && pathname === "/console") {
182 const result = yield* getConsoleOutput().pipe(authorizationResult);
183 return yield* HttpServerResponse.json({
184 ok: result._tag === "Success",
185 tag: result._tag === "Failure" ? result.failure._tag : "Success",
186 });
187 }
188
189 // The instance runs Linux without a key pair, so the password data is
190 // empty — the probe proves the IAM grant and that a present
191 // `PasswordData` surfaces as Redacted (never a raw string).
192 if (request.method === "GET" && pathname === "/password") {
193 const result = yield* getPasswordData().pipe(authorizationResult);
194 const passwordData = result._tag === "Success" ? result.success.PasswordData : undefined;
195 return yield* HttpServerResponse.json({
196 ok: result._tag === "Success",
197 tag: result._tag === "Failure" ? result.failure._tag : "Success",
198 hasField: passwordData !== undefined,
199 redacted: passwordData !== undefined ? Redacted.isRedacted(passwordData) : null,
200 });
201 }
202
203 // Starting an already-running instance succeeds without effect.
204 if (request.method === "POST" && pathname === "/start") {
205 const result = yield* startInstance().pipe(authorizationResult);
206 return yield* HttpServerResponse.json({
207 ok: result._tag === "Success",
208 tag: result._tag === "Failure" ? result.failure._tag : "Success",
209 });
210 }
211
212 if (request.method === "POST" && pathname === "/reboot") {
213 const result = yield* rebootInstance().pipe(authorizationResult);
214 return yield* HttpServerResponse.json({
215 ok: result._tag === "Success",
216 tag: result._tag === "Failure" ? result.failure._tag : "Success",
217 });
218 }
219
220 // Runs LAST in the test file — the instance stays stopped until the
221 // stack is destroyed.
222 if (request.method === "POST" && pathname === "/stop") {
223 const result = yield* stopInstance().pipe(authorizationResult);
224 return yield* HttpServerResponse.json({
225 ok: result._tag === "Success",
226 tag: result._tag === "Failure" ? result.failure._tag : "Success",
227 state:
228 result._tag === "Success"
229 ? result.success.StoppingInstances?.[0]?.CurrentState?.Name
230 : undefined,
231 });
232 }
233
234 if (request.method === "POST" && pathname === "/authorize") {
235 const result = yield* authorizeIngress({
236 IpPermissions: [
237 {
238 IpProtocol: testIngressRule.IpProtocol,
239 FromPort: testIngressRule.FromPort,
240 ToPort: testIngressRule.ToPort,
241 IpRanges: [{ CidrIp: testIngressRule.CidrIp }],
242 },
243 ],
244 }).pipe(authorizationResult);
245 return yield* HttpServerResponse.json({
246 ok: result._tag === "Success",
247 tag: result._tag === "Failure" ? result.failure._tag : "Success",
248 });
249 }
250
251 if (request.method === "POST" && pathname === "/revoke") {
252 const result = yield* revokeIngress({
253 IpPermissions: [
254 {
255 IpProtocol: testIngressRule.IpProtocol,
256 FromPort: testIngressRule.FromPort,
257 ToPort: testIngressRule.ToPort,
258 IpRanges: [{ CidrIp: testIngressRule.CidrIp }],
259 },
260 ],
261 }).pipe(authorizationResult);
262 return yield* HttpServerResponse.json({
263 ok: result._tag === "Success",
264 tag: result._tag === "Failure" ? result.failure._tag : "Success",
265 });
266 }
267
268 // Creates a real (1 GiB) snapshot; the test deletes it out-of-band.
269 if (request.method === "POST" && pathname === "/snapshot") {
270 const result = yield* createSnapshot({
271 Description: "alchemy EC2 bindings test snapshot",
272 }).pipe(authorizationResult);
273 return yield* HttpServerResponse.json({
274 ok: result._tag === "Success",
275 tag: result._tag === "Failure" ? result.failure._tag : "Success",
276 snapshotId: result._tag === "Success" ? result.success.SnapshotId : undefined,
277 });
278 }
279
280 return yield* HttpServerResponse.json(
281 { error: "Not found", method: request.method, pathname },
282 { status: 404 },
283 );
284 }).pipe(Effect.orDie),
285 };
286 }).pipe(
287 Effect.provide(
288 Layer.mergeAll(
289 AWS.Lambda.EventSource,
290 DescribeInstanceHttp,
291 DescribeInstanceStatusHttp,
292 StartInstanceHttp,
293 StopInstanceHttp,
294 RebootInstanceHttp,
295 GetConsoleOutputHttp,
296 GetPasswordDataHttp,
297 CreateSnapshotHttp,
298 AuthorizeSecurityGroupIngressHttp,
299 RevokeSecurityGroupIngressHttp,
300 BindingsFleetLive,
301 ),
302 ),
303 ),
304 );