The best way to control Claude Code, Codex and more from any computer or phone

main
ts 256 lines 9.8 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as Route53 from "@alchemy.run/aws/Route53";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Schedule from "effect/Schedule";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "bindings-handler.ts");
12
13 // Deterministic probe record written and deleted by /record/roundtrip.
14 const PROBE_LABEL = "probe";
15 const PROBE_VALUE = '"alchemy-route53-bindings"';
16
17 export class Route53BindingsFunction extends Lambda.Function<Lambda.Function>()(
18 "Route53BindingsFunction",
19 ) {}
20
21 export default Route53BindingsFunction.make(
22 {
23 main,
24 functionUrl: true,
25 // /record/roundtrip polls GetChange until INSYNC (typically ~20-60s).
26 timeout: Duration.minutes(3),
27 },
28 Effect.gen(function* () {
29 // Public zone under the reserved-domain-safe `.alchemy` TLD — never
30 // delegated, but Route 53's authoritative servers (and TestDNSAnswer)
31 // answer for it regardless.
32 const zone = yield* Route53.HostedZone("BindingsZone", {
33 name: "alchemy-route53-bindings.alchemy.",
34 comment: "alchemy Route53 bindings fixture",
35 forceDestroy: true,
36 });
37
38 const check = yield* Route53.HealthCheck("BindingsCheck", {
39 type: "HTTP",
40 fullyQualifiedDomainName: "example.com",
41 resourcePath: "/",
42 port: 80,
43 requestInterval: "30 seconds",
44 failureThreshold: 3,
45 });
46
47 const changeRecordSets = yield* Route53.ChangeResourceRecordSets(zone);
48 const listRecordSets = yield* Route53.ListResourceRecordSets(zone);
49 const getHostedZone = yield* Route53.GetHostedZone(zone);
50 const testDnsAnswer = yield* Route53.TestDNSAnswer(zone);
51 const getChange = yield* Route53.GetChange();
52 const getHealthCheckStatus = yield* Route53.GetHealthCheckStatus(check);
53 const getHealthCheckLastFailureReason = yield* Route53.GetHealthCheckLastFailureReason(check);
54 const listHostedZones = yield* Route53.ListHostedZones();
55 const listHostedZonesByName = yield* Route53.ListHostedZonesByName();
56 const listHostedZonesByVpc = yield* Route53.ListHostedZonesByVPC();
57
58 const bound = {
59 changeRecordSets,
60 listRecordSets,
61 getHostedZone,
62 testDnsAnswer,
63 getChange,
64 getHealthCheckStatus,
65 getHealthCheckLastFailureReason,
66 listHostedZones,
67 listHostedZonesByName,
68 listHostedZonesByVpc,
69 };
70
71 // `ChangeInfo.Id` comes back as "/change/C…" but GetChange only accepts
72 // the bare id. Bounded: 2s x 40 ≈ 80s worst case.
73 const waitForInsync = (changeId: string) =>
74 getChange({ Id: changeId.replace(/^\/change\//, "") }).pipe(
75 Effect.map((r) => r.ChangeInfo.Status),
76 Effect.repeat({
77 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(40)]),
78 until: (status): boolean => status === "INSYNC",
79 }),
80 );
81
82 return {
83 fetch: Effect.gen(function* () {
84 const request = yield* HttpServerRequest;
85 const url = new URL(request.originalUrl);
86 const pathname = url.pathname;
87
88 if (request.method === "GET" && pathname === "/bindings") {
89 return yield* HttpServerResponse.json({
90 bound: Object.keys(bound),
91 });
92 }
93
94 if (request.method === "GET" && pathname === "/zone") {
95 // `Id` injection scopes the read to the bound zone.
96 const detail = yield* getHostedZone();
97 return yield* HttpServerResponse.json({
98 name: detail.HostedZone.Name,
99 nameServerCount: (detail.DelegationSet?.NameServers ?? []).length,
100 });
101 }
102
103 if (request.method === "GET" && pathname === "/zones") {
104 const detail = yield* getHostedZone();
105 const response = yield* listHostedZones({ MaxItems: 100 });
106 return yield* HttpServerResponse.json({
107 count: (response.HostedZones ?? []).length,
108 found: (response.HostedZones ?? []).some((z) => z.Id === detail.HostedZone.Id),
109 });
110 }
111
112 if (request.method === "GET" && pathname === "/zones/by-name") {
113 const detail = yield* getHostedZone();
114 const response = yield* listHostedZonesByName({
115 DNSName: detail.HostedZone.Name,
116 MaxItems: 1,
117 });
118 return yield* HttpServerResponse.json({
119 firstName: response.HostedZones?.[0]?.Name,
120 });
121 }
122
123 if (request.method === "GET" && pathname === "/zones/by-vpc") {
124 // A well-formed VPC id with no private-zone associations — the
125 // call round-trips (IAM + query encoding) and returns an empty
126 // summary list.
127 const region = yield* Effect.sync(() => process.env.AWS_REGION ?? "us-east-1");
128 const response = yield* listHostedZonesByVpc({
129 VPCId: "vpc-0123456789abcdef0",
130 VPCRegion: region,
131 }).pipe(
132 Effect.map((r) => ({
133 count: (r.HostedZoneSummaries ?? []).length,
134 rejected: false,
135 notOwned: false,
136 })),
137 // Route 53 validates VPC ownership before listing: a VPC id the
138 // account doesn't own comes back as the typed AccessDeniedException
139 // ("The VPC ... is not owned by you"), NOT an empty list. That
140 // rejection still proves the grant + query encoding end-to-end —
141 // but only when the message is the ownership check. A genuine IAM
142 // denial ("not authorized to perform") sets notOwned=false and the
143 // test fails loudly instead of being masked.
144 Effect.catchTag(["InvalidInput", "AccessDeniedException"], (e) =>
145 Effect.succeed({
146 count: 0,
147 rejected: true,
148 notOwned:
149 e._tag === "AccessDeniedException"
150 ? (e.message ?? "").includes("not owned by you")
151 : true,
152 // Surfaced so a failing assertion shows the real rejection.
153 detail: `${e._tag}: ${e.message ?? ""}`.slice(0, 300),
154 }),
155 ),
156 );
157 return yield* HttpServerResponse.json(response);
158 }
159
160 if (request.method === "GET" && pathname === "/dns-test") {
161 // The zone apex NS record answers even without delegation.
162 const detail = yield* getHostedZone();
163 const answer = yield* testDnsAnswer({
164 RecordName: detail.HostedZone.Name,
165 RecordType: "NS",
166 });
167 return yield* HttpServerResponse.json({
168 responseCode: answer.ResponseCode,
169 recordCount: (answer.RecordData ?? []).length,
170 });
171 }
172
173 if (request.method === "POST" && pathname === "/record/roundtrip") {
174 // UPSERT → GetChange-poll INSYNC → List (finds it) → DELETE.
175 // Exercises the full dynamic-DNS loop end-to-end and leaves no
176 // orphan record (UPSERT makes re-runs after a crash idempotent).
177 const detail = yield* getHostedZone();
178 const zoneName = detail.HostedZone.Name;
179 const recordName = `${PROBE_LABEL}.${zoneName}`;
180 const recordSet = {
181 Name: recordName,
182 Type: "TXT" as const,
183 TTL: 60,
184 ResourceRecords: [{ Value: PROBE_VALUE }],
185 };
186
187 const upserted = yield* changeRecordSets({
188 ChangeBatch: {
189 Comment: "alchemy Route53 bindings roundtrip",
190 Changes: [{ Action: "UPSERT", ResourceRecordSet: recordSet }],
191 },
192 });
193 const changeStatus = yield* waitForInsync(upserted.ChangeInfo.Id);
194
195 const listed = yield* listRecordSets({
196 StartRecordName: recordName,
197 StartRecordType: "TXT",
198 MaxItems: 1,
199 });
200 const found = (listed.ResourceRecordSets ?? []).some(
201 (set) => set.Name === recordName && set.Type === "TXT",
202 );
203
204 // A concurrent/previous cleanup racing the DELETE surfaces the
205 // typed InvalidChangeBatch ("not found") — the record is gone
206 // either way.
207 yield* changeRecordSets({
208 ChangeBatch: {
209 Changes: [{ Action: "DELETE", ResourceRecordSet: recordSet }],
210 },
211 }).pipe(Effect.catchTag("InvalidChangeBatch", () => Effect.void));
212
213 return yield* HttpServerResponse.json({
214 changeStatus,
215 found,
216 deleted: true,
217 });
218 }
219
220 if (request.method === "GET" && pathname === "/health/status") {
221 const response = yield* getHealthCheckStatus();
222 return yield* HttpServerResponse.json({
223 observations: response.HealthCheckObservations.length,
224 });
225 }
226
227 if (request.method === "GET" && pathname === "/health/failure-reason") {
228 const response = yield* getHealthCheckLastFailureReason();
229 return yield* HttpServerResponse.json({
230 observations: response.HealthCheckObservations.length,
231 });
232 }
233
234 return yield* HttpServerResponse.json(
235 { error: "Not found", method: request.method, pathname },
236 { status: 404 },
237 );
238 }).pipe(Effect.orDie),
239 };
240 }).pipe(
241 Effect.provide(
242 Layer.mergeAll(
243 Route53.ChangeResourceRecordSetsHttp,
244 Route53.ListResourceRecordSetsHttp,
245 Route53.GetHostedZoneHttp,
246 Route53.TestDNSAnswerHttp,
247 Route53.GetChangeHttp,
248 Route53.GetHealthCheckStatusHttp,
249 Route53.GetHealthCheckLastFailureReasonHttp,
250 Route53.ListHostedZonesHttp,
251 Route53.ListHostedZonesByNameHttp,
252 Route53.ListHostedZonesByVPCHttp,
253 ),
254 ),
255 ),
256 );