Skip to content

Build your personal knowledge base with Trilium Notes

fix(standalone): write uploaded files through the shared core routes

Elian Dorand15f903d61f2
diff --git a/apps/server/src/routes/api/core_routes_http.spec.ts b/apps/server/src/routes/api/core_routes_http.spec.ts
index 708bb626e9..c57844f55d 100644
--- a/apps/server/src/routes/api/core_routes_http.spec.ts
+++ b/apps/server/src/routes/api/core_routes_http.spec.ts
@@ -38,6 +38,25 @@ describe("Core routes over Express", () => {
expect(res.body.title).toBe("Via Express");
});
+ // The upload routes are the only core ones behind multer, so this is where that middleware —
+ // and the CSRF token a multipart PUT has to carry — is actually exercised.
+ it("takes a multipart upload on a core route", async () => {
+ const create = await ctx.agent
+ .post("/api/notes/root/children?target=into")
+ .set("x-csrf-token", ctx.csrfToken)
+ .send({ title: "notes.txt", type: "file", mime: "text/plain", content: "original" })
+ .expect(200);
+ const noteId = create.body.note.noteId as string;
+
+ await ctx.agent
+ .put(`/api/notes/${noteId}/file?replace=1`)
+ .set("x-csrf-token", ctx.csrfToken)
+ .attach("upload", Buffer.from("uploaded"), { filename: "notes.txt", contentType: "text/plain" })
+ .expect(200, { uploaded: true });
+
+ await ctx.agent.get(`/api/notes/${noteId}/open`).expect(200, "uploaded");
+ });
+
// Media players stream from open-partial, and only a real Express response can show that the
// slice leaves as bytes: `res.send()` treats anything that is not a Buffer as JSON.
it("answers a byte range on open-partial with 206 and the raw slice", async () => {
diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.ts
index c1f634c3e3..fd4f57bbda 100644
--- a/apps/server/src/routes/api/files.spec.ts
+++ b/apps/server/src/routes/api/files.spec.ts
@@ -24,37 +24,6 @@ describe("Files API", () => {
});
});
- describe("updateFile", () => {
- it("reports a missing file", () => {
- expect(cls.init(() => filesRoute.updateFile(fileReq({ noteId })))).toEqual({ uploaded: false, message: "Missing file." });
- });
-
- it("replaces note content without a revision when replace=1", () => {
- const file = { buffer: Buffer.from("replaced"), mimetype: "TEXT/Plain", originalname: "new.txt" };
- const result = cls.init(() => filesRoute.updateFile(fileReq({ noteId }, file, { replace: "1" })));
- expect(result).toEqual({ uploaded: true });
- expect(becca.getNoteOrThrow(noteId).mime).toBe("text/plain");
- });
-
- it("saves a revision when not replacing", () => {
- const file = { buffer: Buffer.from("v2"), mimetype: "text/plain", originalname: "v2.txt" };
- expect(cls.init(() => filesRoute.updateFile(fileReq({ noteId }, file)))).toEqual({ uploaded: true });
- });
- });
-
- describe("updateAttachment", () => {
- it("reports a missing file", () => {
- const req = fileReq({ attachmentId } as Record<string, string>) as unknown as Request<{ attachmentId: string }>;
- expect(cls.init(() => filesRoute.updateAttachment(req))).toEqual({ uploaded: false, message: "Missing file." });
- });
-
- it("updates attachment content", () => {
- const file = { buffer: Buffer.from("new-att"), mimetype: "text/plain", originalname: "a.txt" };
- const req = fileReq({ attachmentId } as Record<string, string>, file) as unknown as Request<{ attachmentId: string }>;
- expect(cls.init(() => filesRoute.updateAttachment(req))).toEqual({ uploaded: true });
- });
- });
-
describe("temp-dir round trip", () => {
it("saves a note to a temp file then uploads the modified content back", () => {
const { tmpFilePath } = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId })));
diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.ts
index 795e848f25..479da5b101 100644
--- a/apps/server/src/routes/api/files.ts
+++ b/apps/server/src/routes/api/files.ts
@@ -1,4 +1,4 @@
-import { note_service as noteService, ValidationError, ws } from "@triliumnext/core";
+import { ValidationError, ws } from "@triliumnext/core";
import chokidar from "chokidar";
import type { Request } from "express";
import fs from "fs";
@@ -10,55 +10,6 @@ import dataDirs from "../../services/data_dir.js";
import { getLog } from "@triliumnext/core";
import utils from "../../services/utils.js";
-function updateFile(req: Request<{ noteId: string }>) {
- const note = becca.getNoteOrThrow(req.params.noteId);
-
- const file = req.file;
- if (!file) {
- return {
- uploaded: false,
- message: `Missing file.`
- };
- }
-
- if (req.query.replace !== "1") {
- note.saveRevision();
- }
-
- note.mime = file.mimetype.toLowerCase();
- note.save();
-
- note.setContent(file.buffer);
-
- note.setLabel("originalFileName", file.originalname);
-
- void noteService.asyncPostProcessContent(note, file.buffer);
-
- return {
- uploaded: true
- };
-}
-
-function updateAttachment(req: Request<{ attachmentId: string }>) {
- const attachment = becca.getAttachmentOrThrow(req.params.attachmentId);
- const file = req.file;
- if (!file) {
- return {
- uploaded: false,
- message: `Missing file.`
- };
- }
-
- attachment.getNote().saveRevision();
-
- attachment.mime = file.mimetype.toLowerCase();
- attachment.setContent(file.buffer, { forceSave: true });
-
- return {
- uploaded: true
- };
-}
-
function saveNoteToTmpDir(req: Request<{ noteId: string }>) {
const note = becca.getNoteOrThrow(req.params.noteId);
const fileName = note.getFileName();
@@ -183,8 +134,6 @@ function uploadModifiedFileToAttachment(req: Request<{ attachmentId: string }>)
}
export default {
- updateFile,
- updateAttachment,
saveNoteToTmpDir,
saveAttachmentToTmpDir,
uploadModifiedFileToNote,
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 2eca9048cf..ab3e22181a 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -43,7 +43,6 @@ import setupRoute from "./setup.js";
const GET = "get",
PST = "post",
- PUT = "put",
PATCH = "patch",
DEL = "delete";
@@ -111,13 +110,11 @@ function register(app: express.Application) {
csrfMiddleware
});
- route(PUT, "/api/notes/:noteId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);
apiRoute(PST, "/api/notes/:noteId/save-to-tmp-dir", filesRoute.saveNoteToTmpDir);
apiRoute(PST, "/api/notes/:noteId/upload-modified-file", filesRoute.uploadModifiedFileToNote);
apiRoute(PST, "/api/attachments/:attachmentId/save-to-tmp-dir", filesRoute.saveAttachmentToTmpDir);
apiRoute(PST, "/api/attachments/:attachmentId/upload-modified-file", filesRoute.uploadModifiedFileToAttachment);
- route(PUT, "/api/attachments/:attachmentId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateAttachment, apiResultHandler);
apiRoute(GET, "/api/metrics", metricsRoute.getMetrics);
apiRoute(GET, "/api/system-checks", systemInfoRoute.systemChecks);
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
index 897447157a..1a8bf5579f 100644
--- a/apps/standalone/src/lightweight/browser_routes.spec.ts
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -60,6 +60,31 @@ describe("registerRoutes (real wiring)", () => {
expect(extra.isMainWindow).toBe(false);
});
+ // The upload path end to end: a real FormData body, parsed by the router into the `req.file`
+ // the handler reads. What the PDF viewer saves annotations through, and what "upload new
+ // revision" sends — on the server multer builds that object, here the router does.
+ it("writes an uploaded file over a note", async () => {
+ const created = parseJson((await router.dispatch("POST", "http://localhost/api/notes/root/children?target=into",
+ { title: "notes.txt", type: "file", mime: "text/plain", content: "original" })).body) as { note: { noteId: string } };
+ const { noteId } = created.note;
+
+ const form = new FormData();
+ form.append("upload", new File([ "uploaded" ], "notes.txt", { type: "text/plain" }));
+ // One Response for both: each encoding of a FormData picks its own boundary, so a body and a
+ // content-type taken from two of them describe different messages and parse as neither.
+ const encoded = new Response(form);
+ const contentType = encoded.headers.get("content-type") ?? "";
+ const body = await encoded.arrayBuffer();
+
+ const res = await router.dispatch("PUT", `http://localhost/api/notes/${noteId}/file?replace=1`, body, {
+ "content-type": contentType
+ });
+
+ expect(res.status).toBe(200);
+ expect(parseJson(res.body)).toEqual({ uploaded: true });
+ expect(text((await router.dispatch("GET", `http://localhost/api/notes/${noteId}/open`)).body)).toBe("uploaded");
+ });
+
// The whole standalone media path in one request: the core handler slices the note's content,
// the mock response carries the slice out as a raw response, and the router turns the view into
// exactly those bytes. This is what an <audio>/<video> element does every time it seeks.
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index fd50e288a4..92d925c322 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -124,6 +124,79 @@ describe("Files API (core)", () => {
});
});
+ /**
+ * Writing a file back over a note or an attachment: "upload new revision" on a file note, the
+ * PDF viewer saving its annotations, and replacing an attachment's file. The upload arrives as
+ * `req.file` — multipart parsed by multer on the server, by the router itself in standalone.
+ */
+ describe("file uploads", () => {
+ async function createFileNote(content = "original"): Promise<string> {
+ const res = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {
+ body: { title: "notes.txt", type: "file", mime: "text/plain", content }
+ });
+ expect(res.status).toBe(200);
+ return res.body.note.noteId;
+ }
+
+ function upload(content: string, mimetype = "text/plain", originalname = "new.txt") {
+ return { buffer: encodeUtf8(content), mimetype, originalname };
+ }
+
+ async function revisionCount(noteId: string): Promise<number> {
+ const res = await api.get<unknown[]>(`/api/notes/${noteId}/revisions`);
+ return res.body.length;
+ }
+
+ it("writes an uploaded file over a note, normalising the mime and recording the file name", async () => {
+ const noteId = await createFileNote();
+
+ const res = await api.put(`/api/notes/${noteId}/file`, { file: upload("replaced", "TEXT/Plain") });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ uploaded: true });
+
+ const note = becca.getNoteOrThrow(noteId);
+ expect(note.getContent().toString()).toBe("replaced");
+ expect(note.mime).toBe("text/plain");
+ expect(note.getOwnedLabelValue("originalFileName")).toBe("new.txt");
+ });
+
+ it("keeps a revision of what it replaced, unless the caller asks to replace outright", async () => {
+ const kept = await createFileNote();
+ expect(await revisionCount(kept)).toBe(0);
+ await api.put(`/api/notes/${kept}/file`, { file: upload("v2") });
+ expect(await revisionCount(kept)).toBe(1);
+
+ // `replace=1` is for an editor saving its own work, which would otherwise bury the note
+ // in revisions — one per save.
+ const replaced = await createFileNote();
+ await api.put(`/api/notes/${replaced}/file?replace=1`, { file: upload("v2") });
+ expect(await revisionCount(replaced)).toBe(0);
+ expect(becca.getNoteOrThrow(replaced).getContent().toString()).toBe("v2");
+ });
+
+ it("replaces an attachment's file, keeping a revision of the note holding it", async () => {
+ const noteId = await createFileNote();
+ expect((await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "file", mime: "text/plain", title: "att.txt", content: "att-data" }
+ })).status).toBe(204);
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const { attachmentId } = list.body[0];
+
+ const res = await api.put(`/api/attachments/${attachmentId}/file`, { file: upload("new-att") });
+ expect(res.body).toEqual({ uploaded: true });
+ expect(becca.getAttachmentOrThrow(attachmentId).getContent().toString()).toBe("new-att");
+ expect(await revisionCount(noteId)).toBe(1);
+ });
+
+ it("reports a request that carries no file instead of writing an empty one", async () => {
+ const noteId = await createFileNote();
+
+ const res = await api.put(`/api/notes/${noteId}/file`);
+ expect(res.body).toEqual({ uploaded: false, message: "Missing file." });
+ expect(becca.getNoteOrThrow(noteId).getContent().toString()).toBe("original");
+ });
+ });
+
/**
* What the audio/video players stream from. A media element seeks by re-requesting a byte range,
* so these have to answer 206 with exactly the slice asked for — a full body every time would
diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.ts
index c3d232c0c3..8ecd187d5c 100644
--- a/packages/trilium-core/src/routes/api/files.ts
+++ b/packages/trilium-core/src/routes/api/files.ts
@@ -2,11 +2,15 @@ import { Request, Response } from "express";
import becca from "../../becca/becca";
import type BAttachment from "../../becca/entities/battachment";
import type BNote from "../../becca/entities/bnote";
+import type { File } from "../../services/import/common.js";
+import noteService from "../../services/notes.js";
import { convertOfficeToHtml } from "../../services/office_preview.js";
import protected_session from "../../services/protected_session";
import { downloadData, downloadNoteInt } from "../helpers";
import { serveContentWithRanges } from "../partial_content";
+type FileRequest<P> = Omit<Request<P>, "file"> & { file?: File };
+
const downloadFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, true);
const openFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, false);
@@ -38,6 +42,61 @@ function openPartialAttachment(req: Request<{ attachmentId: string }>, res: Resp
return openPartialInt(attachment, req, res);
}
+/**
+ * Writes an uploaded file over a file note's content: what "upload new revision" sends, and what the
+ * PDF viewer saves annotations through. `replace=1` writes straight over the content — for an editor
+ * saving its own work, where a revision per save would bury the note in them.
+ */
+function updateFile(req: FileRequest<{ noteId: string }>) {
+ const note = becca.getNoteOrThrow(req.params.noteId);
+
+ const file = req.file;
+ if (!file) {
+ return {
+ uploaded: false,
+ message: `Missing file.`
+ };
+ }
+
+ if (req.query.replace !== "1") {
+ note.saveRevision();
+ }
+
+ note.mime = file.mimetype.toLowerCase();
+ note.save();
+
+ note.setContent(file.buffer);
+
+ note.setLabel("originalFileName", file.originalname);
+
+ void noteService.asyncPostProcessContent(note, file.buffer);
+
+ return {
+ uploaded: true
+ };
+}
+
+/** The attachment counterpart of {@link updateFile}: replacing an attachment's file with another. */
+function updateAttachment(req: FileRequest<{ attachmentId: string }>) {
+ const attachment = becca.getAttachmentOrThrow(req.params.attachmentId);
+ const file = req.file;
+ if (!file) {
+ return {
+ uploaded: false,
+ message: `Missing file.`
+ };
+ }
+
+ attachment.getNote().saveRevision();
+
+ attachment.mime = file.mimetype.toLowerCase();
+ attachment.setContent(file.buffer, { forceSave: true });
+
+ return {
+ uploaded: true
+ };
+}
+
/**
* Converts an office document note/attachment to an embeddable HTML fragment for the
* inline preview shown by the client. The returned HTML is unsanitized — the client
@@ -84,6 +143,8 @@ export default {
downloadFile,
openPartialFile,
openPartialAttachment,
+ updateFile,
+ updateAttachment,
openAttachment,
downloadAttachment,
getNoteOfficePreview,
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index c8c769dd93..27bc1db88e 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -260,6 +260,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
// this "hacky" path is used for easier referencing of CSS resources
route(GET, "/api/attachments/download/:attachmentId", [checkApiAuthOrElectron], filesRoute.downloadAttachment);
route(GET, "/api/revisions/:revisionId/download", [checkApiAuthOrElectron], revisionsApiRoute.downloadRevision);
+ route(PUT, "/api/notes/:noteId/file", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);
+ route(PUT, "/api/attachments/:attachmentId/file", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateAttachment, apiResultHandler);
//#endregion
//#region Export