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(sync): show effective server in status tooltip
matt wilkiefe79ed1d59a6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 5a3ec68ac3..ac0f3c3f35 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1117,7 +1117,8 @@"connected_no_changes": "<p>Connected to the sync server.<br>All changes have been already synced.</p><p>Click to trigger sync.</p>","disconnected_with_changes": "<p>Establishing the connection to the sync server was unsuccessful.<br>There are some outstanding changes yet to be synced.</p><p>Click to trigger sync.</p>","disconnected_no_changes": "<p>Establishing the connection to the sync server was unsuccessful.<br>All known changes have been synced.</p><p>Click to trigger sync.</p>",- "in_progress": "Sync with the server is in progress."+ "in_progress": "Sync with the server is in progress.",+ "server": "Sync server: {{host}}"},"left_pane_toggle": {"show_panel": "Show panel",diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx b/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsxnew file mode 100644index 0000000000..3598490490--- /dev/null+++ b/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx@@ -0,0 +1,149 @@+import type { SyncConfigResponse, WebSocketMessage } from "@triliumnext/commons";+import { Tooltip } from "bootstrap";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../entities/fnote";++const mocks = vi.hoisted(() => ({+ storedHost: "https://stored.example/",+ getConfig: vi.fn<() => Promise<SyncConfigResponse>>(),+ syncNow: vi.fn(),+ onMessage: undefined as ((message: WebSocketMessage) => void) | undefined+}));++vi.mock("../../services/server", () => ({+ default: {+ get: (url: string) => url === "sync/config" ? mocks.getConfig()+ : Promise.resolve(url === "keyboard-actions" ? [] : {})+ }+}));+vi.mock("../../services/sync", () => ({ default: { syncNow: mocks.syncNow } }));+vi.mock("../../services/ws", () => ({+ default: { getMaxKnownEntityChangeSyncId: () => 0, subscribeToMessages: () => {} },+ subscribeToMessages: (callback: (message: WebSocketMessage) => void) => {+ mocks.onMessage = callback;+ },+ unsubscribeToMessage: () => { mocks.onMessage = undefined; }+}));+vi.mock("../../services/i18n", async () => {+ const { createInstance } = await import("i18next");+ const translations = await import("../../translations/en/translation.json");+ const i18n = createInstance();+ await i18n.init({+ lng: "en",+ interpolation: { escapeValue: false },+ resources: { en: { translation: translations.default } }+ });+ return { t: i18n.t };+});+vi.mock("../react/hooks", async (importOriginal) => {+ const hooks = await importOriginal<typeof import("../react/hooks")>();+ return {+ ...hooks,+ useTriliumOption: () => [ mocks.storedHost, vi.fn() ],+ useStaticTooltip: (...args: Parameters<typeof hooks.useStaticTooltip>) =>+ hooks.useStaticTooltip(args[0], { ...args[1], animation: false })+ };+});+vi.mock("./launch_bar_widgets", () => ({ launcherContextMenuHandler: () => undefined }));++import SyncStatus from "./SyncStatus";++let container: HTMLDivElement;++beforeEach(() => {+ mocks.storedHost = "https://stored.example/";+ mocks.getConfig.mockReset().mockResolvedValue({ syncServerHost: "https://effective.example/" });+ mocks.syncNow.mockClear();+ container = document.body.appendChild(document.createElement("div"));+});++afterEach(() => {+ act(() => { render(null, container); });+ container.remove();+});++async function mount() {+ await act(async () => {+ render(<SyncStatus launcherNote={{} as FNote} />, container);+ });+ await act(async () => {});+}++function showTooltip() {+ const icon = container.querySelector<HTMLElement>(".sync-status-icon");+ expect(icon).not.toBeNull();+ if (!icon) throw new Error("Missing sync icon");+ const tooltip = Tooltip.getInstance(icon);+ expect(tooltip).not.toBeNull();+ tooltip?.show();+ const body = document.querySelector<HTMLElement>(".tooltip-inner");+ expect(body).not.toBeNull();+ if (!body) throw new Error("Missing tooltip");+ return { icon, body };+}++describe("SyncStatus", () => {+ it("shows the effective host even when the stored host is empty", async () => {+ mocks.storedHost = "";+ await mount();+ const { icon, body } = showTooltip();+ expect(body.textContent).toContain("https://effective.example/");+ expect(mocks.getConfig).toHaveBeenCalledTimes(1);+ icon.click();+ expect(mocks.syncNow).toHaveBeenCalledTimes(1);+ });++ it("keeps the host through status changes and prevents duplicate sync requests", async () => {+ await mount();+ for (const type of [ "sync-finished", "sync-failed", "sync-pull-in-progress" ] as const) {+ await act(async () => { mocks.onMessage?.({ type, lastSyncedPush: 0 }); });+ const { icon, body } = showTooltip();+ expect(body.textContent).toContain("https://effective.example/");+ expect(body.textContent).not.toContain(mocks.storedHost);+ if (type === "sync-pull-in-progress") {+ icon.click();+ expect(mocks.syncNow).not.toHaveBeenCalled();+ }+ }+ });++ it("escapes markup in the host instead of rendering it", async () => {+ const host = 'https://sync.example/<b title="test">&value</b>';+ mocks.getConfig.mockResolvedValue({ syncServerHost: host });+ await mount();+ const { body } = showTooltip();+ expect(body.textContent).toContain(host);+ expect(body.querySelector("b")).toBeNull();+ });++ it("hides disabled sync but keeps the button available after a config read fails", async () => {+ mocks.getConfig.mockResolvedValue({ syncServerHost: null });+ await mount();+ expect(container.querySelector(".sync-status-icon")).toBeNull();+ mocks.storedHost = "https://changed.example/";+ mocks.getConfig.mockRejectedValue(new Error("Unavailable"));+ await mount();+ const { icon, body } = showTooltip();+ expect(body.textContent).not.toContain(mocks.storedHost);+ icon.click();+ expect(mocks.syncNow).toHaveBeenCalledTimes(1);+ });++ it("refreshes after a host change and ignores stale responses", async () => {+ let resolveFirst: ((value: SyncConfigResponse) => void) | undefined;+ mocks.getConfig.mockReturnValueOnce(new Promise(resolve => { resolveFirst = resolve; }));+ await mount();+ mocks.storedHost = "https://new.example/";+ mocks.getConfig.mockResolvedValue({ syncServerHost: "https://new.example/" });+ await mount();+ expect(showTooltip().body.textContent).toContain("https://new.example/");+ await act(async () => { resolveFirst?.({ syncServerHost: "https://old.example/" }); });+ const { body } = showTooltip();+ expect(body.textContent).toContain("https://new.example/");+ expect(body.textContent).not.toContain("https://old.example/");+ expect(mocks.getConfig).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.tsx b/apps/client/src/widgets/launch_bar/SyncStatus.tsxindex 27678df17b..48ff1dcc98 100644--- a/apps/client/src/widgets/launch_bar/SyncStatus.tsx+++ b/apps/client/src/widgets/launch_bar/SyncStatus.tsx@@ -1,10 +1,11 @@import "./SyncStatus.css";-import { WebSocketMessage } from "@triliumnext/commons";+import { SyncConfigResponse, WebSocketMessage } from "@triliumnext/commons";import clsx from "clsx";import { useEffect, useRef, useState } from "preact/hooks";import { t } from "../../services/i18n";+import server from "../../services/server";import sync from "../../services/sync";import { escapeQuotes } from "../../services/utils";import ws, { subscribeToMessages, unsubscribeToMessage } from "../../services/ws";@@ -54,13 +55,31 @@ export default function SyncStatus({ launcherNote }: LauncherNoteProps) {const syncState = useSyncStatus();const { title, icon, hasChanges } = STATE_MAPPINGS[syncState];const spanRef = useRef<HTMLSpanElement>(null);- const [ syncServerHost ] = useTriliumOption("syncServerHost");+ const [ storedSyncServerHost ] = useTriliumOption("syncServerHost");+ const [ syncServerHost, setSyncServerHost ] = useState<string | null>();++ useEffect(() => {+ let cancelled = false;+ setSyncServerHost(undefined);+ server.get<SyncConfigResponse>("sync/config").then(config => {+ if (!cancelled) setSyncServerHost(config.syncServerHost);+ }).catch(() => {+ if (!cancelled) setSyncServerHost(undefined);+ });+ return () => { cancelled = true; };+ }, [ storedSyncServerHost ]);+useStaticTooltip(spanRef, {html: true,- title: escapeQuotes(title)+ title: escapeQuotes(title) + (syncServerHost+ ? `<p>${t("sync_status.server", { host: syncServerHost, interpolation: { escapeValue: true } })}</p>`+ : "")});- return (syncServerHost &&+ const showSyncStatus = syncServerHost !== null && (syncServerHost !== undefined+ || (storedSyncServerHost && storedSyncServerHost !== "disabled"));++ return (showSyncStatus &&<divclass="sync-status-widget launcher-button"onContextMenu={launcherContextMenuHandler(launcherNote)}diff --git a/apps/server/src/routes/api/core_routes_http.spec.ts b/apps/server/src/routes/api/core_routes_http.spec.tsindex c57844f55d..21c87ae668 100644--- a/apps/server/src/routes/api/core_routes_http.spec.ts+++ b/apps/server/src/routes/api/core_routes_http.spec.ts@@ -1,9 +1,12 @@+import supertest from "supertest";import { beforeAll, describe, expect, it } from "vitest";import {type ApiTestContext,bootLoggedInApp,createTextNote } from "../../../spec/support/internal_api.js";+import { refreshAuth } from "../../services/auth.js";+import config from "../../services/config.js";/*** Thin Express-transport layer for the shared **core** API routes.@@ -13,8 +16,7 @@ import {* This spec only asserts the things that exist *because of Express* and the* server middleware — and therefore can't be exercised by the in-process core* driver: CSRF enforcement, and that core routes are actually wired into the- * Express app end to end. (Auth-required can't be asserted here because the test- * fixture's config.ini sets `noAuthentication=true`.)+ * Express app end to end.*/let ctx: ApiTestContext;@@ -32,6 +34,19 @@ describe("Core routes over Express", () => {expect(res.body.notes.some((n: { noteId: string }) => n.noteId === "root")).toBe(true);});+ it("requires authentication to read the effective sync server", async () => {+ const original = config.General.noAuthentication;+ config.General.noAuthentication = false;+ refreshAuth();+ try {+ await supertest(ctx.app).get("/api/sync/config").expect(401);+ await ctx.agent.get("/api/sync/config").expect(200);+ } finally {+ config.General.noAuthentication = original;+ refreshAuth();+ }+ });+it("runs a core mutating route end to end with a CSRF token", async () => {const { noteId } = await createTextNote(ctx, { title: "Via Express" });const res = await ctx.agent.get(`/api/notes/${noteId}`).expect(200);diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 4d39246c34..68420b168f 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -184,6 +184,11 @@ export interface ExistingAnonymizedDatabasesResponse {export type SyncTestResponse = Response;+export interface SyncConfigResponse {+ /** Effective sync server URL without embedded credentials, or null when not configured. */+ syncServerHost: string | null;+}+export interface EtapiToken {name: string;utcDateCreated: string;diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.tsindex 83a93cebbf..00be0e2b5a 100644--- a/packages/trilium-core/src/routes/api/sync.spec.ts+++ b/packages/trilium-core/src/routes/api/sync.spec.ts@@ -1,7 +1,8 @@-import type { EntityChange } from "@triliumnext/commons";+import type { EntityChange, SyncConfigResponse } from "@triliumnext/commons";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import consistencyChecksService from "../../services/consistency_checks";+import { getConfig, initConfig } from "../../services/config";import entityChangesService from "../../services/entity_changes";import optionService from "../../services/options";import { getSql } from "../../services/sql/index";@@ -19,6 +20,13 @@ import { CoreApiTester } from "../../test/api_tester";*/let api: CoreApiTester;+function mockSyncServerHost(syncServerHost: string) {+ const originalGetOption = optionService.getOption.bind(optionService);+ return vi.spyOn(optionService, "getOption").mockImplementation((name) =>+ name === "syncServerHost" ? syncServerHost : originalGetOption(name)+ );+}+describe("Sync API (core)", () => {beforeAll(() => {api = CoreApiTester.build();@@ -60,6 +68,102 @@ describe("Sync API (core)", () => {});});+ describe("getConfig (GET /api/sync/config)", () => {+ it("returns the normalized persisted sync host", async () => {+ mockSyncServerHost(" https://sync.example.com//path/ ");++ const res = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ syncServerHost: "https://sync.example.com/path" });+ });++ it("removes credentials from the displayed sync host", async () => {+ mockSyncServerHost("https://user:[email protected]//path/");++ const res = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ syncServerHost: "https://sync.example.com/path" });+ });++ it("keeps malformed sync host text for diagnostics", async () => {+ mockSyncServerHost("not a URL");++ const res = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ syncServerHost: "not a URL" });+ });++ it("removes credentials from malformed or schemeless hosts", async () => {+ const malformed = mockSyncServerHost("https://user:secret@host:99999");++ const invalidUrl = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(invalidUrl.status).toBe(200);+ expect(invalidUrl.body).toEqual({ syncServerHost: "https://host:99999" });++ malformed.mockRestore();+ mockSyncServerHost("user:[email protected]");+ const schemeless = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(schemeless.status).toBe(200);+ expect(schemeless.body).toEqual({ syncServerHost: "sync.example.com" });+ });++ it("preserves at signs outside URL credentials", async () => {+ mockSyncServerHost("https://sync.example.com/path@[email protected]");++ const res = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ syncServerHost: "https://sync.example.com/path@[email protected]" });+ });++ it("uses the config override when the persisted host is stale or empty", async () => {+ const original = getConfig();+ initConfig({ ...original, Sync: { ...original.Sync, syncServerHost: "https://override.example.com/" } });+ try {+ const persistedHost = mockSyncServerHost("https://stale.example.com");++ const stale = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(stale.status).toBe(200);+ expect(stale.body).toEqual({ syncServerHost: "https://override.example.com" });++ persistedHost.mockRestore();+ mockSyncServerHost("");+ const empty = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(empty.status).toBe(200);+ expect(empty.body).toEqual({ syncServerHost: "https://override.example.com" });+ } finally {+ initConfig(original);+ }+ });++ it("returns null for a disabled config override", async () => {+ const original = getConfig();+ initConfig({ ...original, Sync: { ...original.Sync, syncServerHost: "disabled" } });+ try {+ mockSyncServerHost("https://persisted.example.com");++ const res = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ syncServerHost: null });+ } finally {+ initConfig(original);+ }+ });++ it("returns null when the configured host is empty or whitespace", async () => {+ const emptyHost = mockSyncServerHost("");++ const empty = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(empty.status).toBe(200);+ expect(empty.body).toEqual({ syncServerHost: null });++ emptyHost.mockRestore();+ mockSyncServerHost(" ");+ const whitespace = await api.get<SyncConfigResponse>("/api/sync/config");+ expect(whitespace.status).toBe(200);+ expect(whitespace.body).toEqual({ syncServerHost: null });+ });+ });+describe("getStats (GET /api/sync/stats)", () => {it("returns sync stats in the normal case", async () => {vi.spyOn(syncService, "getOutstandingPullCount").mockReturnValue(3);diff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.tsindex caece8876d..c0f73892fd 100644--- a/packages/trilium-core/src/routes/api/sync.ts+++ b/packages/trilium-core/src/routes/api/sync.ts@@ -1,4 +1,4 @@-import { type EntityChange, type EntityChangeRecord, SyncTestResponse } from "@triliumnext/commons";+import { type EntityChange, type EntityChangeRecord, type SyncConfigResponse, SyncTestResponse } from "@triliumnext/commons";import type { Request } from "express";import { t } from "i18next";@@ -38,6 +38,29 @@ async function testSync(): Promise<SyncTestResponse> {}}+function getConfig(): SyncConfigResponse {+ const host = syncOptions.isSyncSetup() ? syncOptions.getSyncServerHost() : null;++ if (!host) {+ return { syncServerHost: null };+ }++ try {+ const url = new URL(host);+ if (url.username || url.password) {+ url.username = "";+ url.password = "";+ return { syncServerHost: utils.normalizeUrl(url.toString()) || null };+ }+ } catch {+ // Preserve invalid addresses for diagnostics while removing embedded credentials below.+ }++ return {+ syncServerHost: host.replace(/^((?:[a-z][a-z\d+.-]*:)?\/\/)?[^/?#]*@/i, "$1") || null+ };+}+function getStats() {if (!sqlInit.schemaExists()) {// fail silently but prevent errors from not existing options table@@ -388,6 +411,7 @@ function checkEntityChanges() {export default {testSync,+ getConfig,checkSync,syncNow,fillEntityChanges,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 37cac188b8..4b3e321a54 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -218,6 +218,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransasyncRouteWithoutTransaction(PST, "/api/setup/existing/keep", [checkAppNotInitialized, checkSetupAuth], setupApiRoute.keepExisting, apiResultHandler);asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);+ apiRoute(GET, "/api/sync/config", syncApiRoute.getConfig);asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);apiRoute(PST, "/api/sync/force-full-sync", syncApiRoute.forceFullSync);