From f60e940564f548375954a76e995c1c6dbe359d69 Mon Sep 17 00:00:00 2001 From: Petter Rasmussen Date: Sun, 21 Jul 2024 20:03:28 +0200 Subject: [PATCH] Add rate limiter binding --- glot_cloudflare/functions/api/run.ts | 38 +++++++++++++++++++++------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/glot_cloudflare/functions/api/run.ts b/glot_cloudflare/functions/api/run.ts index 82050b7..a0c043e 100644 --- a/glot_cloudflare/functions/api/run.ts +++ b/glot_cloudflare/functions/api/run.ts @@ -1,17 +1,28 @@ +import { RateLimiter } from "../../../glot_cloudflare_rate_limiter/src/rate_limiter"; + type StringRecord = Record; +interface Env { + RATE_LIMITER: DurableObjectNamespace; +} + -export const onRequestPost: PagesFunction = async (context) => { +export const onRequestPost: PagesFunction = async (context) => { if (!isAllowed(context.request)) { - const body = JSON.stringify({ message: "Forbidden" }) - return new Response(body, { - status: 403, - headers: { - "Content-Type": "application/json", - }, - }) + return errorResponse(403, "Forbidden"); } + const ip = context.request.headers.get("CF-Connecting-IP"); + if (ip === null) { + return errorResponse(400, "Could not determine client IP"); + } + + const id = context.env.RATE_LIMITER.idFromName(ip); + const stub = context.env.RATE_LIMITER.get(id); + const stats = stub.increment({ maxRequests: 10, periodDuration: 60 * 1000 }); + + console.log(stats) + const envVars = parseEnvVars(context.env); return run(envVars, context.request.body); }; @@ -93,4 +104,13 @@ function supportsBrotli(request: Request): boolean { const encodings = acceptEncoding.split(", ") return encodings.includes("br") || encodings.some((enc) => enc.startsWith("br;")) -} \ No newline at end of file +} + +function errorResponse(status: number, message: string): Response { + return new Response(JSON.stringify({ message }), { + status, + headers: { + "Content-Type": "application/json", + }, + }); +}