Skip to content

Build your personal knowledge base with Trilium Notes

link previews: fix some issues

Adorian Dorana7a2be311075
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.ts
index f279af0b97..eee17efc4b 100644
--- a/apps/client/src/services/link_embed.spec.ts
+++ b/apps/client/src/services/link_embed.spec.ts
@@ -170,6 +170,18 @@ describe("renderEmbedPreview", () => {
expect(root.querySelector(".link-embed-card-image-placeholder")).toBeNull();
});
+ it("renders a hostile scheme inert rather than as a live link", () => {
+ // `data-url` reaches here straight from the stored note HTML — the sanitizers keep `data-*`
+ // values verbatim — so a crafted note must not become <a href="javascript:...">.
+ const card = makeContainer();
+ renderEmbedPreview(card, { url: "javascript:alert(document.cookie)", embedType: "opengraph", title: "Evil" });
+ expect(card.querySelector("a.link-embed-card")?.getAttribute("href")).toBe("about:blank");
+
+ const mention = document.createElement("div");
+ renderMentionPreview(mention, { url: "javascript:alert(1)", title: "Evil" });
+ expect(mention.querySelector("a.link-embed-mention")?.getAttribute("href")).toBe("about:blank");
+ });
+
it("shows the stored favicon beside the site name, falling back to a dot without one", () => {
const root = makeContainer();
const meta = {
diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsx
index ae86819f9f..d2fa15699b 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 { type LinkEmbedMetadata, YOUTUBE_REGEX, extractYouTubeVideoId } from "@triliumnext/commons";
+import { type LinkEmbedMetadata, YOUTUBE_REGEX, extractYouTubeVideoId, safeLinkPreviewHref } from "@triliumnext/commons";
import { render } from "preact";
import { useState } from "preact/hooks";
@@ -173,7 +173,7 @@ function EmbedPreview({ meta, editable }: { meta: EmbedMetadata; editable?: bool
const target = editable ? undefined : "_blank";
return (
- <a className="link-embed-card" href={meta.url} target={target} rel="noopener noreferrer">
+ <a className="link-embed-card" href={safeLinkPreviewHref(meta.url)} target={target} rel="noopener noreferrer">
<div className="link-embed-card-image-wrapper">
<CardImage src={meta.image} />
</div>
@@ -195,7 +195,7 @@ function MentionPreview({ meta, editable }: { meta: { url: string; title?: strin
const target = editable ? undefined : "_blank";
return (
- <a className="link-embed-mention" href={meta.url} target={target} rel="noopener noreferrer">
+ <a className="link-embed-mention" href={safeLinkPreviewHref(meta.url)} target={target} rel="noopener noreferrer">
<Favicon src={meta.favicon} />
<span className="link-embed-mention-title">{meta.title || safeHostname(meta.url)}</span>
</a>
diff --git a/apps/server/src/share/content_renderer.spec.ts b/apps/server/src/share/content_renderer.spec.ts
index de8f8aa823..38939794ef 100644
--- a/apps/server/src/share/content_renderer.spec.ts
+++ b/apps/server/src/share/content_renderer.spec.ts
@@ -323,6 +323,23 @@ describe("content_renderer", () => {
expect(content).toContain(`<img class="link-embed-video-thumbnail" src="data:image/jpeg;base64,BBB"`);
});
+ it("neuters a hostile scheme in the stored URL, on a page served to anyone", () => {
+ // `data-*` values pass through the save-time sanitizer verbatim, so a note that arrives
+ // by import, ETAPI or sync can carry `data-url="javascript:…"`. It must not become a
+ // live link on the public share page.
+ const note = buildShareNote({
+ content: `<section class="link-embed" data-url="javascript:alert(document.cookie)" data-embed-type="opengraph" data-title="Evil"></section>`
+ + `<p><span class="link-mention" data-url="javascript:alert(1)" data-title="Evil"></span></p>`
+ });
+
+ const content = String(getContent(note).content);
+ // The element keeps its inert data-url attribute — nothing reads it on the shared page —
+ // but no href points at the payload.
+ expect(content).not.toContain(`href="javascript:`);
+ expect(content).toContain(`<a class="link-embed-card" href="about:blank"`);
+ expect(content).toContain(`<a class="link-embed-mention" href="about:blank"`);
+ });
+
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 9951f99410..495eb01a18 100644
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@ -1,4 +1,4 @@
-import { extractYouTubeVideoId } from "@triliumnext/commons";
+import { extractYouTubeVideoId, safeLinkPreviewHref } 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";
@@ -366,7 +366,10 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
const url = mentionEl.getAttribute("data-url");
if (!url) continue;
const title = mentionEl.getAttribute("data-title") || safeHostnameForShare(url);
- mentionEl.innerHTML = `<a class="link-embed-mention" href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">` +
+ // escapeHtml() makes the value safe to *place* in the attribute; it says nothing about the
+ // scheme. `data-*` survives the save-time sanitizer untouched, so a stored
+ // `data-url="javascript:…"` would otherwise become a live link on a public page.
+ mentionEl.innerHTML = `<a class="link-embed-mention" href="${escapeHtml(safeLinkPreviewHref(url))}" target="_blank" rel="noopener noreferrer">` +
renderFavicon(mentionEl.getAttribute("data-favicon")) +
`<span class="link-embed-mention-title">${escapeHtml(title)}</span></a>`;
}
@@ -408,7 +411,7 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt
+ renderFavicon(embedEl.getAttribute("data-favicon"))
+ `<span>${escapeHtml(siteName)}</span></div>`;
- embedEl.innerHTML = `<a class="link-embed-card" href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">` +
+ embedEl.innerHTML = `<a class="link-embed-card" href="${escapeHtml(safeLinkPreviewHref(url))}" target="_blank" rel="noopener noreferrer">` +
imageHtml +
`<div class="link-embed-card-content"><div class="link-embed-card-title">${escapeHtml(title)}</div>${descHtml}${urlHtml}</div></a>`;
}
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
index aa7696b09c..31600be221 100644
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts
@@ -314,6 +314,16 @@ describe("LinkEmbed", () => {
expect(command.embedAvailable).toBe(true);
});
+ it("exposes an http(s) URL but withholds a hostile one, so the toolbar cannot arm it", () => {
+ setModelData(editor.model, '[<linkEmbed url="https://e.com/page" embedType="opengraph"></linkEmbed>]');
+ expect(changeCommand(editor).url).toBe("https://e.com/page");
+
+ // `url` comes from the stored data-url, which the sanitizers keep verbatim. Withholding it
+ // leaves the "open link in new tab" and copy buttons disabled rather than armed.
+ setModelData(editor.model, '[<linkEmbed url="javascript:alert(document.cookie)" embedType="opengraph"></linkEmbed>]');
+ expect(changeCommand(editor).url).toBeNull();
+ });
+
it("reports 'card' for an opengraph linkEmbed and 'embed' otherwise", () => {
setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph"></linkEmbed>]');
expect(changeCommand(editor).value).toBe("card");
@@ -832,12 +842,13 @@ function changeCommand(editor: ClassicEditor): {
isEnabled: boolean;
value: string | null;
embedAvailable: boolean;
+ url: string | null;
} {
const command = editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND);
if (!command) {
throw new Error("changeLinkDisplay command is not registered.");
}
- return command as unknown as { isEnabled: boolean; value: string | null; embedAvailable: boolean };
+ return command as unknown as { isEnabled: boolean; value: string | null; embedAvailable: boolean; url: string | null };
}
/**
diff --git a/packages/ckeditor5/src/plugins/linkembed.ts b/packages/ckeditor5/src/plugins/linkembed.ts
index 223b3513de..17e17be84d 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, isHttpUrl, isUrlAloneInBlock } 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';
@@ -320,7 +320,11 @@ class ChangeLinkDisplayCommand extends Command {
if (selected) {
const url = selected.getAttribute('url') as string;
this.embedAvailable = this._detectEmbedType(url) !== 'opengraph';
- this.url = url;
+ // Only ever hand out an http(s) URL. `url` comes from the stored `data-url`, which the
+ // HTML sanitizers pass through unexamined, so a note carrying `data-url="javascript:…"`
+ // would otherwise reach the toolbar's "open link" button as a live href. Withholding it
+ // here disables that button (and the copy one) instead of arming them.
+ this.url = isHttpUrl(url) ? url : null;
} else {
this.embedAvailable = false;
this.url = null;
diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.ts
index 3bf8bd3c74..6ba9501f5e 100644
--- a/packages/commons/src/lib/link_embed.spec.ts
+++ b/packages/commons/src/lib/link_embed.spec.ts
@@ -4,7 +4,9 @@ import {
type BlockChildLike,
chooseLinkPreviewKind,
extractYouTubeVideoId,
+ isHttpUrl,
isUrlAloneInBlock,
+ safeLinkPreviewHref,
YOUTUBE_REGEX
} from "./link_embed.js";
@@ -46,6 +48,30 @@ describe("YOUTUBE_REGEX", () => {
});
});
+describe("isHttpUrl / safeLinkPreviewHref", () => {
+ it("accepts only http(s), which is all the metadata endpoint can ever produce", () => {
+ expect(isHttpUrl("https://example.com/page")).toBe(true);
+ expect(isHttpUrl("http://localhost:8080/x")).toBe(true);
+
+ expect(isHttpUrl("javascript:alert(1)")).toBe(false);
+ expect(isHttpUrl("JavaScript:alert(1)")).toBe(false);
+ expect(isHttpUrl("data:text/html,<script>alert(1)</script>")).toBe(false);
+ expect(isHttpUrl("vbscript:msgbox(1)")).toBe(false);
+ expect(isHttpUrl("file:///etc/passwd")).toBe(false);
+ // Not absolute, so not something a stored preview may point at.
+ expect(isHttpUrl("/relative/path")).toBe(false);
+ expect(isHttpUrl("not-a-url")).toBe(false);
+ expect(isHttpUrl(undefined)).toBe(false);
+ expect(isHttpUrl("")).toBe(false);
+ });
+
+ it("renders a hostile scheme inert instead of linking to it", () => {
+ expect(safeLinkPreviewHref("https://example.com/page")).toBe("https://example.com/page");
+ expect(safeLinkPreviewHref("javascript:alert(document.cookie)")).toBe("about:blank");
+ expect(safeLinkPreviewHref(undefined)).toBe("about:blank");
+ });
+});
+
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..b5751722f3 100644
--- a/packages/commons/src/lib/link_embed.ts
+++ b/packages/commons/src/lib/link_embed.ts
@@ -5,6 +5,39 @@ export function extractYouTubeVideoId(url: string): string | null {
return match ? match[1] : null;
}
+/**
+ * True when the URL is one a link preview may ever point at.
+ *
+ * A preview's URL reaches the renderers as a `data-url` attribute of the stored note HTML, and the
+ * HTML sanitizers (both `sanitize-html` on save and DOMPurify on render) pass `data-*` values
+ * through untouched — they check attribute *names*, not the contents of custom ones. So a note
+ * carrying `data-url="javascript:…"`, whether it arrived by import, ETAPI, sync from a compromised
+ * instance, or hand-edited HTML, would otherwise be rendered as a live `<a href="javascript:…">`
+ * — in the app *and* on the public share page. The metadata endpoint only ever produces http(s)
+ * URLs, so anything else is illegitimate by construction.
+ */
+export function isHttpUrl(url: string | undefined | null): boolean {
+ if (!url) {
+ return false;
+ }
+
+ try {
+ const { protocol } = new URL(url);
+ return protocol === "http:" || protocol === "https:";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The URL to put in a link preview's `href`, or `about:blank` when it is not one we may link to.
+ * Mirrors what the share view's `sanitizeUrl` does with a hostile scheme: render the element, make
+ * the link inert. See {@link isHttpUrl}.
+ */
+export function safeLinkPreviewHref(url: string | undefined | null): string {
+ return isHttpUrl(url) ? String(url) : "about:blank";
+}
+
export interface LinkEmbedMetadata {
url: string;
title?: string;