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
chore(server): drop tmp for native fs temp files
Elian Doran560da95590e8
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 4044edd517..f32b9737a5 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -61,7 +61,6 @@"@types/serve-favicon": "2.5.7","@types/serve-static": "2.2.0","@types/supertest": "7.2.1",- "@types/tmp": "0.2.6","@types/ws": "8.18.2","@types/yauzl": "3.4.0","archiver": "8.0.0",@@ -95,7 +94,6 @@"supertest": "7.3.1","tesseract.js": "7.0.0","time2fa": "1.4.2",- "tmp": "0.2.7","upng-js": "2.1.0","vite": "8.3.5","yauzl": "3.4.0"diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.tsindex 0316068ca0..bcddc11032 100644--- a/apps/server/src/routes/api/files.spec.ts+++ b/apps/server/src/routes/api/files.spec.ts@@ -2,8 +2,10 @@ import { CANVAS_ATTACHMENT_MIME } from "@triliumnext/commons";import { becca, cls, note_service as noteService, ValidationError } from "@triliumnext/core";import type { Request } from "express";import fs from "fs";+import path from "path";import { beforeAll, describe, expect, it } from "vitest";+import dataDirs from "../../services/data_dir.js";import filesRoute from "./files.js";let noteId: string;@@ -29,6 +31,11 @@ describe("Files API", () => {it("saves a note to a temp file then uploads the modified content back", () => {const { tmpFilePath } = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId })));expect(fs.existsSync(tmpFilePath)).toBe(true);+ expect(path.dirname(tmpFilePath)).toBe(path.resolve(dataDirs.TMP_DIR));+ expect(path.basename(tmpFilePath)).toMatch(/^tmp-\d+-\w{12}-File note\.txt$/);+ if (process.platform !== "win32") {+ expect(fs.statSync(tmpFilePath).mode & 0o777).toBe(0o600);+ }fs.writeFileSync(tmpFilePath, "edited-on-disk");cls.init(() => filesRoute.uploadModifiedFileToNote(fileReq({ noteId }, undefined, {}, { filePath: tmpFilePath })));@@ -75,5 +82,14 @@ describe("Files API", () => {const req = fileReq({ attachmentId } as Record<string, string>, undefined, {}, { filePath: "/nope" }) as unknown as Request<{ attachmentId: string }>;expect(() => cls.init(() => filesRoute.uploadModifiedFileToAttachment(req))).toThrow(ValidationError);});++ it("removes the temp files when the process exits", () => {+ const { tmpFilePath } = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId })));+ const cleanup = process.listeners("exit").find((listener) => listener.name === "removeTemporaryFiles");+ expect(cleanup).toBeDefined();++ cleanup?.(0);+ expect(fs.existsSync(tmpFilePath)).toBe(false);+ });});});diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.tsindex 0967ed499f..ba5ec4ff49 100644--- a/apps/server/src/routes/api/files.ts+++ b/apps/server/src/routes/api/files.ts@@ -3,7 +3,6 @@ import chokidar from "chokidar";import type { Request } from "express";import fs from "fs";import path from "path";-import tmp from "tmp";import { becca, note_service as noteService } from "@triliumnext/core";import dataDirs from "../../services/data_dir.js";@@ -32,40 +31,40 @@ function saveAttachmentToTmpDir(req: Request<{ attachmentId: string }>) {const createdTemporaryFiles = new Set<string>();function saveToTmpDir(fileName: string, content: string | Uint8Array, entityType: string, entityId: string) {- const tmpObj = tmp.fileSync({- postfix: fileName,- tmpdir: dataDirs.TMP_DIR- });-- if (typeof content === "string") {- fs.writeSync(tmpObj.fd, content);- } else {- fs.writeSync(tmpObj.fd, content);- }-- fs.closeSync(tmpObj.fd);+ const tmpFileName = `tmp-${process.pid}-${utils.randomString(12)}-${fileName}`;+ const tmpFilePath = path.resolve(dataDirs.TMP_DIR, tmpFileName);+ fs.writeFileSync(tmpFilePath, content, { flag: "wx", mode: 0o600 });- createdTemporaryFiles.add(tmpObj.name);+ if (createdTemporaryFiles.size === 0) {+ process.once("exit", removeTemporaryFiles);+ }+ createdTemporaryFiles.add(tmpFilePath);- getLog().info(`Saved temporary file ${tmpObj.name}`);+ getLog().info(`Saved temporary file ${tmpFilePath}`);if (utils.isElectron) {- chokidar.watch(tmpObj.name).on("change", (path, stats) => {+ chokidar.watch(tmpFilePath).on("change", (path, stats) => {ws.sendMessageToAllClients({type: "openedFileUpdated",entityType,entityId,lastModifiedMs: stats?.atimeMs,- filePath: tmpObj.name+ filePath: tmpFilePath});});}return {- tmpFilePath: tmpObj.name+ tmpFilePath};}+function removeTemporaryFiles() {+ for (const filePath of createdTemporaryFiles) {+ fs.rmSync(filePath, { force: true });+ }+}+/*** Validates that the given file path is a known temporary file created by this server* and resides within the expected temporary directory. This prevents path traversaldiff --git a/apps/server/src/www.ts b/apps/server/src/www.tsindex 77a4ece31f..6cf778d87a 100644--- a/apps/server/src/www.ts+++ b/apps/server/src/www.ts@@ -4,7 +4,6 @@ import fs from "fs";import http from "http";import https from "https";import { networkInterfaces } from "os";-import tmp from "tmp";import buildApp from "./app.js";import { TRILIUM_LOGO } from "./log_provider.js";@@ -68,8 +67,6 @@ export default async function startTriliumServer(): Promise<Express> {process.exit(1);}- tmp.setGracefulCleanup();-const app = await buildApp();const httpServer = startHttpServer(app);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e5bb61e94f..0c3f28396c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -728,9 +728,6 @@ importers:'@types/supertest':specifier: 7.2.1version: 7.2.1- '@types/tmp':- specifier: 0.2.6- version: 0.2.6'@types/ws':specifier: 8.18.2version: 8.18.2@@ -830,9 +827,6 @@ importers:time2fa:specifier: 1.4.2version: 1.4.2- tmp:- specifier: 0.2.7- version: 0.2.7upng-js:specifier: 2.1.0version: 2.1.0@@ -4942,9 +4936,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-H4xtYl8Dy/g4SrNnZx+oEK/N5+FLLEGTuU3MM7bpUUk3gtYy5aYqSjxQ1pqITnQ/PKHqV1aD4Zd5xels9AnPSA==}- '@types/[email protected]':- resolution: {integrity: sha512-chhaNf2oKHlRkDGt+tiKE2Z5aJ6qalm7Z9rlLdBwmOiAAf09YQvvoLXjWK4HWPF1xU/fqvMgfNfpVoBscA/tKA==}-'@types/[email protected]':resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}@@ -15924,8 +15915,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]':optional: true