Skip to content

Build your personal knowledge base with Trilium Notes

refactor(sync): carry the effective sync server on the options payload

Elian Doran630e7d5e3b2b
diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx b/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx
index 3598490490..073b0b3c3b 100644
--- a/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx
+++ b/apps/client/src/widgets/launch_bar/SyncStatus.spec.tsx
@@ -1,4 +1,4 @@
-import type { SyncConfigResponse, WebSocketMessage } from "@triliumnext/commons";
+import type { WebSocketMessage } from "@triliumnext/commons";
import { Tooltip } from "bootstrap";
import { render } from "preact";
import { act } from "preact/test-utils";
@@ -7,17 +7,13 @@ 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>>(),
+ options: {} as Record<string, string>,
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" ? [] : {})
- }
+ default: { get: (url: string) => Promise.resolve(url === "keyboard-actions" ? [] : {}) }
}));
vi.mock("../../services/sync", () => ({ default: { syncNow: mocks.syncNow } }));
vi.mock("../../services/ws", () => ({
@@ -38,11 +34,14 @@ vi.mock("../../services/i18n", async () => {
});
return { t: i18n.t };
});
+// `useTriliumOptionBool` is mocked alongside `useTriliumOption` rather than left to the original:
+// it reaches for its module's own binding, which a mock of the export does not reach.
vi.mock("../react/hooks", async (importOriginal) => {
const hooks = await importOriginal<typeof import("../react/hooks")>();
return {
...hooks,
- useTriliumOption: () => [ mocks.storedHost, vi.fn() ],
+ useTriliumOption: (name: string) => [ mocks.options[name] ?? "", vi.fn() ],
+ useTriliumOptionBool: (name: string) => [ mocks.options[name] === "true", vi.fn() ],
useStaticTooltip: (...args: Parameters<typeof hooks.useStaticTooltip>) =>
hooks.useStaticTooltip(args[0], { ...args[1], animation: false })
};
@@ -54,8 +53,11 @@ import SyncStatus from "./SyncStatus";
let container: HTMLDivElement;
beforeEach(() => {
- mocks.storedHost = "https://stored.example/";
- mocks.getConfig.mockReset().mockResolvedValue({ syncServerHost: "https://effective.example/" });
+ mocks.options = {
+ syncServerHost: "https://stored.example/",
+ effectiveSyncServerHost: "https://effective.example/",
+ syncServerHostOverridden: "true"
+ };
mocks.syncNow.mockClear();
container = document.body.appendChild(document.createElement("div"));
});
@@ -65,85 +67,82 @@ afterEach(() => {
container.remove();
});
-async function mount() {
- await act(async () => {
+function mount() {
+ act(() => {
render(<SyncStatus launcherNote={{} as FNote} />, container);
});
- await act(async () => {});
}
+const icon = () => container.querySelector<HTMLElement>(".sync-status-icon");
+
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);
+ const element = icon();
+ expect(element).not.toBeNull();
+ if (!element) throw new Error("Missing sync icon");
+ const tooltip = Tooltip.getInstance(element);
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 };
+ return { element, body };
}
describe("SyncStatus", () => {
- it("shows the effective host even when the stored host is empty", async () => {
- mocks.storedHost = "";
- await mount();
- const { icon, body } = showTooltip();
+ it("names the server in use rather than the stored one, and syncs when pressed", () => {
+ mocks.options.syncServerHost = "";
+ mount();
+
+ const { element, body } = showTooltip();
expect(body.textContent).toContain("https://effective.example/");
- expect(mocks.getConfig).toHaveBeenCalledTimes(1);
- icon.click();
+ element.click();
expect(mocks.syncNow).toHaveBeenCalledTimes(1);
});
- it("keeps the host through status changes and prevents duplicate sync requests", async () => {
- await mount();
+ it("keeps the host through status changes and prevents duplicate sync requests", () => {
+ 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();
+ act(() => { mocks.onMessage?.({ type, lastSyncedPush: 0 }); });
+ const { element, body } = showTooltip();
expect(body.textContent).toContain("https://effective.example/");
- expect(body.textContent).not.toContain(mocks.storedHost);
+ expect(body.textContent).not.toContain("https://stored.example/");
if (type === "sync-pull-in-progress") {
- icon.click();
+ element.click();
expect(mocks.syncNow).not.toHaveBeenCalled();
}
}
});
- it("escapes markup in the host instead of rendering it", async () => {
+ it("escapes markup in the host instead of rendering it", () => {
const host = 'https://sync.example/<b title="test">&value</b>';
- mocks.getConfig.mockResolvedValue({ syncServerHost: host });
- await mount();
+ mocks.options.effectiveSyncServerHost = host;
+ 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("hides the button when the configuration turns sync off, whatever the stored host says", () => {
+ mocks.options.effectiveSyncServerHost = "";
+ mount();
+
+ expect(icon()).toBeNull();
});
- 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);
+ it("follows the stored host while nothing overrides it", () => {
+ mocks.options.syncServerHostOverridden = "false";
+ mocks.options.effectiveSyncServerHost = "";
+
+ mount();
+ expect(icon()).not.toBeNull();
+
+ for (const storedHost of [ "disabled", "" ]) {
+ mocks.options.syncServerHost = storedHost;
+ act(() => { render(null, container); });
+ mount();
+ expect(icon()).toBeNull();
+ }
});
});
diff --git a/apps/client/src/widgets/launch_bar/SyncStatus.tsx b/apps/client/src/widgets/launch_bar/SyncStatus.tsx
index 48ff1dcc98..9db8a861ac 100644
--- a/apps/client/src/widgets/launch_bar/SyncStatus.tsx
+++ b/apps/client/src/widgets/launch_bar/SyncStatus.tsx
@@ -1,15 +1,14 @@
import "./SyncStatus.css";
-import { SyncConfigResponse, WebSocketMessage } from "@triliumnext/commons";
+import { 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";
-import { useStaticTooltip, useTriliumOption } from "../react/hooks";
+import { useStaticTooltip, useTriliumOption, useTriliumOptionBool } from "../react/hooks";
import { launcherContextMenuHandler, LauncherNoteProps } from "./launch_bar_widgets";
type SyncState = "unknown" | "in-progress"
@@ -56,28 +55,22 @@ export default function SyncStatus({ launcherNote }: LauncherNoteProps) {
const { title, icon, hasChanges } = STATE_MAPPINGS[syncState];
const spanRef = useRef<HTMLSpanElement>(null);
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 ]);
+ const [ effectiveSyncServerHost ] = useTriliumOption("effectiveSyncServerHost");
+ const [ isSyncServerHostOverridden ] = useTriliumOptionBool("syncServerHostOverridden");
useStaticTooltip(spanRef, {
html: true,
- title: escapeQuotes(title) + (syncServerHost
- ? `<p>${t("sync_status.server", { host: syncServerHost, interpolation: { escapeValue: true } })}</p>`
+ title: escapeQuotes(title) + (effectiveSyncServerHost
+ ? `<p>${t("sync_status.server", { host: effectiveSyncServerHost, interpolation: { escapeValue: true } })}</p>`
: "")
});
- const showSyncStatus = syncServerHost !== null && (syncServerHost !== undefined
- || (storedSyncServerHost && storedSyncServerHost !== "disabled"));
+ // config.ini and environment variables hold still for the life of the process, so only the
+ // stored option can change while the app runs. Reading it directly makes the button appear as
+ // soon as sync is configured, without waiting for a reload.
+ const showSyncStatus = isSyncServerHostOverridden
+ ? !!effectiveSyncServerHost
+ : !!storedSyncServerHost && storedSyncServerHost !== "disabled";
return (showSyncStatus &&
<div
diff --git a/apps/server/src/routes/api/core_routes_http.spec.ts b/apps/server/src/routes/api/core_routes_http.spec.ts
index 21c87ae668..c57844f55d 100644
--- a/apps/server/src/routes/api/core_routes_http.spec.ts
+++ b/apps/server/src/routes/api/core_routes_http.spec.ts
@@ -1,12 +1,9 @@
-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.
@@ -16,7 +13,8 @@ import config from "../../services/config.js";
* 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.
+ * Express app end to end. (Auth-required can't be asserted here because the test
+ * fixture's config.ini sets `noAuthentication=true`.)
*/
let ctx: ApiTestContext;
@@ -34,19 +32,6 @@ 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/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index edf7a27a41..3d34700d10 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -183,6 +183,13 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
backendScriptingEnabled: boolean;
sqlConsoleEnabled: boolean;
allowLanAccess: boolean;
+ /**
+ * Sync address actually in use, with any `user:password@` removed, or empty when sync is off.
+ * Read-only: derived from config.ini / environment variables and the stored `syncServerHost`.
+ */
+ effectiveSyncServerHost: string;
+ /** Whether config.ini or an environment variable supplies the sync address. Read-only. */
+ syncServerHostOverridden: boolean;
hasUserBackendScripts: boolean;
isPasswordSet: boolean;
overrideThemeFonts: boolean;
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 68420b168f..4d39246c34 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -184,11 +184,6 @@ 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/options.spec.ts b/packages/trilium-core/src/routes/api/options.spec.ts
index 75a73c87c5..18edb0a2f8 100644
--- a/packages/trilium-core/src/routes/api/options.spec.ts
+++ b/packages/trilium-core/src/routes/api/options.spec.ts
@@ -2,6 +2,7 @@ import type { UserFont } from "@triliumnext/commons";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import * as i18n from "../../services/i18n";
+import optionService from "../../services/options";
import { getConfig, initConfig } from "../../services/config";
import { getSql } from "../../services/sql/index";
import { CoreApiTester } from "../../test/api_tester";
@@ -16,6 +17,14 @@ function getOptionValue(name: string): string | null {
return getSql().getValue<string | null>("SELECT value FROM options WHERE name = ?", [name]);
}
+/** Forces the stored `syncServerHost` option, leaving every other option reading from the fixture. */
+function mockSyncServerHost(syncServerHost: string) {
+ const originalGetOption = optionService.getOption.bind(optionService);
+ return vi.spyOn(optionService, "getOption").mockImplementation((name) =>
+ name === "syncServerHost" ? syncServerHost : originalGetOption(name)
+ );
+}
+
/** Creates a file note carrying a `#customFont` label and returns its note ID. */
async function createFontNote(title: string): Promise<string> {
const created = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {
@@ -96,6 +105,81 @@ describe("Options API (core)", () => {
}
});
+ describe("the effective sync server", () => {
+ it("reports the normalized stored host, with credentials removed", async () => {
+ mockSyncServerHost(" https://user:[email protected]//path/ ");
+
+ const res = await api.get<Record<string, string>>("/api/options");
+ expect(res.body.effectiveSyncServerHost).toBe("https://sync.example.com/path");
+ expect(res.body.syncServerHostOverridden).toBe("false");
+ });
+
+ it("removes credentials from malformed and schemeless hosts, keeping the rest for diagnostics", async () => {
+ const malformed = mockSyncServerHost("https://user:secret@host:99999");
+ expect((await api.get<Record<string, string>>("/api/options")).body.effectiveSyncServerHost)
+ .toBe("https://host:99999");
+
+ malformed.mockRestore();
+ const schemeless = mockSyncServerHost("user:[email protected]");
+ expect((await api.get<Record<string, string>>("/api/options")).body.effectiveSyncServerHost)
+ .toBe("sync.example.com");
+
+ schemeless.mockRestore();
+ mockSyncServerHost("not a URL");
+ expect((await api.get<Record<string, string>>("/api/options")).body.effectiveSyncServerHost)
+ .toBe("not a URL");
+ });
+
+ it("keeps at signs that are not URL credentials", async () => {
+ mockSyncServerHost("https://sync.example.com/path@[email protected]");
+
+ const res = await api.get<Record<string, string>>("/api/options");
+ expect(res.body.effectiveSyncServerHost)
+ .toBe("https://sync.example.com/path@[email protected]");
+ });
+
+ it("is empty when no host is configured", async () => {
+ const emptyHost = mockSyncServerHost("");
+ expect((await api.get<Record<string, string>>("/api/options")).body.effectiveSyncServerHost).toBe("");
+
+ emptyHost.mockRestore();
+ mockSyncServerHost(" ");
+ expect((await api.get<Record<string, string>>("/api/options")).body.effectiveSyncServerHost).toBe("");
+ });
+
+ it("prefers the config override over a stale or empty stored host, and flags it", async () => {
+ const original = getConfig();
+ initConfig({ ...original, Sync: { ...original.Sync, syncServerHost: "https://override.example.com/" } });
+ try {
+ const stale = mockSyncServerHost("https://stored.example.com");
+ const overridden = await api.get<Record<string, string>>("/api/options");
+ expect(overridden.body.effectiveSyncServerHost).toBe("https://override.example.com");
+ expect(overridden.body.syncServerHostOverridden).toBe("true");
+
+ stale.mockRestore();
+ mockSyncServerHost("");
+ expect((await api.get<Record<string, string>>("/api/options")).body.effectiveSyncServerHost)
+ .toBe("https://override.example.com");
+ } finally {
+ initConfig(original);
+ }
+ });
+
+ it("is empty but still flagged when the config override disables sync", async () => {
+ const original = getConfig();
+ initConfig({ ...original, Sync: { ...original.Sync, syncServerHost: "disabled" } });
+ try {
+ mockSyncServerHost("https://stored.example.com");
+
+ const res = await api.get<Record<string, string>>("/api/options");
+ expect(res.body.effectiveSyncServerHost).toBe("");
+ expect(res.body.syncServerHostOverridden).toBe("true");
+ } finally {
+ initConfig(original);
+ }
+ });
+ });
+
it("flags backend scripts, ignoring #run labels on frontend scripts", async () => {
expect((await api.get<Record<string, string>>("/api/options")).body.hasUserBackendScripts).toBe("false");
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 3630bf9841..5bd2815c3b 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -10,6 +10,7 @@ import { getLog } from "../../services/log.js";
import optionService from "../../services/options.js";
import searchService from "../../services/search/services/search.js";
import { getSql } from "../../services/sql/index.js";
+import syncOptions from "../../services/sync_options.js";
import { ValidationError } from "../../errors.js";
interface UserTheme {
@@ -193,6 +194,11 @@ function getOptions() {
resultMap["sqlConsoleEnabled"] = config.Security.sqlConsoleEnabled ? "true" : "false";
// Desktop LAN-access override (read-only; toggled via the Electron security bridge)
resultMap["allowLanAccess"] = config.Security.allowLanAccess ? "true" : "false";
+ // Expose the sync address actually in use (read-only), which config.ini / env vars can override
+ // so that a development copy of a live document does not push to the live sync server.
+ const syncServerHost = syncOptions.isSyncSetup() ? syncOptions.getSyncServerHost() : null;
+ resultMap["effectiveSyncServerHost"] = syncServerHost ? stripSyncCredentials(syncServerHost) : "";
+ resultMap["syncServerHostOverridden"] = config.Sync.syncServerHost ? "true" : "false";
// Detect if the user has any backend scripts with #run labels (backendStartup, hourly, daily).
// Filter by MIME type since #run can also appear on frontend scripts.
@@ -312,6 +318,11 @@ function isReadable(name: string) {
|| name.startsWith("hideArchivedNotes");
}
+/** Removes any `user:password@` from a sync address, so it can be shown in the UI. */
+function stripSyncCredentials(host: string) {
+ return host.replace(/^((?:[a-z][a-z\d+.-]*:)?\/\/)?[^/?#]*@/i, "$1");
+}
+
/** Check if an option can be written by the client (PUT requests). */
function isAllowed(name: string) {
return isReadable(name)
diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.ts
index 6ab64a69aa..83a93cebbf 100644
--- a/packages/trilium-core/src/routes/api/sync.spec.ts
+++ b/packages/trilium-core/src/routes/api/sync.spec.ts
@@ -1,7 +1,6 @@
-import type { EntityChange, SyncConfigResponse } from "@triliumnext/commons";
+import type { EntityChange } from "@triliumnext/commons";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
-import { getConfig, initConfig } from "../../services/config";
import consistencyChecksService from "../../services/consistency_checks";
import entityChangesService from "../../services/entity_changes";
import optionService from "../../services/options";
@@ -20,13 +19,6 @@ 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();
@@ -68,102 +60,6 @@ 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.ts
index c0f73892fd..caece8876d 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, type SyncConfigResponse, SyncTestResponse } from "@triliumnext/commons";
+import { type EntityChange, type EntityChangeRecord, SyncTestResponse } from "@triliumnext/commons";
import type { Request } from "express";
import { t } from "i18next";
@@ -38,29 +38,6 @@ 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
@@ -411,7 +388,6 @@ 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.ts
index 1c8705a22f..2a1df91547 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -218,7 +218,6 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
asyncRouteWithoutTransaction(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);