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

main
ts 338 lines 12.9 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as WAFv2 from "@alchemy.run/aws/WAFv2";
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 Result from "effect/Result";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 export class Wafv2BindingsFunction extends Lambda.Function<Lambda.Function>()(
14 "Wafv2BindingsFunction",
15 ) {}
16
17 export default Wafv2BindingsFunction.make(
18 {
19 main,
20 functionUrl: true,
21 timeout: Duration.seconds(120),
22 },
23 Effect.gen(function* () {
24 // Cheap, fast-provisioning WAF entities that exercise every binding
25 // scope: an IP set (dynamic block list), a web ACL with a rate-based
26 // rule, and a rule group (permission-policy interface).
27 const ipSet = yield* WAFv2.IPSet("BindingsIpSet", {
28 addresses: ["192.0.2.44/32"],
29 description: "bindings fixture",
30 });
31 const webAcl = yield* WAFv2.WebACL("BindingsAcl", {
32 defaultAction: { Allow: {} },
33 rules: [
34 {
35 Name: "rate-limit",
36 Priority: 0,
37 Statement: {
38 RateBasedStatement: { Limit: 100, AggregateKeyType: "IP" },
39 },
40 Action: { Block: {} },
41 VisibilityConfig: {
42 SampledRequestsEnabled: true,
43 CloudWatchMetricsEnabled: true,
44 MetricName: "rate-limit",
45 },
46 },
47 ],
48 });
49 const ruleGroup = yield* WAFv2.RuleGroup("BindingsRuleGroup", {
50 capacity: 10,
51 });
52
53 // The rule group ARN accessor — resolved per-request to derive the
54 // account id for the permission-policy round trip.
55 const ruleGroupArn = yield* ruleGroup.ruleGroupArn;
56
57 const bound = {
58 getIPSet: yield* WAFv2.GetIPSet(ipSet),
59 updateIPSet: yield* WAFv2.UpdateIPSet(ipSet),
60 getSampledRequests: yield* WAFv2.GetSampledRequests(webAcl),
61 getRateBasedStatementManagedKeys: yield* WAFv2.GetRateBasedStatementManagedKeys(webAcl),
62 listResourcesForWebACL: yield* WAFv2.ListResourcesForWebACL(webAcl),
63 getTopPathStatisticsByTraffic: yield* WAFv2.GetTopPathStatisticsByTraffic(webAcl),
64 getPermissionPolicy: yield* WAFv2.GetPermissionPolicy(ruleGroup),
65 putPermissionPolicy: yield* WAFv2.PutPermissionPolicy(ruleGroup),
66 deletePermissionPolicy: yield* WAFv2.DeletePermissionPolicy(ruleGroup),
67 checkCapacity: yield* WAFv2.CheckCapacity(),
68 createAPIKey: yield* WAFv2.CreateAPIKey(),
69 getDecryptedAPIKey: yield* WAFv2.GetDecryptedAPIKey(),
70 listAPIKeys: yield* WAFv2.ListAPIKeys(),
71 deleteAPIKey: yield* WAFv2.DeleteAPIKey(),
72 describeManagedRuleGroup: yield* WAFv2.DescribeManagedRuleGroup(),
73 listAvailableManagedRuleGroups: yield* WAFv2.ListAvailableManagedRuleGroups(),
74 listAvailableManagedRuleGroupVersions: yield* WAFv2.ListAvailableManagedRuleGroupVersions(),
75 describeAllManagedProducts: yield* WAFv2.DescribeAllManagedProducts(),
76 describeManagedProductsByVendor: yield* WAFv2.DescribeManagedProductsByVendor(),
77 getWebACLForResource: yield* WAFv2.GetWebACLForResource(),
78 };
79
80 return {
81 fetch: Effect.gen(function* () {
82 const request = yield* HttpServerRequest;
83 const url = new URL(request.originalUrl);
84 const pathname = url.pathname;
85
86 if (request.method === "GET" && pathname === "/bindings") {
87 return yield* HttpServerResponse.json({
88 bound: Object.keys(bound),
89 });
90 }
91
92 // IP-set-scoped: Name/Scope/Id injected.
93 if (request.method === "GET" && pathname === "/ip-set") {
94 const response = yield* bound.getIPSet();
95 return yield* HttpServerResponse.json({
96 addresses: [...(response.IPSet?.Addresses ?? [])].sort(),
97 description: response.IPSet?.Description ?? "",
98 });
99 }
100
101 // Dynamic block list: full-replacement update, LockToken handled
102 // inside the binding.
103 if (request.method === "POST" && pathname === "/ip-set") {
104 const body = (yield* request.json) as { addresses: string[] };
105 yield* bound.updateIPSet({ addresses: body.addresses });
106 const after = yield* bound.getIPSet();
107 return yield* HttpServerResponse.json({
108 addresses: [...(after.IPSet?.Addresses ?? [])].sort(),
109 });
110 }
111
112 // Web-ACL-scoped: WebAclArn + Scope injected.
113 if (request.method === "GET" && pathname === "/sampled") {
114 const now = yield* Effect.sync(() => new Date());
115 const response = yield* bound.getSampledRequests({
116 RuleMetricName: "rate-limit",
117 TimeWindow: {
118 StartTime: new Date(now.getTime() - 60 * 60 * 1000),
119 EndTime: now,
120 },
121 MaxItems: 100,
122 });
123 return yield* HttpServerResponse.json({
124 sampled: (response.SampledRequests ?? []).length,
125 populationSize: response.PopulationSize ?? 0,
126 });
127 }
128
129 // Web-ACL-scoped: Scope + WebACLName + WebACLId injected.
130 if (request.method === "GET" && pathname === "/rate-keys") {
131 const response = yield* bound.getRateBasedStatementManagedKeys({
132 RuleName: "rate-limit",
133 });
134 return yield* HttpServerResponse.json({
135 v4: (response.ManagedKeysIPV4?.Addresses ?? []).length,
136 v4Version: response.ManagedKeysIPV4?.IPAddressVersion ?? null,
137 });
138 }
139
140 if (request.method === "GET" && pathname === "/resources") {
141 const response = yield* bound.listResourcesForWebACL();
142 return yield* HttpServerResponse.json({
143 resources: response.ResourceArns ?? [],
144 });
145 }
146
147 // Pricing-plan-gated: report the typed outcome instead of dying.
148 if (request.method === "GET" && pathname === "/top-paths") {
149 const now = yield* Effect.sync(() => new Date());
150 const result = yield* Effect.result(
151 bound.getTopPathStatisticsByTraffic({
152 TimeWindow: {
153 StartTime: new Date(now.getTime() - 60 * 60 * 1000),
154 EndTime: now,
155 },
156 Limit: 10,
157 NumberOfTopTrafficBotsPerPath: 3,
158 }),
159 );
160 return yield* HttpServerResponse.json(
161 Result.isSuccess(result)
162 ? { ok: true, tag: null }
163 : { ok: false, tag: result.failure._tag },
164 );
165 }
166
167 // Permission-policy round trip on the rule group ARN.
168 if (request.method === "GET" && pathname === "/permission-policy") {
169 const before = yield* bound
170 .getPermissionPolicy()
171 .pipe(
172 Effect.catchTag("WAFNonexistentItemException", () =>
173 Effect.succeed({ Policy: undefined }),
174 ),
175 );
176 const arn = yield* ruleGroupArn;
177 const account = arn.split(":")[4];
178 // The policy must NOT include a Resource parameter — the resource
179 // is implied by the ResourceArn the binding injects.
180 yield* bound.putPermissionPolicy({
181 Policy: JSON.stringify({
182 Version: "2012-10-17",
183 Statement: [
184 {
185 Effect: "Allow",
186 Principal: { AWS: `arn:aws:iam::${account}:root` },
187 Action: [
188 "wafv2:CreateWebACL",
189 "wafv2:UpdateWebACL",
190 "wafv2:PutFirewallManagerRuleGroups",
191 ],
192 },
193 ],
194 }),
195 });
196 const after = yield* bound.getPermissionPolicy();
197 yield* bound.deletePermissionPolicy();
198 return yield* HttpServerResponse.json({
199 beforePolicy: before.Policy ?? null,
200 hasPolicy: typeof after.Policy === "string",
201 deleted: true,
202 });
203 }
204
205 // Account-level: WCU cost of a simple geo-match rule.
206 if (request.method === "GET" && pathname === "/capacity") {
207 const response = yield* bound.checkCapacity({
208 Scope: "REGIONAL",
209 Rules: [
210 {
211 Name: "cap-probe",
212 Priority: 0,
213 Statement: { GeoMatchStatement: { CountryCodes: ["US"] } },
214 Action: { Block: {} },
215 VisibilityConfig: {
216 SampledRequestsEnabled: false,
217 CloudWatchMetricsEnabled: false,
218 MetricName: "cap-probe",
219 },
220 },
221 ],
222 });
223 return yield* HttpServerResponse.json({
224 capacity: response.Capacity ?? 0,
225 });
226 }
227
228 // CAPTCHA API-key lifecycle: mint, list, decrypt, delete.
229 if (request.method === "GET" && pathname === "/api-keys") {
230 const created = yield* bound.createAPIKey({
231 Scope: "REGIONAL",
232 TokenDomains: ["example.com"],
233 });
234 const apiKey = created.APIKey ?? "";
235 const listed = yield* bound.listAPIKeys({ Scope: "REGIONAL" });
236 const decrypted = yield* bound.getDecryptedAPIKey({
237 Scope: "REGIONAL",
238 APIKey: apiKey,
239 });
240 yield* bound.deleteAPIKey({ Scope: "REGIONAL", APIKey: apiKey });
241 return yield* HttpServerResponse.json({
242 created: apiKey.length > 0,
243 listed: (listed.APIKeySummaries ?? []).length,
244 domains: decrypted.TokenDomains ?? [],
245 deleted: true,
246 });
247 }
248
249 // Managed rule group catalog.
250 if (request.method === "GET" && pathname === "/managed") {
251 const groups = yield* bound.listAvailableManagedRuleGroups({
252 Scope: "REGIONAL",
253 Limit: 20,
254 });
255 const described = yield* bound.describeManagedRuleGroup({
256 VendorName: "AWS",
257 Name: "AWSManagedRulesCommonRuleSet",
258 Scope: "REGIONAL",
259 });
260 const versions = yield* bound.listAvailableManagedRuleGroupVersions({
261 VendorName: "AWS",
262 Name: "AWSManagedRulesCommonRuleSet",
263 Scope: "REGIONAL",
264 Limit: 5,
265 });
266 return yield* HttpServerResponse.json({
267 groups: (groups.ManagedRuleGroups ?? []).length,
268 capacity: described.Capacity ?? 0,
269 currentDefaultVersion: versions.CurrentDefaultVersion ?? null,
270 });
271 }
272
273 if (request.method === "GET" && pathname === "/products") {
274 const all = yield* bound.describeAllManagedProducts({
275 Scope: "REGIONAL",
276 });
277 const aws = yield* bound.describeManagedProductsByVendor({
278 VendorName: "AWS",
279 Scope: "REGIONAL",
280 });
281 return yield* HttpServerResponse.json({
282 all: (all.ManagedProducts ?? []).length,
283 aws: (aws.ManagedProducts ?? []).length,
284 });
285 }
286
287 // Look up the web ACL of a (nonexistent) ALB — the typed
288 // WAFNonexistentItemException proves grant + wiring.
289 if (request.method === "GET" && pathname === "/waf-for-resource") {
290 const ipSetArn = (yield* bound.getIPSet()).IPSet?.ARN ?? "";
291 const [, , , region, account] = ipSetArn.split(":");
292 const response = yield* bound
293 .getWebACLForResource({
294 ResourceArn: `arn:aws:elasticloadbalancing:${region}:${account}:loadbalancer/app/wafv2-bindings-missing/0123456789abcdef`,
295 })
296 .pipe(
297 Effect.catchTag("WAFNonexistentItemException", () =>
298 Effect.succeed({ WebACL: undefined }),
299 ),
300 );
301 return yield* HttpServerResponse.json({
302 found: response.WebACL !== undefined,
303 });
304 }
305
306 return yield* HttpServerResponse.json(
307 { error: "Not found", method: request.method, pathname },
308 { status: 404 },
309 );
310 }).pipe(Effect.orDie),
311 };
312 }).pipe(
313 Effect.provide(
314 Layer.mergeAll(
315 WAFv2.GetIPSetHttp,
316 WAFv2.UpdateIPSetHttp,
317 WAFv2.GetSampledRequestsHttp,
318 WAFv2.GetRateBasedStatementManagedKeysHttp,
319 WAFv2.ListResourcesForWebACLHttp,
320 WAFv2.GetTopPathStatisticsByTrafficHttp,
321 WAFv2.GetPermissionPolicyHttp,
322 WAFv2.PutPermissionPolicyHttp,
323 WAFv2.DeletePermissionPolicyHttp,
324 WAFv2.CheckCapacityHttp,
325 WAFv2.CreateAPIKeyHttp,
326 WAFv2.GetDecryptedAPIKeyHttp,
327 WAFv2.ListAPIKeysHttp,
328 WAFv2.DeleteAPIKeyHttp,
329 WAFv2.DescribeManagedRuleGroupHttp,
330 WAFv2.ListAvailableManagedRuleGroupsHttp,
331 WAFv2.ListAvailableManagedRuleGroupVersionsHttp,
332 WAFv2.DescribeAllManagedProductsHttp,
333 WAFv2.DescribeManagedProductsByVendorHttp,
334 WAFv2.GetWebACLForResourceHttp,
335 ),
336 ),
337 ),
338 );