feat(security): extend rateLimit to support named categories with 5 tiers
This commit is contained in:
+1
-1
@@ -142,7 +142,7 @@ export const app = new Elysia({ prefix: "/api" })
|
|||||||
error: code === "NOT_FOUND" ? "Not found" : "Internal server error",
|
error: code === "NOT_FOUND" ? "Not found" : "Internal server error",
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.use(rateLimit(60, 100))
|
.use(rateLimit("default"))
|
||||||
.use(betterAuth)
|
.use(betterAuth)
|
||||||
// Health
|
// Health
|
||||||
.use(healthRoutes)
|
.use(healthRoutes)
|
||||||
|
|||||||
+15
-5
@@ -50,14 +50,23 @@ function checkRateLimit(
|
|||||||
return { allowed: true, remaining: max - entry.count, resetAt: entry.resetAt }
|
return { allowed: true, remaining: max - entry.count, resetAt: entry.resetAt }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CATEGORY_LIMITS: Record<string, { window: number; max: number }> = {
|
||||||
|
default: { window: 60, max: 100 },
|
||||||
|
auth: { window: 60, max: 20 },
|
||||||
|
read: { window: 60, max: 300 },
|
||||||
|
write: { window: 60, max: 10 },
|
||||||
|
strict: { window: 60, max: 5 },
|
||||||
|
}
|
||||||
|
|
||||||
export const rateLimit = (
|
export const rateLimit = (
|
||||||
window: number = 60,
|
category: string = "default",
|
||||||
max: number = 100,
|
) => {
|
||||||
) =>
|
const { window, max } = CATEGORY_LIMITS[category] ?? CATEGORY_LIMITS.default
|
||||||
new Elysia({ name: "rate-limit" }).onRequest(({ request, set }) => {
|
|
||||||
|
return new Elysia({ name: `rate-limit-${category}` }).onRequest(({ request, set }) => {
|
||||||
const ip = getClientIP(request)
|
const ip = getClientIP(request)
|
||||||
const path = new URL(request.url).pathname
|
const path = new URL(request.url).pathname
|
||||||
const key = `${ip}:${path}`
|
const key = `${category}:${ip}:${path}`
|
||||||
|
|
||||||
const result = checkRateLimit(key, window, max)
|
const result = checkRateLimit(key, window, max)
|
||||||
|
|
||||||
@@ -76,3 +85,4 @@ export const rateLimit = (
|
|||||||
set.headers["X-RateLimit-Remaining"] = String(result.remaining)
|
set.headers["X-RateLimit-Remaining"] = String(result.remaining)
|
||||||
set.headers["X-RateLimit-Reset"] = String(Math.ceil(result.resetAt / 1000))
|
set.headers["X-RateLimit-Reset"] = String(Math.ceil(result.resetAt / 1000))
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user