Skip to content

Build your personal knowledge base with Trilium Notes

link previews: prevent link preview URLs getting logged or being visible to reverse proxies

Adorian Doranfc0c96c441ec
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index 87f6e56672..f279af0b97 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -60,7 +60,7 @@ describe("safeHostname", () => {
});
describe("fetchMetadata", () => {
- it("maps server metadata into the embed shape and encodes the URL", async () => {
+ it("maps server metadata into the embed shape, POSTing the URL in the body", async () => {
const url = "https://example.com/path?a=b&c=d";
const fromServer = {
url: "https://canonical.example.com",
@@ -71,20 +71,20 @@ describe("fetchMetadata", () => {
siteName: "Example",
image: "https://example.com/img.png"
};
- server.get = vi.fn(async () => fromServer) as typeof server.get;
+ server.post = vi.fn(async () => fromServer) as typeof server.post;
const result = await fetchMetadata(url);
- expect(server.get).toHaveBeenCalledWith(
- `link-embed/metadata?url=${encodeURIComponent(url)}`
- );
+ // The URL travels in the body, so it never reaches an access log — a pasted URL can carry a
+ // one-time token or a signature in its query string.
+ expect(server.post).toHaveBeenCalledWith("link-embed/metadata", { url });
expect(result).toEqual(fromServer);
});
it("falls back to local detection when the server request fails", async () => {
- server.get = vi.fn(async () => {
+ server.post = vi.fn(async () => {
throw new Error("network down");
- }) as typeof server.get;
+ }) as typeof server.post;
const result = await fetchMetadata("https://youtu.be/abcdefghijk");
expect(result).toEqual({
@@ -97,12 +97,12 @@ describe("fetchMetadata", () => {
});
it("passes the server's unresolved flag through", async () => {
- server.get = vi.fn(async () => ({
+ server.post = vi.fn(async () => ({
url: "https://blocked.example.com/x",
embedType: "opengraph",
title: "blocked.example.com",
unresolved: true
- })) as typeof server.get;
+ })) as typeof server.post;
const result = await fetchMetadata("https://blocked.example.com/x");
expect(result.unresolved).toBe(true);
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index 0a995d329e..ae86819f9f 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -37,7 +37,9 @@ export function safeHostname(url: string): string {
*/
export async function fetchMetadata(url: string): Promise<EmbedMetadata> {
try {
- const metadata = await server.get<LinkEmbedMetadata>(`link-embed/metadata?url=${encodeURIComponent(url)}`);
+ // POSTed rather than passed in the query string: a URL can carry a one-time token or a
+ // signed signature, and a query string ends up in every access log along the way.
+ const metadata = await server.post<LinkEmbedMetadata>("link-embed/metadata", { url });
return {
url: metadata.url,
embedType: metadata.embedType,
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.ts
index 12a94b5f00..5e2560d689 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/apps/server/src/routes/api/link_embed.spec.ts
@@ -63,10 +63,13 @@ describe("extractYouTubeVideoId", () => {
});
describe("link-embed getMetadata", () => {
- function req(url?: unknown) { return { query: { url } } as unknown as Request; }
+ // The URL is POSTed in the body, never in the query string: a query string ends up in every
+ // access log along the way, and a pasted URL can carry a one-time token or a signature.
+ function req(url?: unknown) { return { body: { url } } as unknown as Request; }
- it("requires a url query parameter", async () => {
+ it("requires a url in the body", async () => {
await expect(linkEmbedRoute.getMetadata(req())).rejects.toBeInstanceOf(ValidationError);
+ await expect(linkEmbedRoute.getMetadata({} as unknown as Request)).rejects.toBeInstanceOf(ValidationError);
});
it("returns YouTube metadata via the oEmbed endpoint", async () => {
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.ts
index c3237cc5d1..2a80938cb4 100644
--- a/apps/server/src/routes/api/link_embed.ts
+++ b/apps/server/src/routes/api/link_embed.ts
@@ -1,4 +1,4 @@
-import { extractYouTubeVideoId, type LinkEmbedMetadata } from "@triliumnext/commons";
+import { extractYouTubeVideoId, type LinkEmbedMetadata, redactUrlForLog } from "@triliumnext/commons";
import { getLog, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import isSvg from "is-svg";
@@ -163,7 +163,7 @@ async function downloadImageAsDataUri(imageUrl: string, minSourceDimension = 0):
// content type is checked so that an error page served in place of the image (an undecodable
// response that is not an image at all) is dropped rather than embedded. A caller that
// requires a minimum size gets nothing: undecodable means unverifiable.
- getLog().info(`Could not decode link preview image ${imageUrl}: ${e}`);
+ getLog().info(`Could not decode link preview image ${redactUrlForLog(imageUrl)}: ${e}`);
return isSmallEnoughToKeepVerbatim && contentType.startsWith("image/") && !minSourceDimension
? toDataUri(contentType, buffer)
: undefined;
@@ -349,10 +349,11 @@ async function fetchOpenGraphData(url: string) {
}
async function getMetadata(req: Request) {
- const urlParam = req.query.url;
+ // Taken from the body, not the query string: see the route registration for why.
+ const urlParam = req.body?.url;
if (!urlParam || typeof urlParam !== "string") {
- throw new ValidationError("'url' query parameter is required");
+ throw new ValidationError("'url' is required");
}
const validatedUrl = validateUrl(urlParam);
@@ -384,7 +385,7 @@ async function getMetadata(req: Request) {
embedType: "opengraph"
} satisfies LinkEmbedMetadata;
} catch (e: unknown) {
- getLog().info(`Failed to fetch metadata for ${url}: ${e}`);
+ getLog().info(`Failed to fetch metadata for ${redactUrlForLog(url)}: ${e}`);
return unresolvedMetadata(validatedUrl);
}
}
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 6d969967e8..24e55816d2 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -181,7 +181,10 @@ function register(app: express.Application) {
asyncRoute(PST, "/api/sender/note", [auth.checkEtapiToken], senderRoute.saveNote, apiResultHandler);
route(GET, "/api/fonts", [auth.checkApiAuthOrElectron], fontsRoute.getFontCss);
- asyncApiRoute(GET, "/api/link-embed/metadata", linkEmbedRoute.getMetadata);
+ // POST rather than GET: the URL would otherwise sit in the query string of every access-log
+ // line (Trilium's own, and any reverse proxy in front of it), and a pasted URL can carry a
+ // one-time token or a signed signature. The body is not logged.
+ asyncApiRoute(PST, "/api/link-embed/metadata", linkEmbedRoute.getMetadata);
apiRoute(GET, "/api/onenote-import/auth-url", onenoteImportRoute.getAuthUrl);
// Plain GET (no CSRF/auth headers): this is a top-level browser redirect back from Microsoft.
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index 9eaeff717d..225df97666 100644
--- a/packages/ckeditor5/src/plugins/linkembed.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.ts
@@ -1,4 +1,4 @@
-import { type BlockChildLike, chooseLinkPreviewKind, isUrlAloneInBlock } from '@triliumnext/commons';
+import { type BlockChildLike, chooseLinkPreviewKind, isUrlAloneInBlock, redactUrlForLog } from '@triliumnext/commons';
import { ButtonView, Command, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget, type Observable } from 'ckeditor5';
import linkEmbedIcon from '../icons/link-embed.svg?raw';
import { preventCKEditorHandling } from './widget_utils.js';
@@ -455,7 +455,7 @@ class AutoLinkToMention extends Plugin {
// plain link AutoLink already created. A preview built from a hostname placeholder would
// show strictly less than the URL it replaced.
if (metadata.unresolved) {
- console.warn(`Link preview dropped for ${url}: no metadata could be read from the page (kept as a plain link).`);
+ console.warn(`Link preview dropped for ${redactUrlForLog(url)}: no metadata could be read from the page (kept as a plain link).`);
return;
}
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index 3bf8bd3c74..430bb108ad 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -5,6 +5,7 @@ import {
chooseLinkPreviewKind,
extractYouTubeVideoId,
isUrlAloneInBlock,
+ redactUrlForLog,
YOUTUBE_REGEX
} from "./link_embed.js";
@@ -46,6 +47,24 @@ describe("YOUTUBE_REGEX", () => {
});
});
+describe("redactUrlForLog", () => {
+ it("drops the query and fragment, where the secrets live", () => {
+ // A password-reset token, a signed S3 signature, a doc-sharing key — none of it belongs in a
+ // log file. The trailing marker records that parameters were there.
+ expect(redactUrlForLog("https://example.com/reset?token=s3cr3t")).toBe("https://example.com/reset?…");
+ expect(redactUrlForLog("https://example.com/doc#key=s3cr3t")).toBe("https://example.com/doc?…");
+ });
+
+ it("keeps a URL that has nothing to hide intact", () => {
+ expect(redactUrlForLog("https://example.com/blog/post")).toBe("https://example.com/blog/post");
+ expect(redactUrlForLog("http://localhost:8080/x")).toBe("http://localhost:8080/x");
+ });
+
+ it("does not throw on an unparseable URL", () => {
+ expect(redactUrlForLog("not-a-url")).toBe("<unparseable URL>");
+ });
+});
+
describe("isUrlAloneInBlock", () => {
const url = "https://youtu.be/dQw4w9WgXcQ";
const text = (data: string): BlockChildLike => ({ isText: true, data });
diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.ts
index f9da1063ca..d74fb47095 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -5,6 +5,26 @@ export function extractYouTubeVideoId(url: string): string | null {
return match ? match[1] : null;
}
+/**
+ * A URL trimmed to origin + path for logging.
+ *
+ * The query and fragment are where the secrets live — a password-reset token, a signed S3
+ * signature, a document-sharing key — and a log line is exactly the wrong place for them: logs get
+ * rotated, backed up, shipped to aggregators and pasted into bug reports. The `?…` marks that
+ * parameters were present, which is all a reader of the log needs to know.
+ */
+export function redactUrlForLog(url: string): string {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return "<unparseable URL>";
+ }
+
+ const withoutParams = `${parsed.origin}${parsed.pathname}`;
+ return parsed.search || parsed.hash ? `${withoutParams}?…` : withoutParams;
+}
+
export interface LinkEmbedMetadata {
url: string;
title?: string;