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
text editor/link preview: fix YouTube videos for the desktop client
Adorian Doran2aa0bd613897
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 500103c00f..dabd1e9afa 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -25,6 +25,7 @@ import IpcMessagingProvider from "./ipc_messaging_provider";import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";import { setupCustomDictionary } from "./services/custom_dictionary";+import { setupEmbedReferer } from "./services/embed_referer";import { setupPrintingHandlers } from "./services/printing";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";import { setupShellHandlers } from "./services/shell";@@ -228,6 +229,12 @@ function getUserData() {async function onReady() {// app.setAppUserModelId('com.github.zadam.trilium');+ // Supply a valid Referer for embed providers (e.g. YouTube) that reject the+ // custom `trilium-app://` origin. We use the desktop's local server origin —+ // the same value the working browser client sends. Registered on the shared+ // default session before any window is created.+ setupEmbedReferer(`http://localhost:${port}/`);+// if db is not initialized -> setup process// if db is initialized, then we need to wait until the migration process is finishedif (sql_init.isDbInitialized()) {diff --git a/apps/desktop/src/services/embed_referer.spec.ts b/apps/desktop/src/services/embed_referer.spec.tsnew file mode 100644index 0000000000..f5570037e3--- /dev/null+++ b/apps/desktop/src/services/embed_referer.spec.ts@@ -0,0 +1,38 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("electron", () => ({+ default: {+ session: { defaultSession: { webRequest: { onBeforeSendHeaders: () => {} } } }+ }+}));++const { setupEmbedReferer } = await import("./embed_referer.js");++describe("setupEmbedReferer", () => {+ it("registers a header hook scoped to the embed providers that injects the given Referer", () => {+ let captured: ((details: any, cb: (r: any) => void) => void) | undefined;+ const session = {+ webRequest: {+ onBeforeSendHeaders: vi.fn((_filter: any, handler: any) => {+ captured = handler;+ })+ }+ };++ setupEmbedReferer("http://localhost:37840/", session as any);++ expect(session.webRequest.onBeforeSendHeaders).toHaveBeenCalledTimes(1);+ const [filter] = session.webRequest.onBeforeSendHeaders.mock.calls[0];+ // Scoped to the embed providers (Electron does the actual URL matching),+ // and notably NOT a catch-all.+ expect(filter.urls).toContain("*://*.youtube.com/*");+ expect(filter.urls).toContain("*://*.youtube-nocookie.com/*");+ expect(filter.urls).not.toContain("*://*/*");++ // The handler sets the supplied origin as the Referer and forwards the headers.+ let result: any;+ captured!({ url: "https://www.youtube.com/embed/abc", requestHeaders: { "X-Foo": "bar" } }, (r) => (result = r));+ expect(result.requestHeaders["Referer"]).toBe("http://localhost:37840/");+ expect(result.requestHeaders["X-Foo"]).toBe("bar");+ });+});diff --git a/apps/desktop/src/services/embed_referer.ts b/apps/desktop/src/services/embed_referer.tsnew file mode 100644index 0000000000..9d46c3b2ee--- /dev/null+++ b/apps/desktop/src/services/embed_referer.ts@@ -0,0 +1,49 @@+import electron, { type Session } from "electron";++/**+ * Embed providers whose players reject requests that carry no valid HTTP+ * `Referer`. The desktop renderer is loaded from the custom `trilium-app://app`+ * origin (see {@link ../protocol.ts}), which sends no http(s) Referer, so these+ * embeds fail (YouTube "Video player configuration error" — code 153 with no+ * Referer, code 152 with an invalid one). YouTube's Terms of Service now+ * require a valid Referer for embeds.+ *+ * The browser/server client works because its real origin (`http://localhost:<port>`)+ * is sent as the Referer; we replicate that for the desktop app. This fixes both+ * CKEditor's MediaEmbed and Trilium's own link embeds, since both point the+ * iframe at these same provider URLs.+ *+ * Add new entries here if another embed provider shows the same failure.+ */+const EMBED_PROVIDER_URLS = [+ "*://*.youtube.com/*",+ "*://*.youtube-nocookie.com/*"+];++let installed = false;++/**+ * Installs a single `onBeforeSendHeaders` hook on the session (default: the+ * shared default session used by all desktop windows) that sets `appOrigin` as+ * the `Referer` on requests to the embed providers above.+ *+ * `appOrigin` must be a normal http(s) origin that YouTube accepts as an embed+ * host — e.g. the desktop's own local server, `http://localhost:<port>`, which+ * is exactly what the working browser client sends. It must NOT be the+ * provider's own domain (`https://www.youtube.com`): YouTube rejects that as an+ * invalid embed host (Error 152).+ *+ * Must be called after `app.ready`. Idempotent — only the first call registers+ * the hook (Electron allows a single `onBeforeSendHeaders` listener per session).+ */+export function setupEmbedReferer(appOrigin: string, session: Session = electron.session.defaultSession) {+ if (installed) {+ return;+ }+ installed = true;++ session.webRequest.onBeforeSendHeaders({ urls: EMBED_PROVIDER_URLS }, (details, callback) => {+ details.requestHeaders["Referer"] = appOrigin;+ callback({ requestHeaders: details.requestHeaders });+ });+}