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(server): stream import uploads to disk instead of buffering in memory
Elian Doranb3dabe915be4
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.tsnew file mode 100644index 0000000000..da24c45a22--- /dev/null+++ b/apps/server/src/routes/route_api.spec.ts@@ -0,0 +1,42 @@+import express from "express";+import { existsSync } from "fs";+import request from "supertest";+import { describe, expect, it } from "vitest";++import { importMiddlewareWithErrorHandling } from "./route_api.js";++/** Minimal app mounting only the import middleware + a handler that reports what it received. */+function buildApp() {+ const app = express();+ app.post("/import", importMiddlewareWithErrorHandling, (req, res) => {+ const file = req.file;+ res.json({+ hasFile: !!file,+ content: file?.buffer?.toString("utf-8"),+ originalname: file?.originalname,+ // The unlink is awaited before the handler runs, so by now the temp file is already gone.+ tempStillExists: file?.path ? existsSync(file.path) : null+ });+ });+ return app;+}++describe("importMiddlewareWithErrorHandling (disk storage)", () => {+ it("streams the upload to disk, exposes it as file.buffer, and removes the temp file", async () => {+ const res = await request(buildApp())+ .post("/import")+ .attach("upload", Buffer.from("zip-bytes-here"), "vault.zip");++ expect(res.status).toBe(200);+ expect(res.body.content).toBe("zip-bytes-here");+ expect(res.body.originalname).toBe("vault.zip");+ expect(res.body.tempStillExists).toBe(false);+ });++ it("proceeds to the handler when no file is uploaded", async () => {+ const res = await request(buildApp()).post("/import");++ expect(res.status).toBe(200);+ expect(res.body.hasFile).toBe(false);+ });+});diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.tsindex dd75141895..26c734e31a 100644--- a/apps/server/src/routes/route_api.ts+++ b/apps/server/src/routes/route_api.ts@@ -1,12 +1,16 @@-import { entity_changes as entityChangesService, NotFoundError, routes, ValidationError } from "@triliumnext/core";+import { entity_changes as entityChangesService, NotFoundError, routes, utils as coreUtils, ValidationError } from "@triliumnext/core";import express, { type RequestHandler } from "express";import type { ParamsDictionary } from "express-serve-static-core";+import { mkdirSync } from "fs";+import { readFile, rm } from "fs/promises";import multer from "multer";+import { join } from "path";import { namespace } from "../cls_provider.js";import auth from "../services/auth.js";import { cls } from "@triliumnext/core";import { getLog } from "@triliumnext/core";+import dataDirs from "../services/data_dir.js";import sql from "../services/sql.js";import { safeExtractMessageAndStackFromError } from "../services/utils.js";import { doubleCsrfProtection as csrfMiddleware } from "./csrf_protection.js";@@ -141,21 +145,24 @@ function handleException(e: unknown | Error, method: HttpMethod, path: string, r}-export 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). `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).+/**+ * Common multer options for every upload route.+ *+ * `fieldNestingDepth: 0` rejects any bracketed multipart field name — none of our routes consume nested+ * text fields — which activates multer 2.2.0's guard against CVE-2026-5079 (DoS via deeply-nested field+ * names). It is not yet in @types/multer 2.1.0, hence the local intersection type.+ *+ * There is deliberately no `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).+ */+function baseMulterOptions(): multer.Options {const limits: NonNullable<multer.Options["limits"]> & { fieldNestingDepth?: number } = {fieldNestingDepth: 0};- const multerOptions: multer.Options = {+ return {limits,fileFilter: (req: express.Request, file, cb) => {// UTF-8 file names are not well decoded by multer/busboy, so we handle the conversion on our side.@@ -164,20 +171,83 @@ export function createUploadMiddleware(): RequestHandler {cb(null, true);}};+}++export function createUploadMiddleware(): RequestHandler {+ // In-memory storage: small uploads (images, single files) that downstream handlers read as `file.buffer`.+ return multer(baseMulterOptions()).single("upload");+}- return multer(multerOptions).single("upload");+export function createImportUploadMiddleware(): RequestHandler {+ // Disk storage: imports can be large archives, so stream the upload to Trilium's tmp dir instead of+ // buffering the whole multipart in memory during the HTTP receive. The temp file is read back into+ // `file.buffer` and deleted by importMiddlewareWithErrorHandling before the handler runs.+ const outDir = join(dataDirs.TMP_DIR, "upload");+ mkdirSync(outDir, { recursive: true });++ return multer({+ ...baseMulterOptions(),+ storage: multer.diskStorage({+ destination: (req, file, cb) => cb(null, outDir),+ filename: (req, file, cb) => cb(null, `upload-${coreUtils.randomString(13)}.trilium`)+ })+ }).single("upload");}const uploadMiddleware = createUploadMiddleware();+const importUploadMiddleware = createImportUploadMiddleware();++/** Maps the multer field-nesting guard to a clean 400; returns true when the request was already answered. */+function rejectedNestedField(err: { code?: string } | undefined, res: express.Response): boolean {+ 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.");+ return true;+ }+ return false;+}export const uploadMiddlewareWithErrorHandling = function (req: express.Request, res: express.Response, next: express.NextFunction) {uploadMiddleware(req, res, (err) => {- 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.");- } else {+ if (!rejectedNestedField(err, res)) {next();}});};++export const importMiddlewareWithErrorHandling = function (req: express.Request, res: express.Response, next: express.NextFunction) {+ importUploadMiddleware(req, res, (err) => {+ if (rejectedNestedField(err, res)) {+ return;+ }+ if (err) {+ next(err);+ return;+ }+ void materializeUploadedImport(req.file, next);+ });+};++/**+ * diskStorage gives us `file.path` rather than `file.buffer`. The shared core import handlers still consume+ * `file.buffer`, so read the temp file back into it and delete the temp file before handing off — the unlink+ * is awaited so nothing is left behind even if the handler later throws. (Step 2 will stream importers+ * straight from the path instead of re-buffering here.)+ */+async function materializeUploadedImport(file: Express.Multer.File | undefined, next: express.NextFunction) {+ if (!file?.path) {+ next();+ return;+ }+ const tempPath = file.path;+ try {+ file.buffer = await readFile(tempPath);+ } catch (readErr) {+ next(readErr);+ return;+ } finally {+ await rm(tempPath, { force: true }).catch(() => {});+ }+ next();+}diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 47eb056b77..6d969967e8 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -38,7 +38,7 @@ import totp from './api/totp.js';import { doubleCsrfProtection as csrfMiddleware } from "./csrf_protection.js";import * as indexRoute from "./index.js";import loginRoute from "./login.js";-import { apiResultHandler, apiRoute, asyncApiRoute, asyncRoute, route, router, uploadMiddlewareWithErrorHandling } from "./route_api.js";+import { apiResultHandler, apiRoute, asyncApiRoute, asyncRoute, importMiddlewareWithErrorHandling, route, router, uploadMiddlewareWithErrorHandling } from "./route_api.js";// page routesimport setupRoute from "./setup.js";@@ -93,6 +93,7 @@ function register(app: express.Application) {checkCredentials: auth.checkCredentials,loginRateLimiter,uploadMiddlewareWithErrorHandling,+ importMiddlewareWithErrorHandling,csrfMiddleware});diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.tsindex 2664f4f0e3..bc1772c586 100644--- a/apps/standalone/src/lightweight/browser_routes.spec.ts+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts@@ -160,7 +160,7 @@ describe("route wrapper branches (via controlled handlers)", () => {it("provides no-op middleware and an init guard", async () => {buildRouter();// No-op middleware stubs do nothing and never throw.- for (const mw of [ctx.checkApiAuth, ctx.checkApiAuthOrElectron, ctx.checkCredentials, ctx.loginRateLimiter, ctx.uploadMiddlewareWithErrorHandling, ctx.csrfMiddleware]) {+ for (const mw of [ctx.checkApiAuth, ctx.checkApiAuthOrElectron, ctx.checkCredentials, ctx.loginRateLimiter, ctx.uploadMiddlewareWithErrorHandling, ctx.importMiddlewareWithErrorHandling, ctx.csrfMiddleware]) {expect(() => (mw as () => void)()).not.toThrow();}// checkAppNotInitialized throws while the DB is initialized...diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.tsindex 98e18e56c8..1be6260929 100644--- a/apps/standalone/src/lightweight/browser_routes.ts+++ b/apps/standalone/src/lightweight/browser_routes.ts@@ -285,6 +285,9 @@ export function registerRoutes(router: BrowserRouter): void {checkCredentials: noopMiddleware,loginRateLimiter: noopMiddleware,uploadMiddlewareWithErrorHandling: noopMiddleware,+ // The browser variant has no disk; uploads already arrive as a buffer (see browser_router.ts), so+ // imports use the same no-op middleware rather than the server's disk-storage one.+ importMiddlewareWithErrorHandling: noopMiddleware,csrfMiddleware: noopMiddleware});apiRoute('get', '/bootstrap', bootstrapRoute);diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 3ad3ba703c..7df95e6fed 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -52,10 +52,11 @@ interface SharedApiRoutesContext {loginRateLimiter: any;checkCredentials: any;uploadMiddlewareWithErrorHandling: any;+ importMiddlewareWithErrorHandling: any;csrfMiddleware: any;}-export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {+export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler, checkApiAuthOrElectron, checkAppNotInitialized, checkCredentials, loginRateLimiter, uploadMiddlewareWithErrorHandling, importMiddlewareWithErrorHandling, csrfMiddleware }: SharedApiRoutesContext) {apiRoute(GET, '/api/tree', treeApiRoute.getTree);apiRoute(PST, '/api/tree/load', treeApiRoute.load);@@ -149,8 +150,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutroute(GET, "/api/sync/stats", [], syncApiRoute.getStats, apiResultHandler);//#region Import/export- asyncRoute(PST, "/api/notes/:parentNoteId/notes-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);- route(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);+ asyncRoute(PST, "/api/notes/:parentNoteId/notes-import", [checkApiAuthOrElectron, importMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);+ route(PST, "/api/notes/:parentNoteId/attachments-import", [checkApiAuthOrElectron, importMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);asyncRoute(GET, "/api/branches/:branchId/export/:type/:format/:taskId", [checkApiAuthOrElectron], exportRoute.exportBranch);//#endregiondiff --git a/packages/trilium-core/src/test/api_tester.ts b/packages/trilium-core/src/test/api_tester.tsindex dc99a65f90..088352cb5a 100644--- a/packages/trilium-core/src/test/api_tester.ts+++ b/packages/trilium-core/src/test/api_tester.ts@@ -259,6 +259,7 @@ export class CoreApiTester {checkCredentials: noop,loginRateLimiter: noop,uploadMiddlewareWithErrorHandling: noop,+ importMiddlewareWithErrorHandling: noop,csrfMiddleware: noop});}