From bfd7d6811e9595e3123fe18903a1a1fd0c439bae Mon Sep 17 00:00:00 2001 From: Dream Hunter Date: Mon, 3 Nov 2025 02:36:38 +0800 Subject: [PATCH] feat: add RATE_LIMIT_API_DAILY_REQUESTS (#751) --- worker/src/types.d.ts | 3 +++ worker/src/worker.ts | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/worker/src/types.d.ts b/worker/src/types.d.ts index 4f192822..a22271a3 100644 --- a/worker/src/types.d.ts +++ b/worker/src/types.d.ts @@ -86,6 +86,9 @@ type Bindings = { // webhook config FRONTEND_URL: string | undefined + + // rate limiter config + RATE_LIMIT_API_DAILY_REQUESTS: number | string | undefined } type JwtPayload = { diff --git a/worker/src/worker.ts b/worker/src/worker.ts index 7f970992..a43954fd 100644 --- a/worker/src/worker.ts +++ b/worker/src/worker.ts @@ -64,6 +64,19 @@ app.use('/*', async (c, next) => { return c.text(`IP=${reqIp} Rate limit exceeded for ${c.req.path}`, 429) } } + try { + if (reqIp && c.env.KV && c.env.RATE_LIMIT_API_DAILY_REQUESTS) { + const daily_count_key = `limit|${reqIp}|${new Date().toISOString().slice(0, 10)}` + const dailyLimit = parseInt(c.env.RATE_LIMIT_API_DAILY_REQUESTS.toString(), 10); + const current_count = await c.env.KV.get(daily_count_key); + if (current_count && current_count >= dailyLimit) { + return c.text(`IP=${reqIp} Exceeded daily limit of ${dailyLimit} requests`, 429); + } + await c.env.KV.put(daily_count_key, ((current_count || 0) + 1).toString(), { expirationTtl: 24 * 60 * 60 }); + } + } catch (e) { + console.error(e); + } } // webhook check if (