Skip to content

Commit 3b145e5

Browse files
committed
fix: add ratelimiting to the asset upload endpoint
1 parent 0b27826 commit 3b145e5

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

packages/api/routes/assets.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,19 @@ import { z } from "zod";
55
import { Asset } from "@karakeep/trpc/models/assets";
66

77
import { authMiddleware } from "../middlewares/auth";
8+
import { createRateLimitMiddleware } from "../middlewares/rateLimit";
89
import { serveAsset } from "../utils/assets";
910
import { uploadAsset } from "../utils/upload";
1011

1112
const 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

0 commit comments

Comments
 (0)