Skip to content

Build your personal knowledge base with Trilium Notes

fix(link previews): only load a favicon/image stored locally

Elian Doran50ddba9c6e33
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index 49f54f12ae..989db906fe 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -238,7 +238,7 @@ describe("renderEmbedPreview", () => {
title: "A title",
description: "A description",
siteName: "YouTube",
- image: "https://img.example/x.png"
+ image: "api/attachments/abc123/image/x.png"
});
expect(root.querySelector("iframe")).toBeNull();
@@ -264,6 +264,36 @@ describe("renderEmbedPreview", () => {
expect(mention.querySelector("a.link-embed-mention")?.getAttribute("href")).toBe("about:blank");
});
+ it("never loads a remote favicon or image, whatever the note stores", () => {
+ // Reaches here straight from the stored note HTML, exactly like the hostile `data-url` above.
+ // An <img> needs no click, so a remote value would tell a third party that the reader opened
+ // the note — the very thing embedding the metadata server-side exists to prevent.
+ const card = makeContainer();
+ renderEmbedPreview(card, {
+ url: "https://example.com",
+ embedType: "opengraph",
+ favicon: "https://tracker.test/favicon.ico",
+ image: "https://tracker.test/pixel.gif"
+ });
+ expect(card.querySelector("img.link-embed-card-image")).toBeNull();
+ expect(card.querySelector(".link-embed-card-image-placeholder")).not.toBeNull();
+ expect(card.querySelector("img.link-embed-mention-favicon")).toBeNull();
+ expect(card.querySelector(".link-embed-mention-dot")).not.toBeNull();
+
+ const video = makeContainer();
+ renderEmbedPreview(video, {
+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ embedType: "youtube",
+ image: "https://tracker.test/thumb.jpg"
+ });
+ expect(video.querySelector("img.link-embed-video-thumbnail")).toBeNull();
+
+ const mention = makeContainer();
+ renderMentionPreview(mention, { url: "https://example.com", favicon: "http://169.254.169.254/latest/meta-data/" });
+ expect(mention.querySelector("img.link-embed-mention-favicon")).toBeNull();
+ expect(mention.querySelector(".link-embed-mention-dot")).not.toBeNull();
+ });
+
it("shows the stored favicon beside the site name, falling back to a dot without one", () => {
const root = makeContainer();
const meta = {
@@ -312,11 +342,12 @@ describe("renderEmbedPreview", () => {
});
it("replaces a broken card image with the placeholder on error", async () => {
+ // How a stored image actually breaks: its attachment was deleted, so the reference 404s.
const root = makeContainer();
renderEmbedPreview(root, {
url: "https://example.com",
embedType: "opengraph",
- image: "https://img.example/broken.png"
+ image: "api/attachments/deleted1/image/broken.png"
});
const img = root.querySelector("img.link-embed-card-image")!;
@@ -334,7 +365,7 @@ describe("renderMentionPreview", () => {
renderMentionPreview(root, {
url: "https://example.com",
title: "Example site",
- favicon: "https://example.com/favicon.ico"
+ favicon: "data:image/png;base64,AAA"
});
const anchor = root.querySelector("a.link-embed-mention")!;
@@ -363,7 +394,7 @@ describe("renderMentionPreview", () => {
const root = makeContainer();
renderMentionPreview(root, {
url: "https://example.com",
- favicon: "https://example.com/broken.ico"
+ favicon: "api/attachments/deleted1/image/broken.ico"
});
const img = root.querySelector("img.link-embed-mention-favicon")!;
@@ -381,10 +412,10 @@ describe("applyLinkEmbeds", () => {
root.innerHTML = `
<section class="link-embed" data-url="https://full.example.com"
data-embed-type="opengraph" data-title="T" data-description="D"
- data-site-name="Site" data-image="https://img.example/x.png"></section>
+ data-site-name="Site" data-image="api/attachments/abc123/image/x.png"></section>
<section class="link-embed"></section>
<span class="link-mention" data-url="https://m.example.com"
- data-title="MT" data-favicon="https://m.example.com/fav.ico"></span>
+ data-title="MT" data-favicon="data:image/png;base64,AAA"></span>
<span class="link-mention"></span>
`;
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index 616ac512a2..e8590ffad3 100644
--- a/apps/client/src/services/link_embed.tsx
+++ b/apps/client/src/services/link_embed.tsx
@@ -1,6 +1,6 @@
import "../widgets/type_widgets/text/LinkEmbed.css";
-import { extractYouTubeVideoId, type LinkEmbedMetadata, safeLinkPreviewHref, YOUTUBE_REGEX } from "@triliumnext/commons";
+import { extractYouTubeVideoId, type LinkEmbedMetadata, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";
import { render } from "preact";
import { useState } from "preact/hooks";
@@ -88,15 +88,18 @@ async function offloadImageToAttachment(image: string | undefined, ownerNoteId:
function Favicon({ src }: { src?: string }) {
const [failed, setFailed] = useState(false);
+ // See safeLinkPreviewImageSrc: only an inline image or an attachment of this instance, so that
+ // opening a note never announces the reader to a third party.
+ const safeSrc = safeLinkPreviewImageSrc(src);
- if (!src || failed) {
+ if (!safeSrc || failed) {
return <span className="link-embed-mention-dot" />;
}
return (
<img
className="link-embed-mention-favicon"
- src={src}
+ src={safeSrc}
width={16}
height={16}
onError={() => setFailed(true)}
@@ -110,15 +113,16 @@ function ImagePlaceholder() {
function CardImage({ src }: { src?: string }) {
const [failed, setFailed] = useState(false);
+ const safeSrc = safeLinkPreviewImageSrc(src);
- if (!src || failed) {
+ if (!safeSrc || failed) {
return <ImagePlaceholder />;
}
return (
<img
className="link-embed-card-image"
- src={src}
+ src={safeSrc}
alt=""
loading="lazy"
draggable={false}
@@ -136,6 +140,7 @@ function CardImage({ src }: { src?: string }) {
*/
function VideoEmbed({ meta, videoId }: { meta: EmbedMetadata; videoId: string }) {
const [playing, setPlaying] = useState(false);
+ const thumbnail = safeLinkPreviewImageSrc(meta.image);
if (!playing) {
return (
@@ -147,7 +152,7 @@ function VideoEmbed({ meta, videoId }: { meta: EmbedMetadata; videoId: string })
title={t("link_embed.play_video")}
onClick={() => setPlaying(true)}
>
- {meta.image && <img className="link-embed-video-thumbnail" src={meta.image} alt="" draggable={false} />}
+ {thumbnail && <img className="link-embed-video-thumbnail" src={thumbnail} alt="" draggable={false} />}
<span className="link-embed-video-play" aria-hidden="true" />
</button>
</div>
diff --git a/apps/server/src/share/content_renderer.spec.ts b/apps/server/src/share/content_renderer.spec.ts
index fa49b8a8ea..7fbbf42c40 100644
--- a/apps/server/src/share/content_renderer.spec.ts
+++ b/apps/server/src/share/content_renderer.spec.ts
@@ -342,6 +342,43 @@ describe("content_renderer", () => {
expect(content).toContain(`<a class="link-embed-mention" href="about:blank"`);
});
+ it("keeps a stored attachment reference, which is served from this instance", () => {
+ const note = buildShareNote({
+ content: `<section class="link-embed" data-url="https://example.com/page" data-embed-type="opengraph"`
+ + ` data-title="A title" data-image="api/attachments/abc123/image/preview.png"></section>`
+ });
+
+ const content = String(getContent(note).content);
+ expect(content).toContain(`<img class="link-embed-card-image" src="api/attachments/abc123/image/preview.png"`);
+ });
+
+ it("drops a remote favicon/image rather than have every visitor fetch it", () => {
+ // Same route in as the hostile `data-url` above: `data-*` survives the sanitizer, so a
+ // note from import, ETAPI or sync can name any URL here. An <img> needs no click, so
+ // leaving it in place would announce every visitor to whoever it points at — and the
+ // metadata pipeline only ever stores an inline image or an attachment, so a remote URL
+ // is illegitimate by construction.
+ const note = buildShareNote({
+ content: `<section class="link-embed" data-url="https://example.com/page" data-embed-type="opengraph"`
+ + ` data-title="A title" data-favicon="http://169.254.169.254/latest/meta-data/"`
+ + ` data-image="https://tracker.test/pixel.gif"></section>`
+ + `<section class="link-embed" data-url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"`
+ + ` data-embed-type="youtube" data-image="https://tracker.test/thumb.jpg"></section>`
+ + `<p><span class="link-mention" data-url="https://example.com/page" data-title="A title"`
+ + ` data-favicon="https://tracker.test/favicon.ico"></span></p>`
+ });
+
+ const content = String(getContent(note).content);
+ // As with the hostile data-url above, the element keeps its inert attribute — no browser
+ // fetches a `data-favicon` — but nothing reaches an `src`, which is what would be fetched.
+ expect(content).not.toContain(`src="http://169.254.169.254`);
+ expect(content).not.toContain(`src="https://tracker.test`);
+ // Each sink degrades to the placeholder it already shows for a preview with no image.
+ expect(content).toContain(`<span class="link-embed-mention-dot"></span>`);
+ expect(content).toContain(`<div class="link-embed-card-image-placeholder">`);
+ expect(content).not.toContain(`class="link-embed-video-thumbnail"`);
+ });
+
it("renders an inline mention with the same favicon markup", () => {
const note = buildShareNote({
content: `<p><span class="link-mention" data-url="https://example.com/page" data-title="A title" data-favicon="${FAVICON}"></span></p>`
diff --git a/apps/server/src/share/content_renderer.ts b/apps/server/src/share/content_renderer.ts
index 495eb01a18..369c192902 100644
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@ -1,4 +1,4 @@
-import { extractYouTubeVideoId, safeLinkPreviewHref } from "@triliumnext/commons";
+import { extractYouTubeVideoId, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";
import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";
import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";
import { type BAttachment, type BBranch, becca, BNote, getLog, icon_packs as iconPackService, options, sanitize, task_states, utils } from "@triliumnext/core";
@@ -357,9 +357,15 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
// The site's favicon, or a neutral dot when it has none — shown by both the inline mention and
// the card's URL line, from the one `data-favicon` the element already carries.
- const renderFavicon = (favicon: string | undefined) => (favicon
- ? `<img class="link-embed-mention-favicon" src="${escapeHtml(favicon)}" width="16" height="16">`
- : `<span class="link-embed-mention-dot"></span>`);
+ // safeLinkPreviewImageSrc() keeps the dot for anything but an inline image or an attachment of
+ // this instance: an <img> fires on load, so a remote URL here would have every visitor to the
+ // shared page announce itself to a third party without so much as a click.
+ const renderFavicon = (favicon: string | undefined | null) => {
+ const src = safeLinkPreviewImageSrc(favicon);
+ return src
+ ? `<img class="link-embed-mention-favicon" src="${escapeHtml(src)}" width="16" height="16">`
+ : `<span class="link-embed-mention-dot"></span>`;
+ };
// Process link mentions (inline) — metadata is stored in data attributes.
for (const mentionEl of document.querySelectorAll("span.link-mention")) {
@@ -387,7 +393,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
// loads YouTube's player once a visitor asks for it, so simply reading the page does
// not hand every visitor's IP to Google. The swap is done by the share theme's
// video_facade script, which reads data-video-id.
- const image = embedEl.getAttribute("data-image");
+ const image = safeLinkPreviewImageSrc(embedEl.getAttribute("data-image"));
const thumbnailHtml = image
? `<img class="link-embed-video-thumbnail" src="${escapeHtml(image)}" alt="" loading="lazy">`
: "";
@@ -400,7 +406,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
} else {
const title = embedEl.getAttribute("data-title") || safeHostnameForShare(url);
const description = embedEl.getAttribute("data-description");
- const image = embedEl.getAttribute("data-image");
+ const image = safeLinkPreviewImageSrc(embedEl.getAttribute("data-image"));
const siteName = embedEl.getAttribute("data-site-name") || safeHostnameForShare(url);
const imageHtml = image
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index d482f5fd05..f66e08ad27 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -5,8 +5,10 @@ import {
chooseLinkPreviewKind,
extractYouTubeVideoId,
isHttpUrl,
+ isLocalPreviewImageSrc,
isUrlAloneInBlock,
safeLinkPreviewHref,
+ safeLinkPreviewImageSrc,
YOUTUBE_REGEX
} from "./link_embed.js";
@@ -72,6 +74,43 @@ describe("isHttpUrl / safeLinkPreviewHref", () => {
});
});
+describe("isLocalPreviewImageSrc / safeLinkPreviewImageSrc", () => {
+ it("accepts the inline images and own attachments the metadata pipeline produces", () => {
+ expect(isLocalPreviewImageSrc("data:image/png;base64,iVBORw0KGgo=")).toBe(true);
+ expect(isLocalPreviewImageSrc("data:image/jpeg;base64,/9j/4AAQ")).toBe(true);
+ // The server emits one of these for a vector favicon; an SVG loaded through <img> runs no script.
+ expect(isLocalPreviewImageSrc("data:image/svg+xml;base64,PHN2Zz4=")).toBe(true);
+ expect(isLocalPreviewImageSrc("api/attachments/abc123DEF_/image/preview.png")).toBe(true);
+ expect(isLocalPreviewImageSrc(" api/attachments/abc123/image/x.png ")).toBe(true);
+ });
+
+ it("rejects anything that would make the reader fetch from a third party", () => {
+ // The whole point: an <img> fires on load, so a remote favicon/image would announce every
+ // reader of the note — and every visitor to it as a shared page — to whoever it points at.
+ expect(isLocalPreviewImageSrc("https://evil.test/pixel.gif")).toBe(false);
+ expect(isLocalPreviewImageSrc("http://169.254.169.254/latest/meta-data/")).toBe(false);
+ expect(isLocalPreviewImageSrc("//evil.test/api/attachments/abc123/image/x.png")).toBe(false);
+ expect(isLocalPreviewImageSrc("https://evil.test/api/attachments/abc123/image/x.png")).toBe(false);
+ expect(isLocalPreviewImageSrc("/api/attachments/abc123/image/x.png")).toBe(false);
+ expect(isLocalPreviewImageSrc("../../api/attachments/abc123/image/x.png")).toBe(false);
+ });
+
+ it("rejects non-image data URIs and other schemes", () => {
+ expect(isLocalPreviewImageSrc("data:text/html,<script>alert(1)</script>")).toBe(false);
+ expect(isLocalPreviewImageSrc("javascript:alert(1)")).toBe(false);
+ expect(isLocalPreviewImageSrc("file:///etc/passwd")).toBe(false);
+ expect(isLocalPreviewImageSrc(undefined)).toBe(false);
+ expect(isLocalPreviewImageSrc("")).toBe(false);
+ });
+
+ it("degrades a rejected value to no image at all, so the caller shows its placeholder", () => {
+ expect(safeLinkPreviewImageSrc("data:image/png;base64,iVBORw0KGgo=")).toBe("data:image/png;base64,iVBORw0KGgo=");
+ expect(safeLinkPreviewImageSrc(" api/attachments/abc123/image/x.png ")).toBe("api/attachments/abc123/image/x.png");
+ expect(safeLinkPreviewImageSrc("https://evil.test/pixel.gif")).toBeUndefined();
+ expect(safeLinkPreviewImageSrc(undefined)).toBeUndefined();
+ });
+});
+
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 b5751722f3..592b9573c2 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -38,6 +38,51 @@ export function safeLinkPreviewHref(url: string | undefined | null): string {
return isHttpUrl(url) ? String(url) : "about:blank";
}
+/**
+ * A preview image reference the renderers may load: an inline `data:` image, or an attachment of
+ * this very instance.
+ *
+ * The metadata pipeline never produces anything else. The server downloads the favicon and the card
+ * image itself and hands back base64 `data:` URIs, precisely so that the note carries the picture
+ * instead of hotlinking the origin site; the client then offloads the larger card image into an
+ * attachment and stores its `api/attachments/…` URL. So a *remote* URL in `data-favicon` /
+ * `data-image` is illegitimate by construction — the mirror image of the {@link isHttpUrl} rule for
+ * `data-url`, where http(s) is the only legitimate case.
+ *
+ * That matters because those attributes reach an `<img src>` that fires on page load with no click,
+ * and `data-*` survives both sanitizers untouched (see {@link isHttpUrl}), so a note arriving by
+ * import, ETAPI or sync could otherwise make every reader of the note — and every visitor to it as a
+ * shared page — announce themselves to a third party. Keeping the check here, at the render sinks,
+ * means no stored value can produce an outbound request whatever route it came in by.
+ */
+export function isLocalPreviewImageSrc(src: string | undefined | null): boolean {
+ if (!src) {
+ return false;
+ }
+
+ const trimmed = src.trim();
+
+ // An SVG data URI is included on purpose: the server itself emits one for a vector favicon, and
+ // scripts inside an SVG loaded through <img> do not run.
+ if (/^data:image\/[a-z0-9.+-]+[;,]/i.test(trimmed)) {
+ return true;
+ }
+
+ // Exactly the shape the attachment upload endpoint returns. Anchored, so a protocol-relative
+ // `//evil.test/api/attachments/…` or a traversal cannot masquerade as one.
+ return /^api\/attachments\/[a-zA-Z0-9_]+\/image\/[^\s"'<>]*$/.test(trimmed);
+}
+
+/**
+ * The value to put in a preview's `<img src>`, or `undefined` when it is not one we may load.
+ * Every caller already renders a placeholder for a preview with no image (a neutral dot for the
+ * favicon, a link glyph for the card), so a rejected value degrades to that rather than to a broken
+ * image. See {@link isLocalPreviewImageSrc}.
+ */
+export function safeLinkPreviewImageSrc(src: string | undefined | null): string | undefined {
+ return isLocalPreviewImageSrc(src) ? String(src).trim() : undefined;
+}
+
export interface LinkEmbedMetadata {
url: string;
title?: string;