🔒️ Log identifiers when rate limits are hit (#1599)

This commit is contained in:
Luke Vella 2025-03-02 16:11:07 +00:00 committed by GitHub
parent d71a2fb6b6
commit b214de75ab
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 14 additions and 10 deletions

View file

@ -9,13 +9,16 @@ import type { TRPCContext } from "@/trpc/context";
import { appRouter } from "@/trpc/routers";
import { getEmailClient } from "@/utils/emails";
const handler = (req: NextRequest) => {
const handler = async (req: NextRequest) => {
const session = await auth();
const ip = ipAddress(req);
const ja4Digest = req.headers.get("x-vercel-ja4-digest");
return fetchRequestHandler({
endpoint: "/api/trpc",
req,
router: appRouter,
createContext: async () => {
const session = await auth();
const locale = await getLocaleFromHeader(req);
const user = session?.user
? {
@ -31,8 +34,7 @@ const handler = (req: NextRequest) => {
const ip =
process.env.NODE_ENV === "development" ? "127.0.0.1" : ipAddress(req);
const identifier =
session?.user?.id ?? req.headers.get("x-vercel-ja4-digest") ?? ip;
const identifier = session?.user?.id ?? ja4Digest ?? ip;
return {
user,
@ -44,6 +46,14 @@ const handler = (req: NextRequest) => {
if (error.code === "INTERNAL_SERVER_ERROR") {
Sentry.captureException(error);
}
if (error.code === "TOO_MANY_REQUESTS") {
console.warn("Too many requests", {
path: req.nextUrl.pathname,
userId: session?.user?.id,
ip,
ja4Digest,
});
}
},
});
};

View file

@ -114,12 +114,6 @@ export const createRateLimitMiddleware = (
const res = await ratelimit.limit(`${name}:${ctx.identifier}`);
if (!res.success) {
console.warn("Rate limit exceeded", {
identifier: ctx.identifier,
endpoint: name,
limit: requests,
duration,
});
throw new TRPCError({
code: "TOO_MANY_REQUESTS",
message: "Too many requests",