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

main
ts 208 lines 8.17 KB
Raw
1 import * as ApiGateway from "@alchemy.run/aws/ApiGateway";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Effect from "effect/Effect";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Layer from "effect/Layer";
7 import * as Redacted from "effect/Redacted";
8 import path from "pathe";
9
10 const main = path.resolve(import.meta.dirname, "bindings-handler.ts");
11
12 export class ApiGatewayBindingsFunction extends Lambda.Function<Lambda.Function>()(
13 "ApiGatewayBindingsFunction",
14 ) {}
15
16 export default ApiGatewayBindingsFunction.make(
17 {
18 main,
19 functionUrl: true,
20 },
21 Effect.gen(function* () {
22 // Usage plan the key-management routes enroll keys into.
23 const plan = yield* ApiGateway.UsagePlan("AgBindingsPlan", {
24 throttle: { rateLimit: 10, burstLimit: 5 },
25 });
26
27 // Minimal REST API + stage so the flush-cache bindings have a target.
28 const api = yield* ApiGateway.RestApi("AgBindingsApi", {
29 endpointConfiguration: { types: ["REGIONAL"] },
30 });
31 yield* ApiGateway.Method("AgBindingsMock", {
32 restApi: api,
33 httpMethod: "GET",
34 authorizationType: "NONE",
35 integration: { type: "MOCK" },
36 });
37 const deployment = yield* ApiGateway.Deployment("AgBindingsDep", {
38 restApi: api,
39 });
40 const stage = yield* ApiGateway.Stage("AgBindingsStage", {
41 restApi: api,
42 stageName: "bindings",
43 deploymentId: deployment.deploymentId,
44 });
45
46 const createApiKey = yield* ApiGateway.CreateApiKey();
47 const getApiKey = yield* ApiGateway.GetApiKey();
48 const getApiKeys = yield* ApiGateway.GetApiKeys();
49 const updateApiKey = yield* ApiGateway.UpdateApiKey();
50 const deleteApiKey = yield* ApiGateway.DeleteApiKey();
51 const createUsagePlanKey = yield* ApiGateway.CreateUsagePlanKey(plan);
52 const getUsagePlanKey = yield* ApiGateway.GetUsagePlanKey(plan);
53 const getUsagePlanKeys = yield* ApiGateway.GetUsagePlanKeys(plan);
54 const deleteUsagePlanKey = yield* ApiGateway.DeleteUsagePlanKey(plan);
55 const getUsage = yield* ApiGateway.GetUsage(plan);
56 const updateUsage = yield* ApiGateway.UpdateUsage(plan);
57 const flushStageCache = yield* ApiGateway.FlushStageCache(stage);
58 const flushStageAuthorizersCache = yield* ApiGateway.FlushStageAuthorizersCache(stage);
59
60 return {
61 fetch: Effect.gen(function* () {
62 const request = yield* HttpServerRequest;
63 const url = new URL(request.originalUrl);
64 const pathname = url.pathname;
65
66 if (request.method === "POST" && pathname === "/keys") {
67 const body = (yield* request.json) as unknown as { name: string };
68 const created = yield* createApiKey({
69 name: body.name,
70 enabled: true,
71 });
72 yield* createUsagePlanKey({ keyId: created.id! });
73 return yield* HttpServerResponse.json({
74 id: created.id,
75 // Responses decode the key material to Redacted<string> — prove
76 // it round-tripped redacted without ever logging the plaintext.
77 valueRedacted: Redacted.isRedacted(created.value),
78 });
79 }
80
81 if (request.method === "GET" && pathname === "/keys") {
82 const nameQuery = url.searchParams.get("nameQuery") ?? undefined;
83 const page = yield* getApiKeys({ nameQuery, limit: 100 });
84 return yield* HttpServerResponse.json({
85 ids: (page.items ?? []).map((k) => k.id),
86 });
87 }
88
89 if (request.method === "GET" && pathname === "/key") {
90 const id = url.searchParams.get("id")!;
91 const key = yield* getApiKey({ apiKey: id });
92 return yield* HttpServerResponse.json({
93 id: key.id,
94 name: key.name,
95 enabled: key.enabled,
96 });
97 }
98
99 if (request.method === "POST" && pathname === "/disable") {
100 const body = (yield* request.json) as unknown as { id: string };
101 const key = yield* updateApiKey({
102 apiKey: body.id,
103 patchOperations: [{ op: "replace", path: "/enabled", value: "false" }],
104 });
105 return yield* HttpServerResponse.json({ enabled: key.enabled });
106 }
107
108 if (request.method === "GET" && pathname === "/plan-key") {
109 const id = url.searchParams.get("id")!;
110 const enrolled = yield* getUsagePlanKey({ keyId: id }).pipe(
111 Effect.map(() => true),
112 Effect.catchTag("NotFoundException", () => Effect.succeed(false)),
113 );
114 return yield* HttpServerResponse.json({ enrolled });
115 }
116
117 if (request.method === "GET" && pathname === "/plan-keys") {
118 const page = yield* getUsagePlanKeys({ limit: 100 });
119 return yield* HttpServerResponse.json({
120 ids: (page.items ?? []).map((k) => k.id),
121 });
122 }
123
124 if (request.method === "GET" && pathname === "/usage") {
125 const keyId = url.searchParams.get("keyId") ?? undefined;
126 const startDate = url.searchParams.get("startDate")!;
127 const endDate = url.searchParams.get("endDate")!;
128 const usage = yield* getUsage({ keyId, startDate, endDate });
129 return yield* HttpServerResponse.json({
130 usagePlanId: usage.usagePlanId,
131 items: usage.items ?? {},
132 });
133 }
134
135 if (request.method === "POST" && pathname === "/extend") {
136 const body = (yield* request.json) as unknown as { keyId: string };
137 // Quota extensions only apply to plans with a quota; on this
138 // plan the API answers BadRequest — the IAM grant is still
139 // exercised (a missing grant surfaces as UnauthorizedException /
140 // AccessDenied instead, failing the route).
141 const extended = yield* updateUsage({
142 keyId: body.keyId,
143 patchOperations: [{ op: "replace", path: "/remaining", value: "100" }],
144 }).pipe(
145 Effect.map(() => true),
146 Effect.catchTag(["BadRequestException", "NotFoundException"], () =>
147 Effect.succeed(false),
148 ),
149 );
150 return yield* HttpServerResponse.json({ extended });
151 }
152
153 if (request.method === "DELETE" && pathname === "/key") {
154 const id = url.searchParams.get("id")!;
155 yield* deleteUsagePlanKey({ keyId: id }).pipe(
156 Effect.catchTag("NotFoundException", () => Effect.void),
157 );
158 yield* deleteApiKey({ apiKey: id }).pipe(
159 Effect.catchTag("NotFoundException", () => Effect.void),
160 );
161 return yield* HttpServerResponse.json({ deleted: true });
162 }
163
164 if (request.method === "POST" && pathname === "/flush") {
165 // The stage has no cache cluster, so API Gateway answers
166 // BadRequest/NotFound — the IAM grant is still exercised (a
167 // missing grant surfaces as an auth error instead).
168 const cache = yield* flushStageCache().pipe(
169 Effect.map(() => true),
170 Effect.catchTag(["BadRequestException", "NotFoundException"], () =>
171 Effect.succeed(false),
172 ),
173 );
174 const authorizers = yield* flushStageAuthorizersCache().pipe(
175 Effect.map(() => true),
176 Effect.catchTag(["BadRequestException", "NotFoundException"], () =>
177 Effect.succeed(false),
178 ),
179 );
180 return yield* HttpServerResponse.json({ cache, authorizers });
181 }
182
183 return yield* HttpServerResponse.json(
184 { error: "Not found", method: request.method, pathname },
185 { status: 404 },
186 );
187 }).pipe(Effect.orDie),
188 };
189 }).pipe(
190 Effect.provide(
191 Layer.mergeAll(
192 ApiGateway.CreateApiKeyHttp,
193 ApiGateway.GetApiKeyHttp,
194 ApiGateway.GetApiKeysHttp,
195 ApiGateway.UpdateApiKeyHttp,
196 ApiGateway.DeleteApiKeyHttp,
197 ApiGateway.CreateUsagePlanKeyHttp,
198 ApiGateway.GetUsagePlanKeyHttp,
199 ApiGateway.GetUsagePlanKeysHttp,
200 ApiGateway.DeleteUsagePlanKeyHttp,
201 ApiGateway.GetUsageHttp,
202 ApiGateway.UpdateUsageHttp,
203 ApiGateway.FlushStageCacheHttp,
204 ApiGateway.FlushStageAuthorizersCacheHttp,
205 ),
206 ),
207 ),
208 );