Skip to content

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

fix(api): limit upload body size before parsing multipart

Mohamed Bassem3e22b659b65c
diff --git a/packages/api/routes/assets.ts b/packages/api/routes/assets.ts
index a5a91fb2..44cff812 100644
--- a/packages/api/routes/assets.ts
+++ b/packages/api/routes/assets.ts
@@ -10,7 +10,7 @@ import { authMiddleware } from "../middlewares/auth";
import { createRateLimitMiddleware } from "../middlewares/rateLimit";
import { rejectMutationInReadOnlyMode } from "../middlewares/readOnlyMode";
import { serveAsset } from "../utils/assets";
-import { uploadAsset } from "../utils/upload";
+import { uploadAsset, uploadBodyLimit } from "../utils/upload";
const app = new Hono()
.use(authMiddleware)
@@ -23,6 +23,7 @@ const app = new Hono()
windowMs: 60 * 1000,
maxRequests: 30,
}),
+ uploadBodyLimit,
zValidator(
"form",
z
diff --git a/packages/api/routes/bookmarks.ts b/packages/api/routes/bookmarks.ts
index 2918d827..35222abb 100644
--- a/packages/api/routes/bookmarks.ts
+++ b/packages/api/routes/bookmarks.ts
@@ -27,7 +27,7 @@ import {
zIncludeContentSearchParamsSchema,
zStringBool,
} from "../utils/types";
-import { uploadAsset } from "../utils/upload";
+import { uploadAsset, uploadBodyLimit } from "../utils/upload";
const app = new Hono()
.use(authMiddleware)
@@ -138,6 +138,7 @@ const app = new Hono()
.default("skip"),
}),
),
+ uploadBodyLimit,
zValidator(
"form",
z.object({
diff --git a/packages/api/utils/upload.ts b/packages/api/utils/upload.ts
index 6f139927..27059ae9 100644
--- a/packages/api/utils/upload.ts
+++ b/packages/api/utils/upload.ts
@@ -4,6 +4,7 @@ import * as path from "path";
import { Readable } from "stream";
import { pipeline } from "stream/promises";
import { fileTypeFromBlob, supportedMimeTypes } from "file-type";
+import { bodyLimit } from "hono/body-limit";
import { assets, AssetTypes } from "@karakeep/db/schema";
import {
@@ -18,6 +19,14 @@ import { AuthedContext } from "@karakeep/trpc";
const MAX_UPLOAD_SIZE_BYTES = serverConfig.maxAssetSizeMb * 1024 * 1024;
+// Rejects oversized uploads before the multipart body gets buffered in memory.
+// The extra 1MiB leaves room for the multipart framing and other form fields,
+// the exact file size is still enforced in uploadAsset.
+export const uploadBodyLimit = bodyLimit({
+ maxSize: MAX_UPLOAD_SIZE_BYTES + 1024 * 1024,
+ onError: (c) => c.json({ error: "Asset is too big" }, 413),
+});
+
// Helper to convert Web Stream to Node Stream (requires Node >= 16.5 / 14.18)
export function webStreamToNode(
webStream: ReadableStream<Uint8Array>,