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
client/options/database: reveal the database file after clicking the location link
Adorian Doran8ba6ed48f1de
diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.tsindex 07891052d8..22b6fb542a 100644--- a/apps/client/src/services/open.ts+++ b/apps/client/src/services/open.ts@@ -156,6 +156,22 @@ async function openDirectory(directory: string) {}}+/**+ * Shows a file in the file manager, selected, rather than opening it — which is what to do with a+ * file the user has no reader for. The database is the one such file Trilium points at.+ *+ * Nothing comes back, so nothing can be reported: the OS is asked to bring a window forward, and+ * whether it did is not something Electron answers.+ */+function revealFile(filePath: string) {+ if (!utils.isElectron()) {+ console.error("Not running in an Electron environment.");+ return;+ }++ window.electronApi?.shell.showItemInFolder(filePath);+}+/** Reported to the user, not only the console: a silent failure reads as the link doing nothing at all. */function reportDirectoryFailure(directory: string, reason: string) {console.error("Failed to open directory:", directory, reason);@@ -173,5 +189,6 @@ export default {openNoteCustom,openAttachmentCustom,openNoteOnServer,- openDirectory+ openDirectory,+ revealFile};diff --git a/apps/client/src/widgets/react/DirectoryLink.tsx b/apps/client/src/widgets/react/DirectoryLink.tsxindex 5ba37ec951..9f2d22521f 100644--- a/apps/client/src/widgets/react/DirectoryLink.tsx+++ b/apps/client/src/widgets/react/DirectoryLink.tsx@@ -1,31 +1,33 @@-import type { ComponentChildren } from "preact";-import openService from "../../services/open.js";import { isElectron } from "../../services/utils.js";-interface DirectoryLinkProps {- directory: string;- /**- * What to show in place of the path itself, for a link that stands for something inside the- * directory it opens — a file, named in full, with the file manager landing on its folder.- */- children?: ComponentChildren;-}-/**- * A filesystem location, opened in the OS file manager on click. Only the desktop application can+ * A filesystem location, handed to the OS file manager on click. Only the desktop application can* open anything, so everywhere else the path is shown as plain (selectable) text.*/-export default function DirectoryLink({ directory, children }: DirectoryLinkProps) {- const label = children ?? directory;+function ShellLink({ path, onOpen }: { path: string; onOpen: () => void }) {+ if (!isElectron()) {+ return <span className="selectable-text">{path}</span>;+ }- if (isElectron()) {- const onClick = (e: MouseEvent) => {- e.preventDefault();- openService.openDirectory(directory);- };+ const onClick = (e: MouseEvent) => {+ e.preventDefault();+ onOpen();+ };- return <a className="tn-link selectable-text" href="#" onClick={onClick}>{label}</a>;- }- return <span className="selectable-text">{label}</span>;+ return <a className="tn-link selectable-text" href="#" onClick={onClick}>{path}</a>;+}++/** A directory, opened in the file manager. */+export default function DirectoryLink({ directory }: { directory: string }) {+ return <ShellLink path={directory} onOpen={() => openService.openDirectory(directory)} />;+}++/**+ * A file, revealed in the file manager: the folder holding it opens with the file itself selected.+ * For a file the user is meant to find rather than to open, the database being the one Trilium+ * points at — opening that would hand it to whatever program claims the extension.+ */+export function FileLink({ filePath }: { filePath: string }) {+ return <ShellLink path={filePath} onOpen={() => openService.revealFile(filePath)} />;}diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsxindex 0e08f3add4..517f9d64a5 100644--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx@@ -17,7 +17,6 @@ vi.mock("../../../services/setup_mode", () => setupMode);const DATABASE_INFO = {filePath: "/data/trilium/document.db",- directoryPath: "/data/trilium",utcDateCreated: "2020-05-17 08:30:00.000Z",noteCount: 12,attachmentCount: 3,diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsxindex 68ef11b180..5e0642c3cf 100644--- a/apps/client/src/widgets/type_widgets/options/database.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.tsx@@ -26,7 +26,7 @@ import { formatDateTime } from "../../../utils/formatters";import Admonition from "../../react/Admonition";import Button from "../../react/Button";import { Card, CardOption } from "../../react/Card";-import DirectoryLink from "../../react/DirectoryLink";+import { FileLink } from "../../react/DirectoryLink";import { useNoteContext } from "../../react/hooks";import { useFetch } from "../../react/use_fetch";import DatabaseFileList from "./components/DatabaseFileList";@@ -108,10 +108,10 @@ function DatabaseInfo({ refreshToken }: { refreshToken: number }) {<div className="options-section database-info"><Card heading={t("database.info")}><CardOption label={t("database.info_location")}>- {/* The file is named in full, while the link opens the folder holding it: a- file manager is what the path is useful in, not the database's own reader. */}+ {/* Revealed rather than opened: a file manager is what the path is useful in,+ and the database's own reader is Trilium. */}<span className="database-info-value">- <DirectoryLink directory={info.directoryPath}>{info.filePath}</DirectoryLink>+ <FileLink filePath={info.filePath} /></span></CardOption>diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 524aaf6bef..eaca6a4bfc 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -308,6 +308,14 @@ describe("preload script", () => {});});+ it("showItemInFolder sends correct IPC message", () => {+ shell().showItemInFolder("/tmp/test.txt");+ expect(ipcRendererSent).toContainEqual({+ channel: "show-item-in-folder",+ args: ["/tmp/test.txt"]+ });+ });+it("openFileUrl invokes correct IPC channel", async () => {await shell().openFileUrl("file:///tmp/test.txt");expect(ipcRendererInvoked).toContainEqual({diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex eabfb28f7e..357314662e 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -134,6 +134,9 @@ contextBridge.exposeInMainWorld("electronApi", {openPath(path: string): Promise<string> {return ipcRenderer.invoke("open-path", path);},+ showItemInFolder(path: string) {+ ipcRenderer.send("show-item-in-folder", path);+ },openFileUrl(fileUrl: string): Promise<string> {return ipcRenderer.invoke("open-file-url", fileUrl);},diff --git a/apps/desktop/src/services/shell.spec.ts b/apps/desktop/src/services/shell.spec.tsindex e567a64152..c335e1575d 100644--- a/apps/desktop/src/services/shell.spec.ts+++ b/apps/desktop/src/services/shell.spec.ts@@ -205,6 +205,28 @@ describe("validateOpenPath", () => {});});+ describe("a file as a root of its own (the database, wherever it is kept)", () => {+ let documentPath: string;++ beforeAll(() => {+ documentPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "trilium-open-path-db-")), "document.db");+ fs.writeFileSync(documentPath, "");+ });++ afterAll(() => fs.rmSync(path.dirname(documentPath), { recursive: true, force: true }));++ it("accepts that exact file, and nothing else beside it", () => {+ expect(validateOpenPath(documentPath, dataDir, tmpDir, null, documentPath))+ .toBe(path.resolve(documentPath));++ // Naming a file as a root widens the sandbox by one path, not by the directory it is in.+ const sibling = path.join(path.dirname(documentPath), "document.db-wal");+ fs.writeFileSync(sibling, "");+ expect(() => validateOpenPath(sibling, dataDir, tmpDir, null, documentPath))+ .toThrow(/outside data dir/);+ });+ });+it("accepts files under the data directory", () => {expect(validateOpenPath(dataFile, dataDir, tmpDir)).toBe(path.resolve(dataFile));});diff --git a/apps/desktop/src/services/shell.ts b/apps/desktop/src/services/shell.tsindex 6a7ef23ec4..c2e8ef2965 100644--- a/apps/desktop/src/services/shell.ts+++ b/apps/desktop/src/services/shell.ts@@ -68,26 +68,30 @@ export function validateOpenCustomPath(filePath: unknown, tmpDir: string): strin/*** Validates a path for the "open-path" IPC channel (Open Note Externally,* Open Attachment Externally, and the "open data directory" / "open backup- * directory" links in the About dialog and the backup settings). The legit- * callers only ever pass server-generated paths either inside the tmp dir or- * equal to one of the directories themselves.+ * directory" links in the About dialog and the backup settings), and for the+ * "show-item-in-folder" channel, which reveals a file rather than opening it.+ * The legit callers only ever pass server-generated paths either inside the tmp+ * dir or equal to one of the directories themselves.*- * `backupDir` is a root of its own because the user may have moved backups- * outside the data directory. It is resolved from the app's own configuration- * rather than taken from the renderer, so the sandbox still bounds the caller.+ * Beyond the data and tmp directories, each caller names the roots its own case+ * needs: the backup directory, which the user may have moved elsewhere, and the+ * database file, which `TRILIUM_DOCUMENT_PATH` may likewise put outside the+ * data directory. Those come from the app's own configuration rather than from+ * the renderer, so the sandbox still bounds the caller. A root may be a file, in+ * which case only that exact path passes.** UNC paths are blocked implicitly — they cannot normalise to a descendant* of those roots, so the sandbox check rejects them. This closes the* NTLM-hash-leak vector that affects file:// and smb:// URLs.*/-export function validateOpenPath(input: unknown, dataDir: string, tmpDir: string, backupDir?: string | null): string {+export function validateOpenPath(input: unknown, dataDir: string, tmpDir: string, ...extraRoots: (string | null | undefined)[]): string {if (typeof input !== "string" || input.length === 0 || input.includes("\0")) {throw new Error("open-path: invalid filePath");}- const roots = backupDir ? [dataDir, tmpDir, backupDir] : [dataDir, tmpDir];+ const roots = [dataDir, tmpDir, ...extraRoots];const resolved = path.resolve(input);- if (!roots.some((root) => isUnderOrEquals(resolved, root))) {+ if (!roots.some((root) => root && isUnderOrEquals(resolved, root))) {throw new Error(`open-path: refusing path outside data dir: ${resolved}`);}@@ -256,6 +260,18 @@ export function setupShellHandlers() {}});+ // Nothing is returned: `showItemInFolder` reports nothing back, and a refused path is a+ // main-process log line rather than an answer the renderer could act on.+ electron.ipcMain.on("show-item-in-folder", (_event, filePath: string) => {+ try {+ const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR,+ getConfiguredBackupDir(), dataDirs.DOCUMENT_PATH);+ electron.shell.showItemInFolder(resolved);+ } catch (e) {+ getLog().error(`show-item-in-folder failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ }+ });+electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {try {const filePath = validateOpenFileUrl(fileUrl);diff --git a/apps/desktop/src/services/shell_handlers.spec.ts b/apps/desktop/src/services/shell_handlers.spec.tsindex e69d0b496d..efcdc4b595 100644--- a/apps/desktop/src/services/shell_handlers.spec.ts+++ b/apps/desktop/src/services/shell_handlers.spec.ts@@ -9,6 +9,7 @@ const h = vi.hoisted(() => ({handle: new Map<string, Handler>(),openExternal: vi.fn(),openPath: vi.fn(() => Promise.resolve("")),+ showItemInFolder: vi.fn(),execFile: vi.fn()}));@@ -20,7 +21,8 @@ vi.mock("electron", () => ({},shell: {openExternal: h.openExternal,- openPath: h.openPath+ openPath: h.openPath,+ showItemInFolder: h.showItemInFolder}}}));@@ -104,6 +106,18 @@ describe("setupShellHandlers", () => {});});+ describe("show-item-in-folder", () => {+ it("reveals a file inside the sandbox", () => {+ fireOn("show-item-in-folder", dataFile);+ expect(h.showItemInFolder).toHaveBeenCalledWith(path.resolve(dataFile));+ });++ it("reveals nothing for a path outside the sandbox", () => {+ fireOn("show-item-in-folder", process.platform === "win32" ? "C:\\Windows\\evil" : "/etc/passwd");+ expect(h.showItemInFolder).not.toHaveBeenCalled();+ });+ });+describe("open-file-url", () => {it("opens a valid file: URL", () => {const url = process.platform === "win32" ? "file:///C:/Windows/notepad.exe" : "file:///etc/hosts";diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.tsindex 2568810ec4..48d1513397 100644--- a/apps/server/src/routes/api/database.spec.ts+++ b/apps/server/src/routes/api/database.spec.ts@@ -29,12 +29,9 @@ describe("Database API", () => {it("describes the database: where it is, when it began, what it holds and how large it is", () => {const info = databaseRoute.getDatabaseInfo();- const filePath = path.resolve(dataDir.DOCUMENT_PATH);- // The file is named in full, and the directory separately: what a file manager can be- // pointed at is the folder, never the database itself.- expect(info.filePath).toBe(filePath);- expect(info.directoryPath).toBe(path.dirname(filePath));+ // Named in full: the desktop reveals the file in the file manager rather than opening it.+ expect(info.filePath).toBe(path.resolve(dataDir.DOCUMENT_PATH));// SQLite records nothing about when a file was made, so the root note answers for it.expect(info.utcDateCreated).toBe(becca.getNoteOrThrow("root").utcDateCreated);diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.tsindex 1a97eed1a6..303bea274d 100644--- a/apps/server/src/routes/api/database.ts+++ b/apps/server/src/routes/api/database.ts@@ -27,11 +27,8 @@ function getExistingBackups() {* made, and the root is created once, by the very first startup that had no database to open.*/function getDatabaseInfo() {- const filePath = path.resolve(dataDir.DOCUMENT_PATH);-return {- filePath,- directoryPath: path.dirname(filePath),+ filePath: path.resolve(dataDir.DOCUMENT_PATH),utcDateCreated: becca.getNoteOrThrow("root").utcDateCreated,...getContentCounts(),sizeBytes: databaseBytes()diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex edf4c5b919..2fddb4a22f 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -270,6 +270,22 @@ export interface ElectronShellApi {*/openPath(path: string): Promise<string>;+ /**+ * Shows a local file in the OS file manager, with the file itself selected,+ * via `electron.shell.showItemInFolder`. For pointing at a file the user is+ * not meant to open — the database, whose reader is Trilium itself.+ *+ * **Security:** the same sandbox as {@link openPath}, with the database+ * file added as a root of its own, since `TRILIUM_DOCUMENT_PATH` may put it+ * outside the data directory. Revealing is the milder act of the two, the+ * file being selected rather than launched, but a path the renderer names+ * is still a path the renderer must not be free to choose.+ *+ * Nothing is reported back: the OS is asked to bring a window forward, and+ * whether it did is not something Electron answers.+ */+ showItemInFolder(path: string): void;+/*** Opens a `file://` URL with its default OS handler. Exists as a separate* channel from {@link openExternal} because Electron's `shell.openExternal`diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 31a9eac810..7a6b557c70 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -127,8 +127,6 @@ export interface SpaceUsageCounts {export interface DatabaseInfoResponse extends SpaceUsageCounts {/** Absolute path of the database file, its name included. */filePath: string;- /** The directory holding it, which is what a file manager can be pointed at. */- directoryPath: string;/** When the root note was created, standing in for when the knowledge base itself was. */utcDateCreated: string;/**