File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { createMiddleware } from "hono/factory" ;
2+ import { HTTPException } from "hono/http-exception" ;
3+
4+ import type { RateLimitConfig } from "@karakeep/shared/ratelimiting" ;
5+ import serverConfig from "@karakeep/shared/config" ;
6+ import { getRateLimitClient } from "@karakeep/shared/ratelimiting" ;
7+ import { Context } from "@karakeep/trpc" ;
8+
9+ export function createRateLimitMiddleware ( config : RateLimitConfig ) {
10+ return createMiddleware < {
11+ Variables : {
12+ ctx : Context ;
13+ } ;
14+ } > ( async ( c , next ) => {
15+ if ( ! serverConfig . rateLimiting . enabled ) {
16+ return next ( ) ;
17+ }
18+
19+ const ip = c . var . ctx . req . ip ;
20+ if ( ! ip ) {
21+ return next ( ) ;
22+ }
23+
24+ const client = await getRateLimitClient ( ) ;
25+ if ( ! client ) {
26+ return next ( ) ;
27+ }
28+
29+ const key = `${ ip } :${ config . name } ` ;
30+ const result = await client . checkRateLimit ( config , key ) ;
31+
32+ if ( ! result . allowed ) {
33+ throw new HTTPException ( 429 , {
34+ message : `Rate limit exceeded. Try again in ${ result . resetInSeconds } seconds.` ,
35+ } ) ;
36+ }
37+
38+ return next ( ) ;
39+ } ) ;
40+ }
Original file line number Diff line number Diff line change @@ -5,13 +5,19 @@ import { z } from "zod";
55import { Asset } from "@karakeep/trpc/models/assets" ;
66
77import { authMiddleware } from "../middlewares/auth" ;
8+ import { createRateLimitMiddleware } from "../middlewares/rateLimit" ;
89import { serveAsset } from "../utils/assets" ;
910import { uploadAsset } from "../utils/upload" ;
1011
1112const app = new Hono ( )
1213 . use ( authMiddleware )
1314 . post (
1415 "/" ,
16+ createRateLimitMiddleware ( {
17+ name : "assets.upload" ,
18+ windowMs : 60 * 1000 ,
19+ maxRequests : 30 ,
20+ } ) ,
1521 zValidator (
1622 "form" ,
1723 z
You can’t perform that action at this time.
0 commit comments