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
feat(setup): warn and block sync-from-desktop when host is unreachable
Elian Doran038a12f789ca
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex 890f190de8..2149fb9086 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -1,6 +1,6 @@import "./setup.css";-import { LOCALES, SetupSyncFromServerResponse } from "@triliumnext/commons";+import { LOCALES, NetworkAddressesResponse, SetupSyncFromServerResponse } from "@triliumnext/commons";import clsx from "clsx";import { ComponentChildren, render } from "preact";import { useEffect, useMemo, useRef, useState } from "preact/hooks";@@ -410,13 +410,22 @@ function SyncFromServer({ setState }: { setState: (state: State) => void }) {}function SyncFromDesktop({ setState }: { setState: (state: State) => void }) {- const [ networkAddresses, setNetworkAddresses ] = useState<string[]>([]);+ const [ networkInfo, setNetworkInfo ] = useState<NetworkAddressesResponse | null>(null);useEffect(() => {- getNetworkAddresses().then(setNetworkAddresses);+ getNetworkAddresses().then(setNetworkInfo);}, []);+ // Don't wait for an incoming connection that can't arrive: when the host is+ // only bound to loopback the advertised addresses are unreachable, so the+ // other device will never connect. Hold off polling until reachability is+ // confirmed.+ const reachable = networkInfo?.reachableOnNetwork ?? false;+useEffect(() => {+ if (!reachable) {+ return;+ }const interval = setInterval(async () => {const status = await server.get<{ schemaExists: boolean }>("setup/status");if (status.schemaExists) {@@ -424,7 +433,7 @@ function SyncFromDesktop({ setState }: { setState: (state: State) => void }) {}}, 1000);return () => clearInterval(interval);- }, [setState]);+ }, [setState, reachable]);return (<SetupPage@@ -433,28 +442,37 @@ function SyncFromDesktop({ setState }: { setState: (state: State) => void }) {illustration={<SyncIllustration targetDevice="desktop" />}onBack={() => setState("firstOptions")}>- <div class="card-columns">- <Card heading="On the other device">- <CardSection>1. {t("setup.sync-from-desktop-step1")}</CardSection>- <CardSection>2. {t("setup.sync-from-desktop-step2")}</CardSection>- <CardSection>3. {t("setup.sync-from-desktop-step3")}</CardSection>- <CardSection>4. {t("setup.sync-from-desktop-step4")}</CardSection>- <CardSection>5. {t("setup.sync-from-desktop-step5")}</CardSection>- </Card>-- {networkAddresses.length > 0 && (- <Card heading={t("setup.your-ip-addresses")} className="ip-addresses">- {networkAddresses.map((addr) => (- <CardSection key={addr}>{addr}</CardSection>- ))}- </Card>- )}- </div>+ {networkInfo && !networkInfo.reachableOnNetwork ? (+ <Admonition type="caution" className="sync-from-desktop-unreachable">+ <strong>{t("setup.sync-from-desktop-unreachable-title")}</strong>+ <p>{t("setup.sync-from-desktop-unreachable-description")}</p>+ </Admonition>+ ) : (+ <>+ <div class="card-columns">+ <Card heading="On the other device">+ <CardSection>1. {t("setup.sync-from-desktop-step1")}</CardSection>+ <CardSection>2. {t("setup.sync-from-desktop-step2")}</CardSection>+ <CardSection>3. {t("setup.sync-from-desktop-step3")}</CardSection>+ <CardSection>4. {t("setup.sync-from-desktop-step4")}</CardSection>+ <CardSection>5. {t("setup.sync-from-desktop-step5")}</CardSection>+ </Card>++ {networkInfo && networkInfo.addresses.length > 0 && (+ <Card heading={t("setup.your-ip-addresses")} className="ip-addresses">+ {networkInfo.addresses.map((addr) => (+ <CardSection key={addr}>{addr}</CardSection>+ ))}+ </Card>+ )}+ </div>- <div class="sync-from-desktop-waiting">- <div class="main"><Icon icon="bx bx-loader-circle bx-spin" />{" "} {t("setup.sync-from-desktop-waiting")}</div>- <div class="subtle">{t("setup.sync-from-desktop-warning")}</div>- </div>+ <div class="sync-from-desktop-waiting">+ <div class="main"><Icon icon="bx bx-loader-circle bx-spin" />{" "} {t("setup.sync-from-desktop-waiting")}</div>+ <div class="subtle">{t("setup.sync-from-desktop-warning")}</div>+ </div>+ </>+ )}</SetupPage>);}@@ -545,18 +563,20 @@ function SetupPage({ title, description, className, illustration, children, foot);}-async function getNetworkAddresses(): Promise<string[]> {+async function getNetworkAddresses(): Promise<NetworkAddressesResponse> {if (!isElectron()) {- return [`${location.protocol}//${location.host}`];+ // The browser already reached this server over the network, so the+ // address it's using is reachable by definition.+ return { addresses: [`${location.protocol}//${location.host}`], reachableOnNetwork: true };}// Node's `os` module isn't available in the renderer (node integration is// disabled), and the desktop renderer's `location` points at the internal// `trilium-app://` protocol rather than the real HTTP listener. So the// server enumerates its interfaces and builds the reachable URLs (correct- // protocol and port included).- const { addresses } = await server.get<{ addresses: string[] }>("network-addresses");- return addresses;+ // protocol and port included), and reports whether it's actually bound to a+ // network-reachable interface.+ return await server.get<NetworkAddressesResponse>("network-addresses");}function onSetupFinished() {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 320e365e83..1d48b76c3e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2789,6 +2789,8 @@"sync-from-desktop-step5": "Click the \"Test sync\" button to verify connection is successful.","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": "Trilium is only listening on localhost, so another device can't connect to it. Set \"host=0.0.0.0\" under the [Network] section of your config.ini, restart Trilium, and try again.","advanced-options": "Advanced options","sync-failed": "Failed to sync: {{message}}","server-host": "Trilium server address",diff --git a/apps/server/src/routes/api/system_info.spec.ts b/apps/server/src/routes/api/system_info.spec.tsindex 909e75476c..ac51925072 100644--- a/apps/server/src/routes/api/system_info.spec.ts+++ b/apps/server/src/routes/api/system_info.spec.ts@@ -28,7 +28,7 @@ vi.mock("os", () => ({networkInterfaces: () => ({})}));-import systemInfoRoute, { buildNetworkUrl, collectNetworkAddresses, isCpuArchMismatch } from "./system_info.js";+import systemInfoRoute, { buildNetworkUrl, collectNetworkAddresses, isCpuArchMismatch, isHostReachableOnNetwork } from "./system_info.js";type NetworkInterfaces = Parameters<typeof collectNetworkAddresses>[0];@@ -103,4 +103,20 @@ describe("System info API", () => {expect(buildNetworkUrl("http", "fd00::1", 37840)).toBe("http://[fd00::1]:37840");});});++ describe("isHostReachableOnNetwork", () => {+ it("treats loopback bindings as unreachable", () => {+ expect(isHostReachableOnNetwork("127.0.0.1")).toBe(false);+ expect(isHostReachableOnNetwork("127.1.2.3")).toBe(false);+ expect(isHostReachableOnNetwork("localhost")).toBe(false);+ expect(isHostReachableOnNetwork("::1")).toBe(false);+ expect(isHostReachableOnNetwork(" LOCALHOST ")).toBe(false);+ });++ it("treats wildcard and specific interfaces as reachable", () => {+ expect(isHostReachableOnNetwork("0.0.0.0")).toBe(true);+ expect(isHostReachableOnNetwork("::")).toBe(true);+ expect(isHostReachableOnNetwork("192.168.1.20")).toBe(true);+ });+ });});diff --git a/apps/server/src/routes/api/system_info.ts b/apps/server/src/routes/api/system_info.tsindex eff0a304fe..e2648b1c14 100644--- a/apps/server/src/routes/api/system_info.ts+++ b/apps/server/src/routes/api/system_info.ts@@ -1,8 +1,11 @@+import type { NetworkAddressesResponse } from "@triliumnext/commons";import { execSync } from "child_process";-import { isMac, isWindows } from "../../services/utils";import { arch, cpus, networkInterfaces } from "os";+import config from "../../services/config.js";+import host from "../../services/host.js";import port from "../../services/port.js";+import { isMac, isWindows } from "../../services/utils";function systemChecks() {return {@@ -18,11 +21,12 @@ function systemChecks() {* `location` points at the internal `trilium-app://` protocol rather than the* real HTTP listener — so the protocol and port must be resolved here too.*/-function getNetworkAddresses() {+function getNetworkAddresses(): NetworkAddressesResponse {const protocol = config["Network"]["https"] ? "https" : "http";return {- addresses: collectNetworkAddresses(networkInterfaces()).map((addr) => buildNetworkUrl(protocol, addr, port))+ addresses: collectNetworkAddresses(networkInterfaces()).map((addr) => buildNetworkUrl(protocol, addr, port)),+ reachableOnNetwork: isHostReachableOnNetwork(host)};}@@ -98,6 +102,17 @@ export function buildNetworkUrl(protocol: string, address: string, port: number)return `${protocol}://${host}:${port}`;}+/**+ * Whether the configured listening host is reachable from other devices.+ * Returns `false` for loopback-only bindings (the Electron desktop default),+ * where the advertised LAN addresses can't actually be connected to. Pure and+ * exported for unit testing.+ */+export function isHostReachableOnNetwork(host: string): boolean {+ const normalized = host.trim().toLowerCase();+ return normalized !== "localhost" && normalized !== "::1" && !normalized.startsWith("127.");+}+export default {systemChecks,getNetworkAddressesdiff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex cd518f0757..3a72e9bfdd 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -463,4 +463,15 @@ export type SetupSyncFromServerResponse = {error: string;}+export interface NetworkAddressesResponse {+ /** Reachable URLs (protocol + host + port) other devices can sync with. */+ addresses: string[];+ /**+ * Whether this host is bound to a network-reachable interface. `false` when+ * it only listens on loopback, in which case the advertised addresses can't+ * actually be reached by another device.+ */+ reachableOnNetwork: boolean;+}+export type ScriptParams = any[];