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
refactor(desktop): single source of truth for the trilium-app origin
Elian Doran0cf1d5808373
diff --git a/apps/desktop/src/protocol.ts b/apps/desktop/src/protocol.tsindex 44882ba6a2..6d486731b8 100644--- a/apps/desktop/src/protocol.ts+++ b/apps/desktop/src/protocol.ts@@ -6,6 +6,8 @@ import EventEmitter from "events";import type { Application, Response as ExpressResponse } from "express";import { createResponse, type MockResponse } from "node-mocks-http";+import { isTriliumAppShellUrl, TRILIUM_APP_ORIGIN, TRILIUM_APP_SCHEME } from "./services/trilium_app_origin.js";+/*** Registers the `trilium-app://` custom scheme as privileged so the renderer* can load the UI from `trilium-app://app/` with a proper origin & cookie jar,@@ -24,7 +26,7 @@ import { createResponse, type MockResponse } from "node-mocks-http";export function registerTriliumAppScheme() {protocol.registerSchemesAsPrivileged([{- scheme: "trilium-app",+ scheme: TRILIUM_APP_SCHEME,privileges: {standard: true,secure: true,@@ -49,7 +51,7 @@ export function registerTriliumAppScheme() {export function setupTriliumAppProtocol(app: Application) {electron.app.whenReady().then(() => {installFrameOriginGuard();- electron.protocol.handle("trilium-app", async (request) => {+ electron.protocol.handle(TRILIUM_APP_SCHEME, async (request) => {const origin = request.headers.get("origin");if (!isDispatchOriginAllowed(origin)) {console.error(`[trilium-app] blocked ${request.method} ${request.url} from origin '${origin}'`);@@ -107,7 +109,7 @@ export function setupTriliumAppProtocol(app: Application) {* registered, so the scheme does not resolve there at all.*/function installFrameOriginGuard() {- electron.session.defaultSession.webRequest.onBeforeRequest({ urls: ["trilium-app://*/*"] }, (details, callback) => {+ electron.session.defaultSession.webRequest.onBeforeRequest({ urls: [`${TRILIUM_APP_SCHEME}://*/*`] }, (details, callback) => {let frameUrls: string[];try {frameUrls = [];@@ -141,9 +143,11 @@ export function isRequestorChainTrusted(resourceType: string, frameUrls: string[}function isTrustedFrameUrl(frameUrl: string): boolean {+ if (isTriliumAppShellUrl(frameUrl)) {+ return true;+ }try {- const parsed = new URL(frameUrl);- return (parsed.protocol === "trilium-app:" && parsed.host === "app") || parsed.protocol === "devtools:";+ return new URL(frameUrl).protocol === "devtools:";} catch {return false;}@@ -158,7 +162,7 @@ function isTrustedFrameUrl(frameUrl: string): boolean {* the absence of the header proves nothing and must be allowed through.*/export function isDispatchOriginAllowed(origin: string | null): boolean {- return origin === null || origin === "trilium-app://app";+ return origin === null || origin === TRILIUM_APP_ORIGIN;}export async function dispatch(app: Application, request: Request): Promise<Response> {diff --git a/apps/desktop/src/services/printing.ts b/apps/desktop/src/services/printing.tsindex 62ef5e4f4c..bee11fb536 100644--- a/apps/desktop/src/services/printing.ts+++ b/apps/desktop/src/services/printing.ts@@ -4,6 +4,8 @@ import fs from "fs/promises";import { t } from "i18next";import path from "path";+import { TRILIUM_APP_BASE_URL } from "./trilium_app_origin.js";+// Preload bundle path — built next to main.cjs in production by// apps/desktop/scripts/build.ts, or compiled in-place by the dev runner// (scripts/electron-start.mts) into apps/desktop/src/preload.compiled.cjs.@@ -140,7 +142,7 @@ async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, ac// would split origins — the main window's session cookie wouldn't// reach the print window, auth would redirect to /login, and the// print page would never render.- await browserWindow.loadURL(`trilium-app://app/?print#${notePath}`);+ await browserWindow.loadURL(`${TRILIUM_APP_BASE_URL}?print#${notePath}`);} catch (err) {getLog().error(`Failed to load print window: ${err}`);ipcMain.off("print-progress", progressCallback);diff --git a/apps/desktop/src/services/trilium_app_origin.spec.ts b/apps/desktop/src/services/trilium_app_origin.spec.tsnew file mode 100644index 0000000000..95de675eed--- /dev/null+++ b/apps/desktop/src/services/trilium_app_origin.spec.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";++import { isTriliumAppShellUrl, TRILIUM_APP_BASE_URL, TRILIUM_APP_ORIGIN } from "./trilium_app_origin.js";++describe("trilium_app_origin", () => {+ it("derives the origin and base URL from the scheme and host", () => {+ expect(TRILIUM_APP_ORIGIN).toBe("trilium-app://app");+ expect(TRILIUM_APP_BASE_URL).toBe("trilium-app://app/");+ });++ describe("isTriliumAppShellUrl", () => {+ it("accepts the app shell origin and any path under it", () => {+ expect(isTriliumAppShellUrl("trilium-app://app")).toBe(true);+ expect(isTriliumAppShellUrl("trilium-app://app/")).toBe(true);+ expect(isTriliumAppShellUrl("trilium-app://app/pdfjs/web/viewer.html")).toBe(true);+ expect(isTriliumAppShellUrl("trilium-app://app/?print#root/abc")).toBe(true);+ });++ it("rejects other hosts, schemes, and unparseable / empty input", () => {+ expect(isTriliumAppShellUrl("trilium-app://evil")).toBe(false);+ expect(isTriliumAppShellUrl("trilium-app://app.evil.example")).toBe(false);+ expect(isTriliumAppShellUrl("https://www.youtube-nocookie.com/embed/x")).toBe(false);+ expect(isTriliumAppShellUrl("devtools://devtools/bundled/devtools_app.html")).toBe(false);+ expect(isTriliumAppShellUrl("not a url")).toBe(false);+ expect(isTriliumAppShellUrl("")).toBe(false);+ expect(isTriliumAppShellUrl(null)).toBe(false);+ expect(isTriliumAppShellUrl(undefined)).toBe(false);+ });+ });+});diff --git a/apps/desktop/src/services/trilium_app_origin.ts b/apps/desktop/src/services/trilium_app_origin.tsnew file mode 100644index 0000000000..561e23ec84--- /dev/null+++ b/apps/desktop/src/services/trilium_app_origin.ts@@ -0,0 +1,36 @@+/**+ * Single source of truth for the desktop app shell's custom scheme and origin.+ *+ * The renderer is served from `trilium-app://app/` — see the `loadURL` call+ * sites (window.ts, printing.ts) and the privileged-scheme registration in+ * protocol.ts. Several independent security gates must all agree on exactly+ * what "the app shell" is: the protocol dispatch origin check, the webRequest+ * frame guard, the navigation guard, and the permission-origin check. Deriving+ * each of them from the constants and predicate here keeps the layers from+ * drifting apart (a mismatch either bricks the app or silently weakens a gate).+ */++/** The privileged custom scheme the desktop UI is served from (no trailing colon). */+export const TRILIUM_APP_SCHEME = "trilium-app";++/** The sole host the app shell is ever loaded under. */+export const TRILIUM_APP_HOST = "app";++/** Canonical origin of the app shell, e.g. for exact `Origin`-header matching. */+export const TRILIUM_APP_ORIGIN = `${TRILIUM_APP_SCHEME}://${TRILIUM_APP_HOST}`;++/** Root URL the windows load (origin + `/`). */+export const TRILIUM_APP_BASE_URL = `${TRILIUM_APP_ORIGIN}/`;++/** True when `rawUrl` parses to the app shell origin (`trilium-app://app`). */+export function isTriliumAppShellUrl(rawUrl: string | null | undefined): boolean {+ if (!rawUrl) {+ return false;+ }+ try {+ const parsed = new URL(rawUrl);+ return parsed.protocol === `${TRILIUM_APP_SCHEME}:` && parsed.host === TRILIUM_APP_HOST;+ } catch {+ return false;+ }+}diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.tsindex 2a0eae7524..10a20aa5aa 100644--- a/apps/desktop/src/services/web_contents_security.ts+++ b/apps/desktop/src/services/web_contents_security.ts@@ -4,6 +4,7 @@ import electron from "electron";import url from "url";import { validateOpenExternalUrl } from "./shell.js";+import { isTriliumAppShellUrl, TRILIUM_APP_HOST, TRILIUM_APP_SCHEME } from "./trilium_app_origin.js";/*** Security guard for `<webview>` attachment.@@ -176,20 +177,7 @@ export function isPermissionAllowedForOrigin(kind: SessionKind, permission: striif (permission === "fullscreen") {return true;}- return isAppShellOrigin(requestingUrl);-}--/** True only for the app shell's own origin (`trilium-app://app`). */-function isAppShellOrigin(requestingUrl: string | null | undefined): boolean {- if (!requestingUrl) {- return false;- }- try {- const parsed = new URL(requestingUrl);- return parsed.protocol === "trilium-app:" && parsed.host === "app";- } catch {- return false;- }+ return isTriliumAppShellUrl(requestingUrl);}/**@@ -203,7 +191,7 @@ function isAppShellOrigin(requestingUrl: string | null | undefined): boolean {export function isNavigationAllowed(targetUrl: string): boolean {const parsedUrl = url.parse(targetUrl);- const isInternal = (parsedUrl.protocol === "trilium-app:" && parsedUrl.hostname === "app")+ const isInternal = (parsedUrl.protocol === `${TRILIUM_APP_SCHEME}:` && parsedUrl.hostname === TRILIUM_APP_HOST)|| ["localhost", "127.0.0.1"].includes(parsedUrl.hostname || "");return isInternal && (!parsedUrl.path || parsedUrl.path === "/" || parsedUrl.path === "/?");}diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.tsindex 5d8c7673dd..79854a43f1 100644--- a/apps/desktop/src/services/window.ts+++ b/apps/desktop/src/services/window.ts@@ -3,6 +3,7 @@ import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";import { type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";import path from "path";+import { TRILIUM_APP_BASE_URL } from "./trilium_app_origin.js";import { setupWebContentsSecurity } from "./web_contents_security.js";// Preload bundle path. Two layouts:@@ -74,7 +75,7 @@ async function createExtraWindow(extraWindowHash: string) {});win.setMenuBarVisibility(false);- win.loadURL(`trilium-app://app/?extraWindow=1${extraWindowHash}`);+ win.loadURL(`${TRILIUM_APP_BASE_URL}?extraWindow=1${extraWindowHash}`);configureWebContents(win.webContents, spellcheckEnabled);@@ -129,7 +130,7 @@ async function createMainWindow() {mainWindowState.manage(mainWindow);mainWindow.setMenuBarVisibility(false);- mainWindow.loadURL("trilium-app://app/");+ mainWindow.loadURL(TRILIUM_APP_BASE_URL);mainWindow.on("closed", () => (mainWindow = null));configureWebContents(mainWindow.webContents, spellcheckEnabled);@@ -253,7 +254,7 @@ async function createSetupWindow() {}});setupWindow.removeMenu();- setupWindow.loadURL("trilium-app://app/");+ setupWindow.loadURL(TRILIUM_APP_BASE_URL);setupWindow.on("closed", () => (setupWindow = null));}