diff options
| author | Mohamed Bassem <me@mbassem.com> | 2025-07-10 21:22:54 +0000 |
|---|---|---|
| committer | Mohamed Bassem <me@mbassem.com> | 2025-07-10 22:03:30 +0000 |
| commit | 613137ff99442885c5fe679b2cc1172adfc5a283 (patch) | |
| tree | 97f2b940448357870090364c6f73b780d6f473d9 /packages/trpc/index.ts | |
| parent | 333d1610fad10e70759545f223959503288a02c6 (diff) | |
| download | karakeep-613137ff99442885c5fe679b2cc1172adfc5a283.tar.zst | |
feat: Add API ratelimits
Diffstat (limited to 'packages/trpc/index.ts')
| -rw-r--r-- | packages/trpc/index.ts | 43 |
1 files changed, 32 insertions, 11 deletions
diff --git a/packages/trpc/index.ts b/packages/trpc/index.ts index 90f37ae4..cc62c534 100644 --- a/packages/trpc/index.ts +++ b/packages/trpc/index.ts @@ -5,6 +5,7 @@ import { ZodError } from "zod"; import type { db } from "@karakeep/db"; import serverConfig from "@karakeep/shared/config"; +import { createRateLimitMiddleware } from "./rateLimit"; import { apiErrorsTotalCounter, apiRequestDurationSummary, @@ -86,21 +87,38 @@ export const procedure = t.procedure end(); return res; }); -export const publicProcedure = procedure; -export const authedProcedure = procedure.use(function isAuthed(opts) { - const user = opts.ctx.user; +// Default public procedure rate limiting +export const publicProcedure = procedure.use( + createRateLimitMiddleware({ + name: "globalPublic", + windowMs: 60 * 1000, + maxRequests: 1000, + }), +); - if (!user?.id) { - throw new TRPCError({ code: "UNAUTHORIZED" }); - } +export const authedProcedure = procedure + // Default authed procedure rate limiting + .use( + createRateLimitMiddleware({ + name: "globalAuthed", + windowMs: 60 * 1000, + maxRequests: 3000, + }), + ) + .use(function isAuthed(opts) { + const user = opts.ctx.user; + + if (!user?.id) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } - return opts.next({ - ctx: { - user, - }, + return opts.next({ + ctx: { + user, + }, + }); }); -}); export const adminProcedure = authedProcedure.use(function isAdmin(opts) { const user = opts.ctx.user; @@ -109,3 +127,6 @@ export const adminProcedure = authedProcedure.use(function isAdmin(opts) { } return opts.next(opts); }); + +// Export the rate limiting utilities for use in routers +export { createRateLimitMiddleware }; |
