feat: add RATE_LIMIT_API_DAILY_REQUESTS (#751)

This commit is contained in:
Dream Hunter
2025-11-03 02:36:38 +08:00
committed by GitHub
parent b5c229b6c4
commit bfd7d6811e
2 changed files with 16 additions and 0 deletions

View File

@@ -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 = {

View File

@@ -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<number>(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 (