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
link previews: load the YouTube player only when the user demands playing the video, reject credentials in the URL
Adorian Doran17b3dabdea7a
diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex bfd893a95a..87f6e56672 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -110,17 +110,42 @@ describe("fetchMetadata", () => {});describe("renderEmbedPreview", () => {- it("renders a YouTube iframe when embedType is not opengraph and the URL is a video", () => {+ it("shows a click-to-play facade for a video, contacting YouTube only once clicked", async () => {const root = makeContainer();renderEmbedPreview(root, {url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",- embedType: "youtube"+ embedType: "youtube",+ image: "data:image/jpeg;base64,AAA"});+ // Nothing is loaded from YouTube until the user asks for it: no iframe, just the thumbnail+ // stored in the note.+ expect(root.querySelector("iframe")).toBeNull();+ expect(root.querySelector("a.link-embed-card")).toBeNull();+ const facade = root.querySelector<HTMLButtonElement>("button.link-embed-video-facade");+ expect(facade).not.toBeNull();+ expect(root.querySelector("img.link-embed-video-thumbnail")?.getAttribute("src")).toBe("data:image/jpeg;base64,AAA");++ facade?.click();+ await new Promise((resolve) => setTimeout(resolve, 0));+const iframe = root.querySelector("iframe");expect(iframe).not.toBeNull();- expect(iframe!.getAttribute("src")).toContain("youtube-nocookie.com/embed/dQw4w9WgXcQ");- expect(root.querySelector("a.link-embed-card")).toBeNull();+ expect(iframe?.getAttribute("src")).toContain("youtube-nocookie.com/embed/dQw4w9WgXcQ");+ // The click was the play command, so the player starts straight away.+ expect(iframe?.getAttribute("src")).toContain("autoplay=1");+ expect(root.querySelector("button.link-embed-video-facade")).toBeNull();+ });++ it("shows the facade without a thumbnail when the note stores no image", () => {+ const root = makeContainer();+ renderEmbedPreview(root, {+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ embedType: "youtube"+ });++ expect(root.querySelector("button.link-embed-video-facade")).not.toBeNull();+ expect(root.querySelector("img.link-embed-video-thumbnail")).toBeNull();});it("renders a card (not an iframe) for a YouTube URL forced to opengraph", () => {diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsxindex 6c54499cec..0a995d329e 100644--- a/apps/client/src/services/link_embed.tsx+++ b/apps/client/src/services/link_embed.tsx@@ -4,6 +4,7 @@ import { type LinkEmbedMetadata, YOUTUBE_REGEX, extractYouTubeVideoId } from "@timport { render } from "preact";import { useState } from "preact/hooks";+import { t } from "./i18n.js";import server from "./server.js";/** Paste mode chosen by user from the floating popup. */@@ -104,8 +105,56 @@ function CardImage({ src }: { src?: string }) {);}+/**+ * A YouTube player that only contacts YouTube once the user asks it to.+ *+ * Until then it shows the thumbnail already stored in the note, so merely opening a note with an+ * embedded video does not tell Google that the reader opened it — the note stays free of+ * third-party requests, which is the whole point of embedding the metadata server-side.+ */+function VideoEmbed({ meta, videoId }: { meta: EmbedMetadata; videoId: string }) {+ const [playing, setPlaying] = useState(false);++ if (!playing) {+ return (+ <div className="link-embed-video">+ <button+ type="button"+ className="link-embed-video-facade"+ aria-label={t("link_embed.play_video")}+ title={t("link_embed.play_video")}+ onClick={() => setPlaying(true)}+ >+ {meta.image && <img className="link-embed-video-thumbnail" src={meta.image} alt="" />}+ <span className="link-embed-video-play" aria-hidden="true" />+ </button>+ </div>+ );+ }++ // The `origin` param is only valid for a real web origin. On desktop the+ // renderer is served from `trilium-app://app`, which YouTube's player+ // rejects ("video player configuration error"), so omit it there.+ const webOrigin = window.location.protocol.startsWith("http") ? window.location.origin : null;+ // autoplay: the click on the facade *was* the play command; without it the user would have to+ // press play a second time, inside YouTube's own player.+ const embedSrc = `https://www.youtube-nocookie.com/embed/${videoId}?rel=0&autoplay=1${webOrigin ? `&origin=${encodeURIComponent(webOrigin)}` : ""}`;++ return (+ <div className="link-embed-video">+ <iframe+ src={embedSrc}+ frameBorder="0"+ allowFullScreen+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"+ referrerPolicy="strict-origin-when-cross-origin"+ />+ </div>+ );+}+function EmbedPreview({ meta, editable }: { meta: EmbedMetadata; editable?: boolean }) {- // Only show the YouTube iframe embed when embedType is not explicitly+ // Only show the YouTube player when embedType is not explicitly// set to 'opengraph' (Card mode). This lets the user choose between// an embedded player and a static card preview for YouTube links.const videoId = meta.embedType !== "opengraph"@@ -113,23 +162,7 @@ function EmbedPreview({ meta, editable }: { meta: EmbedMetadata; editable?: bool: null;if (videoId) {- // The `origin` param is only valid for a real web origin. On desktop the- // renderer is served from `trilium-app://app`, which YouTube's player- // rejects ("video player configuration error"), so omit it there.- const webOrigin = window.location.protocol.startsWith("http") ? window.location.origin : null;- const embedSrc = `https://www.youtube-nocookie.com/embed/${videoId}?rel=0${webOrigin ? `&origin=${encodeURIComponent(webOrigin)}` : ""}`;- return (- <div className="link-embed-video">- <iframe- src={embedSrc}- frameBorder="0"- allowFullScreen- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"- referrerPolicy="strict-origin-when-cross-origin"- loading="lazy"- />- </div>- );+ return <VideoEmbed meta={meta} videoId={videoId} />;}// In editing mode, omit target="_blank" so Trilium's global link handlerdiff --git a/apps/client/src/services/media_playback.spec.ts b/apps/client/src/services/media_playback.spec.tsindex 48bc2d6072..aa01cb00aa 100644--- a/apps/client/src/services/media_playback.spec.ts+++ b/apps/client/src/services/media_playback.spec.ts@@ -50,6 +50,26 @@ describe("stopBackgroundMedia", () => {expect(pdfSets()).toBe(0);});+ it("drops autoplay when reloading, so a hidden player does not start over", () => {+ // The link-preview player carries autoplay=1 (the click on the facade was the play command).+ // Reloading with it intact would restart the video in the background — the very thing being+ // prevented here.+ const container = document.createElement("div");+ container.innerHTML = `+ <div class="link-embed-video">+ <iframe src="https://www.youtube-nocookie.com/embed/abc?rel=0&autoplay=1&origin=http%3A%2F%2Flocalhost"></iframe>+ </div>+ `;+ const iframe = container.querySelector("iframe") as HTMLIFrameElement;++ stopBackgroundMedia(container);++ expect(iframe.src).not.toContain("autoplay");+ // The rest of the embed URL is preserved, so showing the note again restores the player.+ expect(iframe.src).toContain("youtube-nocookie.com/embed/abc");+ expect(iframe.src).toContain("rel=0");+ });+it("is a no-op for null/empty containers", () => {expect(() => stopBackgroundMedia(null)).not.toThrow();expect(() => stopBackgroundMedia(document.createElement("div"))).not.toThrow();diff --git a/apps/client/src/services/media_playback.ts b/apps/client/src/services/media_playback.tsindex 94dd5386f8..31203a3785 100644--- a/apps/client/src/services/media_playback.ts+++ b/apps/client/src/services/media_playback.ts@@ -8,8 +8,8 @@* - HTML5 `<video>` / `<audio>` are paused directly.* - Cross-origin embeds (YouTube, Vimeo, …) expose no pause API to the host page,* so the iframe is reloaded by reassigning its `src`. This tears down the- * player and stops the audio; because the embeds don't autoplay, the reloaded- * iframe simply shows its thumbnail again when the container is shown later.+ * player and stops the audio, and the reloaded iframe simply shows its+ * thumbnail again when the container is shown later.** Scoped to the known video-embed containers — Trilium's Link Preview* (`.link-embed-video`) and `figure.media` — so unrelated iframes (PDFs,@@ -26,7 +26,26 @@ export function stopBackgroundMedia(container: HTMLElement | null | undefined) {const src = iframe.src;if (src) {// Reassigning src (even to the same value) reloads the frame.- iframe.src = src;+ iframe.src = withoutAutoplay(src);}}}++/**+ * Strips `autoplay=1` from an embed URL. The link-preview player carries it — the user's click on+ * the click-to-play facade *is* the play command — but reloading a hidden iframe with autoplay still+ * set would start the video playing again in the background, which is the very thing being+ * prevented here.+ */+function withoutAutoplay(src: string): string {+ if (!src.includes("autoplay=1")) return src;++ try {+ const url = new URL(src);+ url.searchParams.delete("autoplay");+ return url.toString();+ } catch {+ /* v8 ignore next -- an iframe's resolved `src` is always a valid absolute URL */+ return src;+ }+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 16810a828b..21d0fca8b0 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2449,6 +2449,9 @@"failed_to_open": "Failed to open link '{{- href}}': {{- message}}","copy_url": "Copy URL"},+ "link_embed": {+ "play_video": "Play video"+ },"link_context_menu": {"open_note_in_new_tab": "Open note in a new tab","open_note_in_new_split": "Open note in a new split",diff --git a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css b/apps/client/src/widgets/type_widgets/text/LinkEmbed.cssindex bd4256d64f..8e314aee68 100644--- a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css+++ b/apps/client/src/widgets/type_widgets/text/LinkEmbed.css@@ -170,6 +170,57 @@display: block;}+/* ---------- Click-to-play facade ----------+ Shown in place of the player until the user asks for it, so opening a note never contacts+ YouTube. The thumbnail is the one stored in the note, not a remote one. */++.link-embed-video-facade {+ position: relative;+ display: block;+ width: 100%;+ aspect-ratio: 16 / 9;+ padding: 0;+ border: none;+ background: #000;+ cursor: pointer;+}++.link-embed-video-thumbnail {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}++.link-embed-video-play {+ position: absolute;+ inset: 0;+ margin: auto;+ width: 68px;+ height: 48px;+ border-radius: 12px;+ background: rgba(0, 0, 0, 0.7);+ transition: background-color 0.12s;+}++/* The play triangle. */+.link-embed-video-play::after {+ content: "";+ position: absolute;+ inset: 0;+ margin: auto;+ width: 0;+ height: 0;+ border-style: solid;+ border-width: 10px 0 10px 17px;+ border-color: transparent transparent transparent #fff;+}++.link-embed-video-facade:hover .link-embed-video-play,+.link-embed-video-facade:focus-visible .link-embed-video-play {+ background: #f00;+}+/* ---------- Card embed (Notion-style) ---------- */.link-embed-card {diff --git a/apps/server/src/services/safe_fetch.spec.ts b/apps/server/src/services/safe_fetch.spec.tsindex 45fbc13f14..e54ca32bc0 100644--- a/apps/server/src/services/safe_fetch.spec.ts+++ b/apps/server/src/services/safe_fetch.spec.ts@@ -55,6 +55,12 @@ describe("validateUrl", () => {expect(() => validateUrl("not-a-url")).toThrow("Invalid URL");expect(() => validateUrl("")).toThrow("Invalid URL");});++ it("rejects URLs carrying credentials, which must not reach the wire, the note or the log", () => {+ expect(() => validateUrl("https://user:[email protected]/page")).toThrow("credentials");+ expect(() => validateUrl("https://[email protected]/page")).toThrow("credentials");+ expect(() => validateUrl("http://:[email protected]/page")).toThrow("credentials");+ });});describe("validateHostResolution", () => {diff --git a/apps/server/src/services/safe_fetch.ts b/apps/server/src/services/safe_fetch.tsindex 1cc5ff8beb..486e22655b 100644--- a/apps/server/src/services/safe_fetch.ts+++ b/apps/server/src/services/safe_fetch.ts@@ -68,6 +68,13 @@ function validateUrl(urlString: string): URL {throw new ValidationError("Only http and https URLs are supported");}+ // `https://user:pass@host/` would put the credentials on the wire, and — for a link preview —+ // into the note's stored URL and the server log along with them. Nothing here needs to+ // authenticate, so refuse the URL rather than carry a secret around.+ if (parsed.username || parsed.password) {+ throw new ValidationError("URLs containing credentials are not supported");+ }+return parsed;}diff --git a/apps/server/src/share/content_renderer.spec.ts b/apps/server/src/share/content_renderer.spec.tsindex 7e2d4a3df7..de8f8aa823 100644--- a/apps/server/src/share/content_renderer.spec.ts+++ b/apps/server/src/share/content_renderer.spec.ts@@ -308,6 +308,21 @@ describe("content_renderer", () => {expect(content).toContain(`<div class="link-embed-card-url"><span class="link-embed-mention-dot"></span><span>example.com</span></div>`);});+ it("renders a video as a click-to-play facade, without contacting YouTube", () => {+ const note = buildShareNote({+ content: `<section class="link-embed" data-url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"`+ + ` data-embed-type="youtube" data-title="A video" data-image="data:image/jpeg;base64,BBB"></section>`+ });++ const content = String(getContent(note).content);+ // A visitor who merely reads the page sends nothing to YouTube: no iframe, just the+ // thumbnail already stored in the note. The theme's script swaps in the player on click.+ expect(content).not.toContain("<iframe");+ expect(content).not.toContain("youtube-nocookie.com");+ expect(content).toContain(`<button type="button" class="link-embed-video-facade" data-video-id="dQw4w9WgXcQ"`);+ expect(content).toContain(`<img class="link-embed-video-thumbnail" src="data:image/jpeg;base64,BBB"`);+ });+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.tsindex db0197a64d..9951f99410 100644--- a/apps/server/src/share/content_renderer.ts+++ b/apps/server/src/share/content_renderer.ts@@ -380,7 +380,19 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOptif (embedType === "youtube") {const videoId = extractYouTubeVideoId(url);if (videoId) {- embedEl.innerHTML = `<div class="link-embed-video"><iframe src="https://www.youtube-nocookie.com/embed/${escapeHtml(videoId)}?rel=0" frameborder="0" allowfullscreen loading="lazy" referrerpolicy="strict-origin-when-cross-origin" style="width:100%;aspect-ratio:16/9;border:none;"></iframe></div>`;+ // Click-to-play: the shared page shows the thumbnail stored in the note and only+ // 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 thumbnailHtml = image+ ? `<img class="link-embed-video-thumbnail" src="${escapeHtml(image)}" alt="" loading="lazy">`+ : "";+ embedEl.innerHTML = `<div class="link-embed-video">`+ + `<button type="button" class="link-embed-video-facade" data-video-id="${escapeHtml(videoId)}" aria-label="Play video" title="Play video">`+ + thumbnailHtml+ + `<span class="link-embed-video-play" aria-hidden="true"></span>`+ + `</button></div>`;}} else {const title = embedEl.getAttribute("data-title") || safeHostnameForShare(url);diff --git a/packages/share-theme/src/scripts/index.ts b/packages/share-theme/src/scripts/index.tsindex 2c7f58bf62..6dd50add36 100644--- a/packages/share-theme/src/scripts/index.ts+++ b/packages/share-theme/src/scripts/index.ts@@ -6,6 +6,7 @@ import setupThemeSelector from "./modules/theme.js";import setupMermaid from "./modules/mermaid.js";import setupMath from "./modules/math.js";import setupSidebars from "./modules/sidebar.js";+import setupVideoFacades from "./modules/video_facade.js";import api from "./modules/api.js";import "highlight.js/styles/default.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";@@ -30,6 +31,7 @@ $try(setupSidebars);function setupTextNote() {$try(setupMermaid);$try(setupMath);+ $try(setupVideoFacades);}document.addEventListener(diff --git a/packages/share-theme/src/scripts/modules/video_facade.ts b/packages/share-theme/src/scripts/modules/video_facade.tsnew file mode 100644index 0000000000..f87f053c44--- /dev/null+++ b/packages/share-theme/src/scripts/modules/video_facade.ts@@ -0,0 +1,28 @@+/**+ * Click-to-play for the link-preview video embeds.+ *+ * The shared page ships only the thumbnail stored in the note (see the share content renderer), so+ * reading a page that contains a video does not tell YouTube that the visitor read it. The player is+ * loaded here, on the visitor's own click — which doubles as the play command, hence `autoplay=1`.+ */+export default function setupVideoFacades() {+ const facades = document.querySelectorAll<HTMLButtonElement>(".link-embed-video-facade[data-video-id]");++ for (const facade of facades) {+ facade.addEventListener("click", () => {+ const videoId = facade.dataset.videoId;+ const container = facade.parentElement;+ if (!videoId || !container) {+ return;+ }++ const iframe = document.createElement("iframe");+ iframe.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(videoId)}?rel=0&autoplay=1`;+ iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";+ iframe.referrerPolicy = "strict-origin-when-cross-origin";+ iframe.allowFullscreen = true;++ container.replaceChildren(iframe);+ });+ }+}diff --git a/packages/share-theme/src/styles/link-embed.css b/packages/share-theme/src/styles/link-embed.cssindex 6a0ea7f03b..6089fc632d 100644--- a/packages/share-theme/src/styles/link-embed.css+++ b/packages/share-theme/src/styles/link-embed.css@@ -70,6 +70,57 @@display: block;}+/* ---------- Click-to-play facade ----------+ Stands in for the player until the visitor clicks, so reading a shared page containing a video+ sends no request to YouTube. The thumbnail comes from the note, not from a remote server. */++.link-embed-video-facade {+ position: relative;+ display: block;+ width: 100%;+ aspect-ratio: 16 / 9;+ padding: 0;+ border: none;+ background: #000;+ cursor: pointer;+}++.link-embed-video-thumbnail {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}++.link-embed-video-play {+ position: absolute;+ inset: 0;+ margin: auto;+ width: 68px;+ height: 48px;+ border-radius: 12px;+ background: rgba(0, 0, 0, 0.7);+ transition: background-color 0.12s;+}++/* The play triangle. */+.link-embed-video-play::after {+ content: "";+ position: absolute;+ inset: 0;+ margin: auto;+ width: 0;+ height: 0;+ border-style: solid;+ border-width: 10px 0 10px 17px;+ border-color: transparent transparent transparent #fff;+}++.link-embed-video-facade:hover .link-embed-video-play,+.link-embed-video-facade:focus-visible .link-embed-video-play {+ background: #f00;+}+/* ---------- Card embed ---------- */.link-embed-card {