Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

fix: add ratelimiting to the asset upload endpoint

Mohamed Bassem3b145e599210
diff --git a/packages/api/middlewares/rateLimit.ts b/packages/api/middlewares/rateLimit.ts
new file mode 100644
index 00000000..305eaa28
--- /dev/null
+++ b/packages/api/middlewares/rateLimit.ts
@@ -0,0 +1,40 @@
+import { createMiddleware } from "hono/factory";
+import { HTTPException } from "hono/http-exception";
+
+import type { RateLimitConfig } from "@karakeep/shared/ratelimiting";
+import serverConfig from "@karakeep/shared/config";
+import { getRateLimitClient } from "@karakeep/shared/ratelimiting";
+import { Context } from "@karakeep/trpc";
+
+export function createRateLimitMiddleware(config: RateLimitConfig) {
+ return createMiddleware<{
+ Variables: {
+ ctx: Context;
+ };
+ }>(async (c, next) => {
+ if (!serverConfig.rateLimiting.enabled) {
+ return next();
+ }
+
+ const ip = c.var.ctx.req.ip;
+ if (!ip) {
+ return next();
+ }
+
+ const client = await getRateLimitClient();
+ if (!client) {
+ return next();
+ }
+
+ const key = `${ip}:${config.name}`;
+ const result = await client.checkRateLimit(config, key);
+
+ if (!result.allowed) {
+ throw new HTTPException(429, {
+ message: `Rate limit exceeded. Try again in ${result.resetInSeconds} seconds.`,
+ });
+ }
+
+ return next();
+ });
+}
diff --git a/packages/api/routes/assets.ts b/packages/api/routes/assets.ts
index e7d1c35f..0b05518d 100644
--- a/packages/api/routes/assets.ts
+++ b/packages/api/routes/assets.ts
@@ -5,6 +5,7 @@ import { z } from "zod";
import { Asset } from "@karakeep/trpc/models/assets";
import { authMiddleware } from "../middlewares/auth";
+import { createRateLimitMiddleware } from "../middlewares/rateLimit";
import { serveAsset } from "../utils/assets";
import { uploadAsset } from "../utils/upload";
@@ -12,6 +13,11 @@ const app = new Hono()
.use(authMiddleware)
.post(
"/",
+ createRateLimitMiddleware({
+ name: "assets.upload",
+ windowMs: 60 * 1000,
+ maxRequests: 30,
+ }),
zValidator(
"form",
z