Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(import): replace upload size cap with a per-blob sync-safe limit
Elian Doran0d9fa6593a08
diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.tsindex 884ee158eb..dd75141895 100644--- a/apps/server/src/routes/route_api.ts+++ b/apps/server/src/routes/route_api.ts@@ -11,7 +11,6 @@ import sql from "../services/sql.js";import { safeExtractMessageAndStackFromError } from "../services/utils.js";import { doubleCsrfProtection as csrfMiddleware } from "./csrf_protection.js";-const MAX_ALLOWED_FILE_SIZE_MB = 250;export const router = express.Router();// TODO: Deduplicate with etapi_utils.ts afterwards.@@ -145,17 +144,17 @@ function handleException(e: unknown | Error, method: HttpMethod, path: string, rexport function createUploadMiddleware(): RequestHandler {// None of our upload routes consume nested multipart text fields, so reject any bracketed field// name outright. This activates multer 2.2.0's guard against CVE-2026-5079 (DoS via deeply-nested- // field names) and must be set unconditionally — it is a safety limit, not a user-facing size- // limit gated by TRILIUM_NO_UPLOAD_LIMIT. `fieldNestingDepth` is not yet in @types/multer 2.1.0,- // hence the local intersection type.+ // field names). `fieldNestingDepth` is not yet in @types/multer 2.1.0, hence the local intersection+ // type.+ //+ // There is deliberately no upload `fileSize` limit: the old 250 MiB cap conflated archive size+ // (a ZIP's many entries are each their own blob) with single-blob size, and only bounded the+ // *compressed* upload. The real constraint — a single blob must stay serialisable for sync — is now+ // enforced per blob at creation time (see AbstractBeccaEntity._setContent / MAX_BLOB_CONTENT_LENGTH).const limits: NonNullable<multer.Options["limits"]> & { fieldNestingDepth?: number } = {fieldNestingDepth: 0};- if (!process.env.TRILIUM_NO_UPLOAD_LIMIT) {- limits.fileSize = MAX_ALLOWED_FILE_SIZE_MB * 1024 * 1024;- }-const multerOptions: multer.Options = {limits,fileFilter: (req: express.Request, file, cb) => {@@ -173,9 +172,7 @@ const uploadMiddleware = createUploadMiddleware();export const uploadMiddlewareWithErrorHandling = function (req: express.Request, res: express.Response, next: express.NextFunction) {uploadMiddleware(req, res, (err) => {- if (err?.code === "LIMIT_FILE_SIZE") {- res.setHeader("Content-Type", "text/plain").status(400).send(`Cannot upload file because it excceeded max allowed file size of ${MAX_ALLOWED_FILE_SIZE_MB} MiB`);- } else if (err?.code === "LIMIT_FIELD_NESTING") {+ if (err?.code === "LIMIT_FIELD_NESTING") {// Triggered by the fieldNestingDepth: 0 limit (CVE-2026-5079 guard). Without this branch the// error would be swallowed and the request forwarded to the handler with no file.res.setHeader("Content-Type", "text/plain").status(400).send("Upload rejected: nested multipart field names are not allowed.");diff --git a/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts b/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.tsindex c8022885cc..7bfa8152a2 100644--- a/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts+++ b/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts@@ -5,6 +5,7 @@ import noteService from "../../services/notes.js";import protectedSessionService from "../../services/protected_session.js";import { getSql } from "../../services/sql/index.js";import { encodeUtf8, unwrapStringOrBuffer } from "../../services/utils/binary.js";+import { exceedsBlobContentLimit, MAX_BLOB_CONTENT_LENGTH } from "./abstract_becca_entity.js";import type BNote from "./bnote.js";import BBlob from "./bblob.js";import BOption from "./boption.js";@@ -129,6 +130,53 @@ describe("AbstractBeccaEntity (real DB)", () => {getContext().init(() => note.setContent(undefined as unknown as string))).toThrow(/Cannot set null content/);});++ it("denies content that exceeds the blob limit at creation time", () => {+ const note = createNote();+ // allocUnsafe (no zeroing) so the ~373 MiB buffer is cheap; _setContent rejects it before any copy.+ const tooBig = Buffer.allocUnsafe(MAX_BLOB_CONTENT_LENGTH + 1);+ expect(() => getContext().init(() => note.setContent(tooBig))).toThrow(/too large to store/);+ });++ it("allows content within the blob limit", () => {+ const note = createNote();+ expect(() => getContext().init(() => note.setContent("still fine"))).not.toThrow();+ });+ });++ describe("blob content limit", () => {+ it("derives a limit in the expected range (~373 MiB, base64 of it under both the V8 string cap and the 500 MiB body limit)", () => {+ // Bounded by the HTTP body limit (the tighter ceiling): 500 MiB - 2 MiB envelope, * 3/4.+ expect(MAX_BLOB_CONTENT_LENGTH).toBe(Math.floor(((500 * 1024 * 1024 - 2 * 1024 * 1024) * 3) / 4));+ expect(Math.round(MAX_BLOB_CONTENT_LENGTH / 1024 / 1024)).toBe(374);++ // The whole point: its base64 form must fit under V8's max string length.+ const base64Length = 4 * Math.ceil(MAX_BLOB_CONTENT_LENGTH / 3);+ expect(base64Length).toBeLessThan(0x1fffffe8);+ });++ it("flags binary content strictly above the limit", () => {+ expect(exceedsBlobContentLimit(new Uint8Array(10), 10)).toBe(false); // exactly at the limit is allowed+ expect(exceedsBlobContentLimit(new Uint8Array(11), 10)).toBe(true);+ expect(exceedsBlobContentLimit(new Uint8Array(0), 10)).toBe(false);+ });++ it("measures string content by its UTF-8 byte length, not character count", () => {+ // ASCII: bytes == chars.+ expect(exceedsBlobContentLimit("a".repeat(10), 10)).toBe(false);+ expect(exceedsBlobContentLimit("a".repeat(11), 10)).toBe(true);++ // Multi-byte: "€" is 3 UTF-8 bytes, so 4 of them (12 bytes) exceed a 10-byte limit even though+ // there are only 4 characters — exercising the exact-measurement path past the cheap upper bound.+ expect(exceedsBlobContentLimit("€€€€", 10)).toBe(true);+ // 3 of them = 9 bytes, under the limit.+ expect(exceedsBlobContentLimit("€€€", 10)).toBe(false);+ });++ it("short-circuits without measuring when the character count alone is safely under the limit", () => {+ // 3 chars * 3 (max bytes/char) = 9 <= 10, so it returns false via the cheap bound.+ expect(exceedsBlobContentLimit("abc", 10)).toBe(false);+ });});describe("forceFrontendReload componentId branch (saveBlob)", () => {diff --git a/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts b/packages/trilium-core/src/becca/entities/abstract_becca_entity.tsindex 2a17af5687..da336a81dd 100644--- a/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts+++ b/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts@@ -150,6 +150,14 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {throw new Error(`Cannot set null content to ${constructorData.primaryKeyName} '${(this as any)[constructorData.primaryKeyName]}'`);}+ // Deny oversized content at the point a blob is created. Sync serialises blob content as a single+ // base64 JS string, so content above this threshold can never be synced (it would throw V8's+ // "Cannot create a string longer than 0x1fffffe8"); rejecting it here keeps un-syncable blobs out of+ // the database in the first place. See MAX_BLOB_CONTENT_LENGTH below for how the threshold is derived.+ if (exceedsBlobContentLimit(content)) {+ throw new Error(`Content is too large to store: the maximum is ${MAX_BLOB_CONTENT_LENGTH} bytes (~${Math.round(MAX_BLOB_CONTENT_LENGTH / 1024 / 1024)} MiB), beyond which it can no longer be synchronised.`);+ }+if (this.hasStringContent()) {content = unwrapStringOrBuffer(content);} else {@@ -334,3 +342,48 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}export default AbstractBeccaEntity;++/**+ * Maximum byte length of a single blob's content.+ *+ * The sync protocol serialises a blob's content as **one base64 JS string** embedded in a JSON+ * request body (see `sync.ts` `getEntityChangeRow`). Two ceilings bound that encoded form:+ *+ * 1. **V8's maximum string length** — `0x1fffffe8` = 536,870,888 bytes (empirically+ * `require("buffer").constants.MAX_STRING_LENGTH` on 64-bit). A blob whose base64 form exceeds+ * it can never be encoded, throwing `Cannot create a string longer than 0x1fffffe8 characters`+ * and wedging sync — the original motivation for the import size cap (zadam/trilium#3108).+ * 2. **The HTTP JSON body limit** — `express.json({ limit: "500mb" })` in `apps/server/src/app.ts`,+ * which the *receiving* instance parses every sync push through.+ *+ * base64 inflates by 4/3, so the largest blob whose encoded form clears the **tighter** of the two+ * ceilings — minus headroom for the surrounding JSON envelope (field names, the entity-change+ * metadata, quotes) — is the real limit. With the body limit binding, that lands at ~373 MiB.+ *+ * This replaces the blunt 250 MiB multipart-upload cap, which conflated the size of an *archive*+ * (e.g. a ZIP, whose many entries are each their own blob) with the size of a single blob, and —+ * because it bounded only the *compressed* upload — didn't reliably protect against an oversized+ * blob decompressed out of a small archive anyway.+ */+const V8_MAX_STRING_LENGTH = 536_870_888;+const HTTP_BODY_LIMIT = 500 * 1024 * 1024;+const JSON_ENVELOPE_MARGIN = 2 * 1024 * 1024;++export const MAX_BLOB_CONTENT_LENGTH = Math.floor(((Math.min(V8_MAX_STRING_LENGTH, HTTP_BODY_LIMIT) - JSON_ENVELOPE_MARGIN) * 3) / 4);++/**+ * Whether `content` exceeds {@link MAX_BLOB_CONTENT_LENGTH} once measured the way sync will encode it+ * (UTF-8 bytes for string content, raw bytes for binary). `limit` is injectable for testing.+ */+export function exceedsBlobContentLimit(content: string | Uint8Array, limit = MAX_BLOB_CONTENT_LENGTH): boolean {+ if (typeof content !== "string") {+ return content.length > limit;+ }+ // A UTF-16 code unit encodes to at most 3 UTF-8 bytes (surrogate pairs average 2 bytes/unit), so+ // this cheap upper bound avoids encoding the whole string in the common case; only when it's close+ // to the limit do we pay for an exact measurement.+ if (content.length * 3 <= limit) {+ return false;+ }+ return encodeUtf8(content).length > limit;+}