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(server): make desktop LAN access an app setting, not [Network] host
Elian Doran59df4ff7aab9
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex a68d129c54..e917da6b59 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -452,18 +452,11 @@ function SyncFromDesktop({ setState }: { setState: (state: State) => void }) {<p>{t("setup.sync-from-desktop-unreachable-description")}</p>{isElectron() && (<div class="unreachable-actions">- {networkInfo.configPath && (- <Button- icon="bx bx-edit"- text={t("setup.sync-from-desktop-open-config")}- onClick={() => void openConfigFile(networkInfo.configPath)}- />- )}<Buttonkind="primary"- icon="bx bx-refresh"- text={t("setup.sync-from-desktop-restart")}- onClick={() => window.electronApi?.window.restartApp()}+ icon="bx bx-broadcast"+ text={t("setup.sync-from-desktop-allow-access")}+ onClick={() => void allowLanAccessAndRestart()}/></div>)}@@ -600,17 +593,13 @@ async function getNetworkAddresses(): Promise<NetworkAddressesResponse> {return await server.get<NetworkAddressesResponse>("network-addresses");}-async function openConfigFile(configPath?: string) {- if (!configPath) {- return;- }-- // `openPath` resolves to a non-empty string when the OS couldn't open the- // file (e.g. no editor associated with `.ini`). The path is also shown in- // the banner, so the user can still navigate to it manually.- const error = await window.electronApi?.shell.openPath(configPath);- if (error) {- console.error(`Could not open config file "${configPath}": ${error}`);+async function allowLanAccessAndRestart() {+ // Shows a native confirmation dialog (LAN exposure is a security tradeoff)+ // and persists the choice to security.json. Only restart once the user has+ // actually confirmed — otherwise the binding wouldn't change anyway.+ const confirmed = await window.electronApi?.security.setLanAccessEnabled(true);+ if (confirmed) {+ window.electronApi?.window.restartApp();}}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex dea638ed38..65704400ce 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2790,9 +2790,8 @@"sync-from-desktop-warning": "Make sure both devices are on the same network.","sync-from-desktop-waiting": "Waiting for connection...","sync-from-desktop-unreachable-title": "This device can't be reached by other devices",- "sync-from-desktop-unreachable-description": "To sync, the other desktop has to connect to this one over the network. For security, this desktop app only accepts connections from this computer, so that other desktop can't reach it yet. To let it in, set \"host=0.0.0.0\" under the [Network] section of your config.ini, then restart Trilium.",- "sync-from-desktop-open-config": "Open config file",- "sync-from-desktop-restart": "Restart Trilium",+ "sync-from-desktop-unreachable-description": "To sync, the other desktop has to connect to this one over the network. For security, this desktop app only accepts connections from this computer, so that other desktop can't reach it yet. Allow network access below — Trilium will restart to apply it.",+ "sync-from-desktop-allow-access": "Allow network access & restart","advanced-options": "Advanced options","sync-failed": "Failed to sync: {{message}}","server-host": "Trilium server address",diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex 9de1e4cefd..f0ba88cbf7 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -12,6 +12,7 @@ interface FakeWindow {interface SecuritySettings {backendScriptingEnabled?: boolean;sqlConsoleEnabled?: boolean;+ allowLanAccess?: boolean;}// A tiny real deferred so the core/server init promises behave like the real thing.@@ -550,6 +551,16 @@ describe("security settings override", () => {expect(config.Security.backendScriptingEnabled).toBe(true);expect(config.Security.sqlConsoleEnabled).toBe(true);});++ it("applies the allowLanAccess override", async () => {+ h.securitySettings = { allowLanAccess: true };+ const { main } = await importMain();+ await main();+ const config = (await import("@triliumnext/server/src/services/config.js")).default as {+ Security: { allowLanAccess?: boolean };+ };+ expect(config.Security.allowLanAccess).toBe(true);+ });});describe("initializeCore dbConfig callbacks + getDemoArchive", () => {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex bf61ef5921..3c46d531e6 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -166,6 +166,11 @@ export async function main() {if (securitySettings.sqlConsoleEnabled !== undefined) {config.Security.sqlConsoleEnabled = securitySettings.sqlConsoleEnabled;}+ // Applied before the server (and host.ts) load below, so getHost() picks up+ // the desktop LAN-access choice on this boot.+ if (securitySettings.allowLanAccess !== undefined) {+ config.Security.allowLanAccess = securitySettings.allowLanAccess;+ }const dbProvider = new BetterSqlite3Provider();dbProvider.loadFromFile(DOCUMENT_PATH, config.General.readOnly);diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 9f02fa48d5..9543dc71dc 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -598,5 +598,10 @@ describe("preload script", () => {await security().setSqlConsoleEnabled(false);expect(ipcRendererInvoked).toContainEqual({ channel: "security-set-sql-console", args: [false] });});++ it("setLanAccessEnabled invokes the corresponding IPC channel", async () => {+ await security().setLanAccessEnabled(true);+ expect(ipcRendererInvoked).toContainEqual({ channel: "security-set-lan-access", args: [true] });+ });});});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex f991d49787..cdab8da3c0 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -257,6 +257,9 @@ contextBridge.exposeInMainWorld("electronApi", {},setSqlConsoleEnabled(enabled: boolean): Promise<boolean> {return ipcRenderer.invoke("security-set-sql-console", enabled);+ },+ setLanAccessEnabled(enabled: boolean): Promise<boolean> {+ return ipcRenderer.invoke("security-set-lan-access", enabled);}}} satisfies ElectronApi);diff --git a/apps/desktop/src/services/security_settings.ts b/apps/desktop/src/services/security_settings.tsindex 566902719d..39c94c00b3 100644--- a/apps/desktop/src/services/security_settings.ts+++ b/apps/desktop/src/services/security_settings.ts@@ -9,6 +9,7 @@ const SECURITY_JSON_PATH = path.join(dataDirs.TRILIUM_DATA_DIR, "security.json")interface SecuritySettings {backendScriptingEnabled?: boolean;sqlConsoleEnabled?: boolean;+ allowLanAccess?: boolean;}function readSettings(): SecuritySettings {@@ -121,4 +122,10 @@ export function registerSecurityIpcHandlers(): void {"security-dialog.sql-console","security-dialog.sql-console-warning");+ registerToggleHandler(+ "security-set-lan-access",+ "allowLanAccess",+ "security-dialog.lan-access",+ "security-dialog.lan-access-warning"+ );}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 958a452b94..d01506fb66 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -420,6 +420,8 @@"backend-scripting": "Backend script execution","backend-scripting-warning": "Backend scripts have full access to the server, including the file system and network.","sql-console": "SQL console",- "sql-console-warning": "The SQL console allows executing arbitrary SQL queries against the database."+ "sql-console-warning": "The SQL console allows executing arbitrary SQL queries against the database.",+ "lan-access": "network access",+ "lan-access-warning": "Other devices on your local network will be able to connect to this Trilium instance."}}diff --git a/apps/server/src/routes/api/system_info.ts b/apps/server/src/routes/api/system_info.tsindex a9b8b9f45b..e2648b1c14 100644--- a/apps/server/src/routes/api/system_info.ts+++ b/apps/server/src/routes/api/system_info.ts@@ -3,7 +3,6 @@ import { execSync } from "child_process";import { arch, cpus, networkInterfaces } from "os";import config from "../../services/config.js";-import dataDir from "../../services/data_dir.js";import host from "../../services/host.js";import port from "../../services/port.js";import { isMac, isWindows } from "../../services/utils";@@ -27,8 +26,7 @@ function getNetworkAddresses(): NetworkAddressesResponse {return {addresses: collectNetworkAddresses(networkInterfaces()).map((addr) => buildNetworkUrl(protocol, addr, port)),- reachableOnNetwork: isHostReachableOnNetwork(host),- configPath: dataDir.CONFIG_INI_PATH+ reachableOnNetwork: isHostReachableOnNetwork(host)};}diff --git a/apps/server/src/services/config.spec.ts b/apps/server/src/services/config.spec.tsindex 6e8f3e06bc..f29b9004c7 100644--- a/apps/server/src/services/config.spec.ts+++ b/apps/server/src/services/config.spec.ts@@ -345,7 +345,7 @@ corsAllowOrigin=https://ini-cors.comexpect(config.General.noDesktopIcon).toBe(false);expect(config.General.readOnly).toBe(false);- // Network defaults (server build binds all interfaces by default)+ // Network defaults (host is the web/server bind address)expect(config.Network.host).toBe("0.0.0.0");expect(config.Network.port).toBe("3000");expect(config.Network.https).toBe(false);@@ -374,23 +374,11 @@ corsAllowOrigin=https://ini-cors.com// Logging defaultsexpect(config.Logging.retentionDays).toBe(90);- });- it("defaults the host to loopback on desktop (Electron)", async () => {- const originalElectron = process.versions.electron;- // The default is computed from `process.versions.electron` at module- // load, so stub it before importing config (modules are reset per test).- Object.defineProperty(process.versions, "electron", { value: "41.0.0", configurable: true });- try {- const { default: config } = await import("./config.js");- expect(config.Network.host).toBe("127.0.0.1");- } finally {- if (originalElectron === undefined) {- delete (process.versions as { electron?: string }).electron;- } else {- Object.defineProperty(process.versions, "electron", { value: originalElectron, configurable: true });- }- }+ // Security defaults (allowLanAccess is the desktop LAN-bind override)+ expect(config.Security.backendScriptingEnabled).toBe(false);+ expect(config.Security.sqlConsoleEnabled).toBe(false);+ expect(config.Security.allowLanAccess).toBe(false);});});});\ No newline at end of filediff --git a/apps/server/src/services/config.ts b/apps/server/src/services/config.tsindex 72be778e62..0fbfb2f461 100644--- a/apps/server/src/services/config.ts+++ b/apps/server/src/services/config.ts@@ -144,6 +144,12 @@ export interface TriliumConfig {backendScriptingEnabled: boolean;/** Whether the SQL console is accessible (default: false) */sqlConsoleEnabled: boolean;+ /**+ * Desktop only: whether the TCP listener binds all interfaces (LAN-reachable)+ * instead of loopback. Managed via the desktop `security.json` override, not+ * config.ini. Consumed by host.ts; has no effect on server builds.+ */+ allowLanAccess: boolean;};}@@ -322,15 +328,11 @@ const configMapping = {},Network: {host: {+ // Web/server only — desktop ignores this and resolves its bind+ // address from the `allowLanAccess` security override (see host.ts).standardEnvVar: 'TRILIUM_NETWORK_HOST',iniGetter: () => getIniSection("Network")?.host,- // Desktop (Electron) binds loopback by default: the renderer reaches- // the server in-process via `trilium-app://`, so the TCP listener- // only needs same-host traffic, and keeping the port off the LAN is- // defense in depth on top of the per-request auth marker. Server- // builds bind all interfaces. Either can be overridden via the env- // var or config.ini.- defaultValue: process.versions.electron ? '127.0.0.1' : '0.0.0.0'+ defaultValue: '0.0.0.0'},port: {standardEnvVar: 'TRILIUM_NETWORK_PORT',@@ -490,6 +492,14 @@ const configMapping = {iniGetter: () => getIniSection("Security")?.sqlConsoleEnabled,defaultValue: false,transformer: transformBoolean+ },+ allowLanAccess: {+ // Desktop-only: normally written to security.json and applied by the+ // Electron main process at startup; host.ts reads it instead of the+ // [Network] host. Kept off the documented config surface on purpose.+ iniGetter: () => getIniSection("Security")?.allowLanAccess,+ defaultValue: false,+ transformer: transformBoolean}}};@@ -547,7 +557,8 @@ const config: TriliumConfig = {},Security: {backendScriptingEnabled: getConfigValue(configMapping.Security.backendScriptingEnabled),- sqlConsoleEnabled: getConfigValue(configMapping.Security.sqlConsoleEnabled)+ sqlConsoleEnabled: getConfigValue(configMapping.Security.sqlConsoleEnabled),+ allowLanAccess: getConfigValue(configMapping.Security.allowLanAccess)}};diff --git a/apps/server/src/services/host.spec.ts b/apps/server/src/services/host.spec.tsindex bdc4faea72..c705c55a67 100644--- a/apps/server/src/services/host.spec.ts+++ b/apps/server/src/services/host.spec.ts@@ -15,32 +15,42 @@ describe("host", () => {vi.doUnmock("./utils.js");});- async function loadHost(opts: { isElectron: boolean; configHost: string }) {+ async function loadHost(opts: { isElectron: boolean; configHost?: string; allowLanAccess?: boolean }) {vi.resetModules();vi.doMock("./utils.js", () => ({ isElectron: opts.isElectron }));- vi.doMock("./config.js", () => ({ default: { Network: { host: opts.configHost } } }));+ vi.doMock("./config.js", () => ({+ default: {+ Network: { host: opts.configHost ?? "" },+ Security: { allowLanAccess: opts.allowLanAccess ?? false }+ }+ }));return (await import("./host.js")).default;}- it("prefers TRILIUM_HOST env var when not running under Electron", async () => {+ // Desktop: the [Network] host config (and TRILIUM_HOST) are for web+ // deployments — the listener binds loopback unless LAN access is allowed.+ it("binds loopback under Electron, ignoring the config host and TRILIUM_HOST", async () => {process.env.TRILIUM_HOST = "env-host";- expect(await loadHost({ isElectron: false, configHost: "config-host" })).toBe("env-host");+ expect(await loadHost({ isElectron: true, configHost: "config-host" })).toBe("127.0.0.1");});- it("ignores TRILIUM_HOST under Electron and falls back to config host", async () => {- process.env.TRILIUM_HOST = "env-host";- expect(await loadHost({ isElectron: true, configHost: "config-host" })).toBe("config-host");+ it("binds all interfaces under Electron when LAN access is allowed", async () => {+ expect(await loadHost({ isElectron: true, allowLanAccess: true })).toBe("0.0.0.0");});- it("uses the config host when no env var is set", async () => {- expect(await loadHost({ isElectron: false, configHost: "config-host" })).toBe("config-host");+ // Server: TRILIUM_HOST > config host > all-interfaces default.+ it("prefers TRILIUM_HOST env var on the server", async () => {+ process.env.TRILIUM_HOST = "env-host";+ expect(await loadHost({ isElectron: false, configHost: "config-host" })).toBe("env-host");});- it("defaults to loopback under Electron when nothing else is set", async () => {- expect(await loadHost({ isElectron: true, configHost: "" })).toBe("127.0.0.1");+ it("uses the config host on the server when no env var is set", async () => {+ expect(await loadHost({ isElectron: false, configHost: "config-host" })).toBe("config-host");});- it("defaults to all interfaces on the server when nothing else is set", async () => {- expect(await loadHost({ isElectron: false, configHost: "" })).toBe("0.0.0.0");+ // The all-interfaces default lives in the config layer (configMapping.Network.host),+ // so host.ts just returns whatever config resolves — here, that default.+ it("returns the all-interfaces config default on the server", async () => {+ expect(await loadHost({ isElectron: false, configHost: "0.0.0.0" })).toBe("0.0.0.0");});});diff --git a/apps/server/src/services/host.ts b/apps/server/src/services/host.tsindex b17e568d1f..044b76179f 100644--- a/apps/server/src/services/host.ts+++ b/apps/server/src/services/host.ts@@ -2,16 +2,21 @@ import config from "./config.js";import { isElectron } from "./utils.js";function getHost() {+ if (isElectron) {+ // Desktop ignores the [Network] host config — that setting is for web+ // deployments. The renderer reaches the server in-process via+ // `trilium-app://`, so the TCP listener binds loopback and stays off the+ // LAN by default. The user opts into LAN access (e.g. to sync from+ // another device) with the `allowLanAccess` security override, which the+ // desktop main process applies to the config at startup.+ return config["Security"]["allowLanAccess"] ? "0.0.0.0" : "127.0.0.1";+ }+const envHost = process.env.TRILIUM_HOST;- if (envHost && !isElectron) {+ if (envHost) {return envHost;}- // `config.Network.host` resolves the standard env var, then config.ini, then- // a platform-aware default — loopback on desktop (the renderer reaches the- // server in-process via `trilium-app://`, so the listener can stay off the- // LAN as defense in depth), all interfaces on server. A user who wants LAN- // access sets `[Network] host=` in config.ini. See `configMapping.Network.host`.return config["Network"]["host"];}diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex a85bfd4029..7e11809735 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -481,6 +481,14 @@ export interface ElectronSecurityApi {/** Requests a change to the SQL console setting. Same flow as above. */setSqlConsoleEnabled(enabled: boolean): Promise<boolean>;++ /**+ * Requests enabling/disabling LAN access. When enabled, the desktop binds+ * its TCP listener to all interfaces (instead of loopback) so other devices+ * can reach it — e.g. to sync from another device. Same confirmation ++ * restart flow as above.+ */+ setLanAccessEnabled(enabled: boolean): Promise<boolean>;}/**diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex bf3bb5e4cf..3a72e9bfdd 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -472,12 +472,6 @@ export interface NetworkAddressesResponse {* actually be reached by another device.*/reachableOnNetwork: boolean;- /**- * Absolute path to this instance's `config.ini`. Only sent when the request- * is served by a Node host (server/desktop); lets the setup screen offer an- * "open config" shortcut when the host needs to be reconfigured.- */- configPath?: string;}export type ScriptParams = any[];