Skip to content

Build your personal knowledge base with Trilium Notes

fix(pdf): preview attachments behind proxies that block traversal (closes #9879)

Elian Dorancfe12bba724c
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 7750ba7be7..5dd770a6c2 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -73,8 +73,12 @@ vi.mock("mermaid", () => ({
default: { mermaidAPI: { initialize: (...a: any[]) => mermaidInitialize(...a), render: (...a: any[]) => mermaidRender(...a) } }
}));
-const pdfViewerComponent = vi.fn(() => null);
-vi.mock("../widgets/type_widgets/file/PdfViewer", () => ({ default: pdfViewerComponent }));
+const pdfViewerComponent = vi.fn((_props: any) => null);
+// Only the component is stubbed: the URL the viewer is handed is the assertion below (#8877).
+vi.mock("../widgets/type_widgets/file/PdfViewer", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../widgets/type_widgets/file/PdfViewer")>()),
+ default: pdfViewerComponent
+}));
const webViewComponent = vi.fn((_props: any): VNode<any> => h("span", { class: "mock-webview-marker" }));
vi.mock("../widgets/type_widgets/WebView", () => ({ default: webViewComponent }));
@@ -291,6 +295,14 @@ describe("getRenderedContent file rendering", () => {
const { type, $renderedContent } = await getRenderedContent(note);
expect(type).toBe("pdf");
expect(pdfViewerComponent).toHaveBeenCalled();
+ // Root-relative, never `../../api/...`: a path climbing out of /pdfjs/web is rejected by
+ // proxies that filter traversal, before the request reaches Trilium (#8877).
+ expect(pdfViewerComponent.mock.calls.at(-1)?.[0].pdfUrl).toBe(`/api/notes/${note.noteId}/open`);
+
+ const att = buildAttachment({ role: "file", mime: "application/pdf" });
+ await getRenderedContent(att);
+ expect(pdfViewerComponent.mock.calls.at(-1)?.[0].pdfUrl).toBe(`/api/attachments/${att.attachmentId}/open`);
+
expect($renderedContent.find(".file-download").length).toBe(1);
const $open = $renderedContent.find(".file-open");
expect($open.length).toBe(1);
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 071447731e..e5069259ec 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -309,9 +309,9 @@ async function renderFile(entity: FNote | FAttachment, type: string, $renderedCo
let mediaOwnsFileActions = false;
if (type === "pdf") {
- const url = `../../api/${entityType}/${entityId}/open`;
const $viewer = $(`<div style="height: 100%">`);
- const PdfViewer = (await import("../widgets/type_widgets/file/PdfViewer")).default;
+ const { default: PdfViewer, getPdfUrl } = await import("../widgets/type_widgets/file/PdfViewer");
+ const url = getPdfUrl(`${entityType}/${entityId}/open`);
render(h(PdfViewer, {pdfUrl: url, editable: false, toolbar: options.pdfToolbar ?? false}), $viewer.get(0)!);
$content.append($viewer);
diff --git a/apps/client/src/test/setup.ts b/apps/client/src/test/setup.ts
index 2f654a870e..30d037bf68 100644
--- a/apps/client/src/test/setup.ts
+++ b/apps/client/src/test/setup.ts
@@ -14,7 +14,8 @@ function injectGlobals() {
uncheckedWindow.jQuery = $;
uncheckedWindow.WebSocket = () => {};
uncheckedWindow.glob = {
- isMainWindow: true
+ isMainWindow: true,
+ baseApiUrl: "api/"
};
}
diff --git a/apps/client/src/widgets/dialogs/revisions.tsx b/apps/client/src/widgets/dialogs/revisions.tsx
index 549df3502a..76f00f3868 100644
--- a/apps/client/src/widgets/dialogs/revisions.tsx
+++ b/apps/client/src/widgets/dialogs/revisions.tsx
@@ -31,7 +31,7 @@ import { DetailPane, MasterDetailHeader, MasterPane, useMobileMasterDetail } fro
import Modal from "../react/Modal";
import NoItems from "../react/NoItems";
import { RawHtmlBlock, SanitizedHtml } from "../react/RawHtml";
-import PdfViewer from "../type_widgets/file/PdfViewer";
+import PdfViewer, { getPdfUrl } from "../type_widgets/file/PdfViewer";
import { applyReferenceLinks } from "../type_widgets/text/read_only_helper";
const DIFFABLE_TYPES = ["text", "code", "mermaid"];
@@ -844,7 +844,7 @@ function FilePreviewInner({ revisionItem, fullRevision }: { revisionItem: Revisi
if (revisionItem.mime === "application/pdf") {
return (
<PdfViewer
- pdfUrl={`../../api/revisions/${revisionItem.revisionId}/download`}
+ pdfUrl={getPdfUrl(`revisions/${revisionItem.revisionId}/download`)}
/>
);
}
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index a87978f0b0..2ee315b9e9 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -8,7 +8,7 @@ import open from "../../../services/open";
import options from "../../../services/options";
import { useViewModeConfig } from "../../collections/NoteList";
import { useBlobEditorSpacedUpdate, useEffectiveReadOnly, useTriliumEvent } from "../../react/hooks";
-import PdfViewer from "./PdfViewer";
+import PdfViewer, { getPdfUrl } from "./PdfViewer";
/**
* How long annotating is left to settle before a save. Longer than the second an editor of text
@@ -234,7 +234,7 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
<PdfViewer
iframeRef={iframeRef}
tabIndex={300}
- pdfUrl={new URL(`${window.glob.baseApiUrl}notes/${note.noteId}/open`, window.location.href).pathname}
+ pdfUrl={getPdfUrl(`notes/${note.noteId}/open`)}
onLoad={() => {
const win = iframeRef.current?.contentWindow;
if (win) {
diff --git a/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx b/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx
new file mode 100644
index 0000000000..35c55a5ffb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx
@@ -0,0 +1,18 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import { getPdfUrl } from "./PdfViewer";
+
+describe("getPdfUrl", () => {
+ afterEach(() => history.replaceState({}, "", "/"));
+
+ it("resolves an API path against the deployment root, never relative to the viewer", () => {
+ expect(getPdfUrl("attachments/abc123/open")).toBe("/api/attachments/abc123/open");
+
+ // Trilium behind a reverse proxy on a subpath: the URL keeps the prefix, so pdf.js still
+ // reaches the API without `../../` — which a proxy filtering traversal would reject (#8877).
+ history.replaceState({}, "", "/trilium/#root/abc123");
+ expect(getPdfUrl("notes/abc123/open")).toBe("/trilium/api/notes/abc123/open");
+
+ expect(getPdfUrl("revisions/rev1/download")).not.toContain("..");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx b/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
index 26459ff02b..b5cb17c353 100644
--- a/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
@@ -15,7 +15,7 @@ const FONTS: FontDefinition[] = [
interface PdfViewerProps extends Pick<HTMLAttributes<HTMLIFrameElement>, "tabIndex"> {
iframeRef?: RefObject<HTMLIFrameElement>;
- /** Note: URLs are relative to /pdfjs/web, ideally use absolute paths (but without domain name) to avoid issues with some proxies. */
+ /** Relative URLs resolve against /pdfjs/web; build API paths with {@link getPdfUrl} instead. */
pdfUrl: string;
onLoad?(): void;
/**
@@ -118,6 +118,16 @@ function cssVarsToString(vars: Record<string, string>) {
.join('\n')}\n}`;
}
+/**
+ * Resolves an API path such as `attachments/<id>/open` to a root-relative URL for
+ * {@link PdfViewerProps.pdfUrl}. A URL relative to the viewer needs `../../` to climb out of
+ * /pdfjs/web, which proxies that filter path traversal reject before the request reaches
+ * Trilium (Nginx Proxy Manager's "Block Common Exploits" answers 403). See #8877.
+ */
+export function getPdfUrl(apiPath: string) {
+ return new URL(`${window.glob.baseApiUrl}${apiPath}`, window.location.href).pathname;
+}
+
function injectFont(font: FontDefinition) {
return `
@font-face {