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
fix(geomap): tell a tile server who is asking, rather than be handed a notice
Elian Dorana35a10df9198
diff --git a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx b/apps/client/src/widgets/collections/geomap/map.init.spec.tsxindex 3b9ae068d9..9b21122c5c 100644--- a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/map.init.spec.tsx@@ -168,6 +168,26 @@ describe("Map initialization", () => {expect(container.querySelector(".map-child")).not.toBeNull();});+ /**+ * The app is served with `Referrer-Policy: no-referrer`, and OpenStreetMap answers a request that+ * says nothing of itself with a 403 drawn into the tile — an image reading "Access blocked",+ * served as HTTP 200, so the map fills with complaint and no error is ever raised. A policy on+ * the request itself is what overrules the document's.+ */+ it("tells a tile server where it is asking from, which the page's own policy would withhold", () => {+ MapConstructor.mockImplementation(workingMap);++ renderMap();++ const { transformRequest } = MapConstructor.mock.calls[0][0];+ expect(transformRequest("https://tile.openstreetmap.org/2/1/1.png", "Tile")).toEqual({+ url: "https://tile.openstreetmap.org/2/1/1.png",+ // The origin and never the path, so no note is named, and nothing at all from a secure+ // page to an insecure server.+ referrerPolicy: "strict-origin"+ });+ });+/*** Leaving a geo map for another note, which used to throw where nobody could catch it: the scale* was taken off a map that had already gone, and a control given its notice twice reaches for thediff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsxindex 36a4999d3e..e205d7bc42 100644--- a/apps/client/src/widgets/collections/geomap/map.tsx+++ b/apps/client/src/widgets/collections/geomap/map.tsx@@ -1,6 +1,6 @@import "maplibre-gl/dist/maplibre-gl.css";-import { AttributionControl, type ErrorEvent as MapErrorEvent, Map as MapLibreGLMap, MapMouseEvent, type Point, ScaleControl, type StyleSpecification, type TransformStyleFunction } from "maplibre-gl";+import { AttributionControl, type ErrorEvent as MapErrorEvent, Map as MapLibreGLMap, MapMouseEvent, type Point, type RequestTransformFunction, ScaleControl, type StyleSpecification, type TransformStyleFunction } from "maplibre-gl";import { ComponentChildren, createContext, RefObject } from "preact";import { useEffect, useImperativeHandle, useRef, useState } from "preact/hooks";@@ -302,10 +302,22 @@ function createMap(container: HTMLDivElement, style: StyleSpecification | string// behavior we want.renderWorldCopies: false,// Added by hand by the caller, in the corner opposite the one MapLibre keeps it in.- attributionControl: false+ attributionControl: false,+ transformRequest: withReferrer});}+/**+ * Names the app to a tile server, which `Referrer-Policy: no-referrer` otherwise keeps from it —+ * OpenStreetMap answers an anonymous request with a refusal drawn into the tile, served as HTTP 200+ * so that nothing here ever sees an error. Given per request, so the rest of the page keeps the+ * policy it is served with; `strict-origin` names no note and says nothing to an insecure server.+ *+ * Nothing to send where the app has no http(s) origin: desktop puts the header back by hand (see+ * `services/referer.ts`), and iOS on `capacitor://` has nowhere to do that yet.+ */+const withReferrer: RequestTransformFunction = (url) => ({ url, referrerPolicy: "strict-origin" });+/** An HTTP failure as MapLibre reports one: what {@link summarizeMapError} reads off an `AJAXError`. */interface HttpFailure {status: number;diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex ccc2d3606f..a4ec6258f3 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -111,7 +111,7 @@ vi.mock("electron", () => {handle: (channel: string, fn: Handler) => h.ipcHandle.set(channel, fn)};// onReady() installs the embed-Referer hook, whose default argument reads- // `electron.session.defaultSession` (see services/embed_referer.ts).+ // `electron.session.defaultSession` (see services/referer.ts).const session = {defaultSession: {webRequest: {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex e6f2fc99b7..e3dfa9f3e3 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -28,7 +28,7 @@ import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";import { applyLaunchOnStartup, setupAutoLaunch, wasLaunchedHidden } from "./services/auto_launch";import { setupCustomDictionary } from "./services/custom_dictionary";-import { setupEmbedReferer } from "./services/embed_referer";+import { setupReferer } from "./services/referer";import { setupExportHandlers } from "./services/export";import { setupImportHandlers } from "./services/import";import { setupOneNoteHandlers } from "./services/onenote";@@ -324,7 +324,7 @@ async function onReady() {// 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}/`);+ setupReferer(`http://localhost:${port}/`);// if db is not initialized -> setup process// if db is initialized, then we need to wait until the migration process is finisheddiff --git a/apps/desktop/src/services/embed_referer.ts b/apps/desktop/src/services/embed_referer.tsdeleted file mode 100644index e5cba03419..0000000000--- a/apps/desktop/src/services/embed_referer.ts+++ /dev/null@@ -1,63 +0,0 @@-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- * Trilium's link embeds (and any other embedded YouTube/Vimeo iframe), since- * they 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/*"-];--/**- * Sessions already carrying the hook. Keyed on the session rather than a module-wide flag so that a- * second session (and each test) can install its own — Electron allows one `onBeforeSendHeaders`- * listener per session, not one per process.- */-const installedSessions = new WeakSet<Session>();--/**- * 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 per session — a repeat call for a session that- * already has the hook does nothing.- */-export function setupEmbedReferer(appOrigin: string, session: Session = electron.session.defaultSession) {- if (installedSessions.has(session)) {- return;- }- installedSessions.add(session);-- session.webRequest.onBeforeSendHeaders({ urls: EMBED_PROVIDER_URLS }, (details, callback) => {- // Header names are case-insensitive, but `requestHeaders` is a plain object with- // case-sensitive keys: assigning "Referer" alongside an existing "referer" would send the- // header twice, and YouTube rejects a request whose embed host it cannot pin down.- for (const name of Object.keys(details.requestHeaders)) {- if (name.toLowerCase() === "referer") {- delete details.requestHeaders[name];- }- }- details.requestHeaders["Referer"] = appOrigin;-- callback({ requestHeaders: details.requestHeaders });- });-}diff --git a/apps/desktop/src/services/embed_referer.spec.ts b/apps/desktop/src/services/referer.spec.tssimilarity index 79%rename from apps/desktop/src/services/embed_referer.spec.tsrename to apps/desktop/src/services/referer.spec.tsindex 97f539ff4b..0cd0a2d1a1 100644--- a/apps/desktop/src/services/embed_referer.spec.ts+++ b/apps/desktop/src/services/referer.spec.ts@@ -7,7 +7,7 @@ vi.mock("electron", () => ({}}));-const { setupEmbedReferer } = await import("./embed_referer.js");+const { setupReferer } = await import("./referer.js");type RequestHeaders = Record<string, string>;type Filter = { urls: string[] };@@ -49,17 +49,18 @@ function fakeSession() {};}-describe("setupEmbedReferer", () => {- it("registers a header hook scoped to the embed providers that injects the given Referer", () => {+describe("setupReferer", () => {+ it("registers a header hook scoped to the hosts that need one, and injects the given Referer", () => {const { session, registrations, filter, run } = fakeSession();- setupEmbedReferer("http://localhost:37840/", session);+ setupReferer("http://localhost:37840/", session);expect(registrations()).toBe(1);- // Scoped to the embed providers (Electron does the actual URL matching),- // and notably NOT a catch-all.+ // Scoped to the hosts that turn away an unidentified request (Electron does the actual URL+ // matching), and notably NOT a catch-all: a Referer says where the reader is.expect(filter()?.urls).toContain("*://*.youtube.com/*");expect(filter()?.urls).toContain("*://*.youtube-nocookie.com/*");+ expect(filter()?.urls).toContain("*://tile.openstreetmap.org/*");expect(filter()?.urls).not.toContain("*://*/*");// The handler sets the supplied origin as the Referer and forwards the headers.@@ -71,7 +72,7 @@ describe("setupEmbedReferer", () => {it("replaces an existing Referer whatever its casing, so the header is never sent twice", () => {const { session, run } = fakeSession();- setupEmbedReferer("http://localhost:37840/", session);+ setupReferer("http://localhost:37840/", session);const headers = run({ "referer": "https://elsewhere.example.com/", "X-Foo": "bar" });expect(Object.keys(headers).filter((name) => name.toLowerCase() === "referer")).toEqual(["Referer"]);@@ -83,9 +84,9 @@ describe("setupEmbedReferer", () => {const first = fakeSession();const second = fakeSession();- setupEmbedReferer("http://localhost:37840/", first.session);- setupEmbedReferer("http://localhost:37840/", first.session);- setupEmbedReferer("http://localhost:37840/", second.session);+ setupReferer("http://localhost:37840/", first.session);+ setupReferer("http://localhost:37840/", first.session);+ setupReferer("http://localhost:37840/", second.session);// Electron allows one listener per session — not one per process.expect(first.registrations()).toBe(1);diff --git a/apps/desktop/src/services/referer.ts b/apps/desktop/src/services/referer.tsnew file mode 100644index 0000000000..0008d9697f--- /dev/null+++ b/apps/desktop/src/services/referer.ts@@ -0,0 +1,73 @@+import electron, { type Session } from "electron";++/**+ * Hosts that turn away a request carrying no valid HTTP `Referer`. The desktop renderer is loaded+ * from the custom `trilium-app://app` origin (see {@link ../protocol.ts}), and a referrer whose+ * scheme is not http(s) is dropped by the browser before the request leaves — so the desktop app+ * tells these hosts nothing about itself, whatever referrer policy it asks for.+ *+ * The browser/server client works because its real origin (`http://localhost:<port>`) is sent as the+ * Referer; we replicate that here, in the one place a header can still be set by hand.+ *+ * - **YouTube** rejects the embedded player ("Video player configuration error" — code 153 with no+ * Referer, code 152 with an invalid one); their Terms of Service now require a valid one. This+ * covers Trilium's link embeds and any other embedded YouTube/Vimeo iframe, since they point at+ * these same provider URLs.+ * - **OpenStreetMap's tile servers** answer an unidentified request with a 403 *drawn into the+ * tile* — an image reading "Access blocked", served as HTTP 200, so the geo map shows tiled+ * complaint rather than a map and nothing on the page ever sees an error. Their tile usage policy+ * requires either a Referer or a User-Agent identifying the app; the browser client sends its+ * origin (see the geo map's own `transformRequest`), and this is the desktop's answer to the same+ * requirement.+ *+ * Add new entries here if another host shows the same failure. Only hosts that need it: a Referer+ * says where the reader is, and there is no reason to volunteer that to anyone who has not asked.+ */+const REFERER_REQUIRED_URLS = [+ "*://*.youtube.com/*",+ "*://*.youtube-nocookie.com/*",+ "*://tile.openstreetmap.org/*",+ "*://*.tile.openstreetmap.org/*"+];++/**+ * Sessions already carrying the hook. Keyed on the session rather than a module-wide flag so that a+ * second session (and each test) can install its own — Electron allows one `onBeforeSendHeaders`+ * listener per session, not one per process.+ */+const installedSessions = new WeakSet<Session>();++/**+ * 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 hosts 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 per session — a repeat call for a session that+ * already has the hook does nothing.+ */+export function setupReferer(appOrigin: string, session: Session = electron.session.defaultSession) {+ if (installedSessions.has(session)) {+ return;+ }+ installedSessions.add(session);++ session.webRequest.onBeforeSendHeaders({ urls: REFERER_REQUIRED_URLS }, (details, callback) => {+ // Header names are case-insensitive, but `requestHeaders` is a plain object with+ // case-sensitive keys: assigning "Referer" alongside an existing "referer" would send the+ // header twice, and YouTube rejects a request whose embed host it cannot pin down.+ for (const name of Object.keys(details.requestHeaders)) {+ if (name.toLowerCase() === "referer") {+ delete details.requestHeaders[name];+ }+ }+ details.requestHeaders["Referer"] = appOrigin;++ callback({ requestHeaders: details.requestHeaders });+ });+}