ratelimiting via "withRateLimit"

This commit is contained in:
Oliver Bryan
2026-01-21 23:04:38 +00:00
parent be57b4d6df
commit f780725a23
3 changed files with 199 additions and 47 deletions

View File

@@ -1,5 +1,6 @@
import type { BunRequest } from "bun";
import { getSession } from "../db/queries";
import { GLOBAL_RATE_LIMIT, getClientIP, rateLimitResponse, recordRateLimitAttempt } from "./rate-limit";
import { parseCookies, verifyToken } from "./utils";
export type AuthedRequest<T extends BunRequest = BunRequest> = T & {
@@ -19,6 +20,19 @@ const extractTokenFromCookie = (req: Request) => {
return cookies.token || null;
};
export const withRateLimit = <T extends BunRequest>(handler: RouteHandler<T>): RouteHandler<T> => {
return async (req: T) => {
const ip = getClientIP(req);
const key = `global:ip:${ip}`;
const attempt = recordRateLimitAttempt(key, GLOBAL_RATE_LIMIT);
if (!attempt.allowed) {
return rateLimitResponse(attempt.retryAfterMs);
}
return handler(req);
};
};
export const withAuth = <T extends BunRequest>(handler: AuthedRouteHandler<T>): RouteHandler<T> => {
return async (req: T) => {
const token = extractTokenFromCookie(req);