Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rate limiter #37

Merged
merged 3 commits into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,9 @@ NEXTAUTH_URL="http://localhost:3000"

# Seed data
ADMIN_PASSWORD="password"

# Rate Limiter
RATE_LIMITER_ENABLED=false
# Upstash redis database credentials required for rate limiter to work
UPSTASH_REDIS_REST_URL=""
UPSTASH_REDIS_REST_TOKEN=""
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@trpc/react-query": "next",
"@trpc/server": "next",
"@uidotdev/usehooks": "^2.4.1",
"@upstash/ratelimit": "^2.0.2",
"bcrypt": "^5.1.1",
"class-variance-authority": "^0.7.0",
"drizzle-orm": "^0.30.10",
Expand Down
6 changes: 6 additions & 0 deletions src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ export const env = createEnv({
process.env.VERCEL ? z.string() : z.string().url(),
),
ADMIN_PASSWORD: z.string(),
RATE_LIMITER_ENABLED: z
.string()
.transform((val) => val === "true")
.optional()
.default("false"),
},

/**
Expand All @@ -44,6 +49,7 @@ export const env = createEnv({
NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD,
RATE_LIMITER_ENABLED: process.env.RATE_LIMITER_ENABLED,
9helix marked this conversation as resolved.
Show resolved Hide resolved
},
/**
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
Expand Down
21 changes: 20 additions & 1 deletion src/server/api/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import { ZodError } from "zod";

import { getServerAuthSession } from "~/server/auth";
import { db } from "~/server/db";
import { env } from "~/env"; // Import the environment variables

import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

/**
* 1. CONTEXT
Expand Down Expand Up @@ -87,6 +91,14 @@ export const createTRPCRouter = t.router;
*/
export const publicProcedure = t.procedure;

let rateLimiter: Ratelimit | null = null;
if (env.RATE_LIMITER_ENABLED) {
rateLimiter = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, "10 s"),
});
}

/**
* Protected (authenticated) procedure
*
Expand All @@ -95,10 +107,17 @@ export const publicProcedure = t.procedure;
*
* @see https://trpc.io/docs/procedures
*/
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
if (rateLimiter) {
const { success } = await rateLimiter.limit(ctx.session.user.id);
if (!success) {
throw new TRPCError({ code: "TOO_MANY_REQUESTS" });
}
}

return next({
ctx: {
// infers the `session` as non-nullable
Expand Down
63 changes: 42 additions & 21 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1539,20 +1539,20 @@
dependencies:
"@tanstack/query-core" "5.51.15"

"@trpc/client@^11.0.0-rc.467":
version "11.0.0-rc.467"
resolved "https://registry.yarnpkg.com/@trpc/client/-/client-11.0.0-rc.467.tgz#31aaaea76f0a750021894c958169c0f44e4b87d8"
integrity sha512-ovZaGdAUl+EEmtJJc5uuo95B0gw8+q3jwNjUQQmmSMU5Isq4sYdjIWNkhbrFtR8CovllFyrRrjAgCWdaOTEY4g==
"@trpc/client@next":
version "11.0.0-rc.502"
resolved "https://registry.yarnpkg.com/@trpc/client/-/client-11.0.0-rc.502.tgz#12846fdc2421950cc03f68a3214ebc3c6cbda5d5"
integrity sha512-ysFQ3wHnjzLcAqeuwx9/B/YV+2XN/kmfAdTUG+O/SUAdP2wAwo6XbhOxlHw0HWS5pDCsTfJkxDr1nMVkuFM07Q==

"@trpc/react-query@^11.0.0-rc.467":
version "11.0.0-rc.467"
resolved "https://registry.yarnpkg.com/@trpc/react-query/-/react-query-11.0.0-rc.467.tgz#b72e86acd9f4888357129d6c35f17111d94cb4a6"
integrity sha512-PNpHgISXJ60s0fJc6JUomKe3iu1wj6pZNFHJgQecAEK0gs1y6VM8Oh8CHgZg8+J/KDP/UtUmBcbpFP9l8Nq48w==
"@trpc/react-query@next":
version "11.0.0-rc.502"
resolved "https://registry.yarnpkg.com/@trpc/react-query/-/react-query-11.0.0-rc.502.tgz#1ddb04e2edfc557d70a0fe4b67092308dfba79ae"
integrity sha512-aWZZGFTxERXOzI0cb2zYoJQyLrnfJz7sqJVTR4/5UJQ1eCRdu7mFnni6rAlcAHI4r2iA+2xtBQ74JPlaVp5krg==

"@trpc/server@^11.0.0-rc.467":
version "11.0.0-rc.467"
resolved "https://registry.yarnpkg.com/@trpc/server/-/server-11.0.0-rc.467.tgz#2593085b683554c1ceac70296bac296a3bf297c0"
integrity sha512-94Gv26ALuBfxgFlSGV3x2uF2ixUEViuK0m3IPKOvCTMreisZkBqyTa3NkBcuPZW/AMUieM5P4Q2NrbHTIA0fKQ==
"@trpc/server@next":
version "11.0.0-rc.502"
resolved "https://registry.yarnpkg.com/@trpc/server/-/server-11.0.0-rc.502.tgz#f094f14be207cf9e46ecfab3568c08f1ee75bc6c"
integrity sha512-n6B8Q/UqF+hFXyCTXq9AWSn6EkXBbVo/Bs7/QzZxe5KD5CdnBomC7A1y6Qr+i0eiOWwTHJZQ0az+gJetb2fdxw==

"@tsconfig/node10@^1.0.7":
version "1.0.11"
Expand Down Expand Up @@ -1871,6 +1871,27 @@
resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.2.0.tgz#756641adb587851b5ccb3e095daf27ae581c8406"
integrity sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==

"@upstash/core-analytics@^0.0.10":
version "0.0.10"
resolved "https://registry.yarnpkg.com/@upstash/core-analytics/-/core-analytics-0.0.10.tgz#e686a313ec2279d5a8d53e6c215085f1c0f5ab4b"
integrity sha512-7qJHGxpQgQr9/vmeS1PktEwvNAF7TI4iJDi8Pu2CFZ9YUGHZH4fOP5TfYlZ4aVxfopnELiE4BS4FBjyK7V1/xQ==
dependencies:
"@upstash/redis" "^1.28.3"

"@upstash/ratelimit@^2.0.2":
version "2.0.2"
resolved "https://registry.yarnpkg.com/@upstash/ratelimit/-/ratelimit-2.0.2.tgz#cdab809151db050a53334c3b76ecd69a51881038"
integrity sha512-1J5Szbu5r9OTV2F95SinFVo5DQ7jm1Gmal9xD7HrcBlOxyn7YXToEsK2j6lSNJEhklvKl96Ntzzd3Q/yR9GB2A==
dependencies:
"@upstash/core-analytics" "^0.0.10"

"@upstash/redis@^1.28.3":
version "1.34.0"
resolved "https://registry.yarnpkg.com/@upstash/redis/-/redis-1.34.0.tgz#f32cd53ebeeafbba7eca10f8597a573d5a2fed0d"
integrity sha512-TrXNoJLkysIl8SBc4u9bNnyoFYoILpCcFJcLyWCccb/QSUmaVKdvY0m5diZqc3btExsapcMbaw/s/wh9Sf1pJw==
dependencies:
crypto-js "^4.2.0"

JSONStream@^1.3.5:
version "1.3.5"
resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.3.5.tgz#3208c1f08d3a4d99261ab64f92302bc15e111ca0"
Expand Down Expand Up @@ -2587,6 +2608,11 @@ cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3:
shebang-command "^2.0.0"
which "^2.0.1"

crypto-js@^4.2.0:
version "4.2.0"
resolved "https://registry.yarnpkg.com/crypto-js/-/crypto-js-4.2.0.tgz#4d931639ecdfd12ff80e8186dba6af2c2e856631"
integrity sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==

cssesc@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-3.0.0.tgz#37741919903b868565e1c09ea747445cd18983ee"
Expand Down Expand Up @@ -4956,10 +4982,10 @@ lru-queue@^0.1.0:
dependencies:
es5-ext "~0.10.2"

lucide-react@^0.426.0:
version "0.426.0"
resolved "https://registry.yarnpkg.com/lucide-react/-/lucide-react-0.426.0.tgz#15ab8cbf73c45655bcc8d3a69065277d4e201808"
integrity sha512-aby5G+Zt+LIIEU0n9900XQNJFJUcs7/S+jOEgIhkV08NX3kGx1zxALKh1JvAKcYqutWLg07exbnYvh66szhrRA==
lucide-react@^0.394.0:
version "0.394.0"
resolved "https://registry.yarnpkg.com/lucide-react/-/lucide-react-0.394.0.tgz#ea496bcdb0a1295219936766f70b48235624e1ef"
integrity sha512-PzTbJ0bsyXRhH59k5qe7MpTd5MxlpYZUcM9kGSwvPGAfnn0J6FElDwu2EX6Vuh//F7y60rcVJiFQ7EK9DCMgfw==

make-dir@^3.1.0:
version "3.1.0"
Expand Down Expand Up @@ -5684,11 +5710,6 @@ react-hook-form@^7.52.1:
resolved "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.52.1.tgz"
integrity sha512-uNKIhaoICJ5KQALYZ4TOaOLElyM+xipord+Ha3crEFhTntdLvWZqVY49Wqd/0GiVCA/f9NjemLeiNPjG7Hpurg==

react-icons@^5.2.1:
version "5.2.1"
resolved "https://registry.yarnpkg.com/react-icons/-/react-icons-5.2.1.tgz#28c2040917b2a2eda639b0f797bff1888e018e4a"
integrity sha512-zdbW5GstTzXaVKvGSyTaBalt7HSfuK5ovrzlpyiWHAFXndXTdd/1hdDHI4xBM1Mn7YriT6aqESucFl9kEXzrdw==

react-is@^16.13.1:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
Expand Down