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
fix(sync): don't seed a synced option when setting up from a sync server, closes #10626
Elian Doran7da0c8ef006f
diff --git a/packages/trilium-core/src/services/options_init.spec.ts b/packages/trilium-core/src/services/options_init.spec.tsindex d4e888670d..7a541680eb 100644--- a/packages/trilium-core/src/services/options_init.spec.ts+++ b/packages/trilium-core/src/services/options_init.spec.ts@@ -1,5 +1,8 @@-import { describe, expect, it } from "vitest";-import { getDefaultOptionSyncedFlag, migrateSyncTimeoutFromMilliseconds } from "./options_init.js";+import type { OptionDefinitions, OptionNames } from "@triliumnext/commons";+import { afterEach, describe, expect, it, vi } from "vitest";++import optionService from "./options.js";+import { getDefaultOptionSyncedFlag, initNotSyncedOptions, migrateSyncTimeoutFromMilliseconds } from "./options_init.js";describe("migrateSyncTimeoutFromMilliseconds", () => {it("returns null when no migration is needed (values < 1000 are already in seconds)", () => {@@ -26,6 +29,47 @@ describe("migrateSyncTimeoutFromMilliseconds", () => {});});+describe("initNotSyncedOptions", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ /**+ * Setting up an instance against a sync server goes through `sql_init#createDatabaseForSync`,+ * which calls this function on an empty database *before* the first pull. Every option created+ * here is therefore stamped with the current time, so a synced one beats the server's older+ * value in the purely timestamp-based conflict resolution of `sync_update#updateNormalEntity`+ * and is then pushed to every instance in the cluster: setting up one fresh client silently+ * resets a setting for all of them (#10626).+ *+ * Deliberately asserted over the whole set rather than for one known option, so that any future+ * synced option added to the sync-setup path is caught here.+ */+ it("creates no synced option, since it also runs when the database is created for sync", async () => {+ const created = captureCreatedOptions();++ await initNotSyncedOptions(false, {});++ expect(created.filter(({ isSynced }) => isSynced)).toEqual([]);+ });++ /**+ * An option created here as local-only while {@link defaultOptions} declares it synced (or vice+ * versa) produces a row whose sync flag depends on which code path created the database, which+ * in turn makes the sync content hash unreconcilable across instances.+ */+ it("uses the same sync flag as the default options table for the options it shares with it", async () => {+ const created = captureCreatedOptions();++ await initNotSyncedOptions(true, {});++ const mismatched = created+ .map(({ name, isSynced }) => ({ name, isSynced, declared: getDefaultOptionSyncedFlag(name) }))+ .filter(({ isSynced, declared }) => declared !== undefined && declared !== isSynced);+ expect(mismatched).toEqual([]);+ });+});+describe("getDefaultOptionSyncedFlag", () => {it("returns true for an option declared as synced", () => {expect(getDefaultOptionSyncedFlag("seenCallToActions")).toBe(true);@@ -43,3 +87,26 @@ describe("getDefaultOptionSyncedFlag", () => {expect(getDefaultOptionSyncedFlag("doesNotExistOption" as never)).toBeUndefined();});});++interface CreatedOption {+ name: OptionNames;+ value: string;+ isSynced: boolean;+}++/**+ * Replaces `optionService.createOption` with a recorder, so that the option initialization can be+ * inspected without a database (and without the entity changes that creating one would produce).+ * Restored by the `afterEach` of the calling suite.+ */+function captureCreatedOptions(): CreatedOption[] {+ const created: CreatedOption[] = [];++ vi.spyOn(optionService, "createOption").mockImplementation(+ <T extends OptionNames>(name: T, value: string | OptionDefinitions[T], isSynced: boolean) => {+ created.push({ name, value: String(value), isSynced });+ }+ );++ return created;+}diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 402fdf7689..3bf9bbfafe 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -1,4 +1,4 @@-import { type KeyboardShortcutWithRequiredActionName, type OptionMap, type OptionNames, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";+import { type KeyboardShortcutWithRequiredActionName, type OptionDefinitions, type OptionMap, type OptionNames, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";import appInfo from "./app_info.js";import { getPlatform } from "./platform.js";@@ -39,41 +39,71 @@ interface DefaultOption {/*** Initializes the default options for new databases only.*+ * Every option registered here is local-only (hence the name), which is what makes it safe to run on+ * both paths that create a database: a brand-new document, and the empty shell that+ * `sql_init#createDatabaseForSync` fills by syncing an existing document into it. Defaults that must+ * be synced belong in {@link initNewDocumentOptions} instead — see the warning there.+ ** @param initialized `true` if the database has been fully initialized (i.e. a new database was created), or `false` if the database is created for sync.* @param opts additional options to be initialized, for example the sync configuration.*/export async function initNotSyncedOptions(initialized: boolean, opts: NotSyncedOpts = {}) {- optionService.createOption(+ createNotSyncedOption("openNoteContexts",JSON.stringify([{notePath: "root",active: true}- ]),- false+ ]));- optionService.createOption("lastDailyBackupDate", dateUtils.utcNowDateTime(), false);- optionService.createOption("lastWeeklyBackupDate", dateUtils.utcNowDateTime(), false);- optionService.createOption("lastMonthlyBackupDate", dateUtils.utcNowDateTime(), false);- optionService.createOption("dbVersion", appInfo.dbVersion.toString(), false);+ createNotSyncedOption("lastDailyBackupDate", dateUtils.utcNowDateTime());+ createNotSyncedOption("lastWeeklyBackupDate", dateUtils.utcNowDateTime());+ createNotSyncedOption("lastMonthlyBackupDate", dateUtils.utcNowDateTime());+ createNotSyncedOption("dbVersion", appInfo.dbVersion.toString());- optionService.createOption("initialized", initialized ? "true" : "false", false);+ createNotSyncedOption("initialized", initialized ? "true" : "false");- optionService.createOption("lastSyncedPull", "0", false);- optionService.createOption("lastSyncedPush", "0", false);+ createNotSyncedOption("lastSyncedPull", "0");+ createNotSyncedOption("lastSyncedPush", "0");- optionService.createOption("theme", "next", false);- optionService.createOption("textNoteEditorType", "ckeditor-classic", true);+ createNotSyncedOption("theme", "next");- optionService.createOption("syncServerHost", opts.syncServerHost || "", false);- optionService.createOption("syncServerTimeout", "120", false); // 120 seconds (2 minutes)- optionService.createOption("syncProxy", opts.syncProxy || "", false);- optionService.createOption("syncIncomplete", "false", false);+ createNotSyncedOption("syncServerHost", opts.syncServerHost || "");+ createNotSyncedOption("syncServerTimeout", "120"); // 120 seconds (2 minutes)+ createNotSyncedOption("syncProxy", opts.syncProxy || "");+ createNotSyncedOption("syncIncomplete", "false");// Per-device blob size limit (bytes) for sync pulls; 0 = disabled. Set to a non-zero value only// on memory-constrained clients (mobile), so this is not synced across the cluster.- optionService.createOption("syncMaxBlobContentSize", (opts.syncMaxBlobContentSize ?? 0).toString(), false);+ createNotSyncedOption("syncMaxBlobContentSize", (opts.syncMaxBlobContentSize ?? 0).toString());+}++/**+ * Initializes the defaults that apply to a brand-new document only and that, unlike+ * {@link initNotSyncedOptions}, do participate in sync. Must therefore be called only when creating a+ * genuinely new document, never when creating a database to sync an existing one into.+ *+ * These cannot live in {@link defaultOptions}, which is also applied to existing databases on every+ * startup: a value there fills in for everyone who does not have the option yet, so it would change+ * the behaviour of upgrading users as well. And they must not live in {@link initNotSyncedOptions},+ * which also runs on the sync-setup path, on an empty database, before the first pull. An option+ * created there carries the current timestamp, so it wins the purely timestamp-based conflict+ * resolution in `sync_update#updateNormalEntity` against the server's older value and is then pushed+ * to the whole cluster — setting up a single fresh client would silently reset the setting+ * everywhere (#10626).+ */+export function initNewDocumentOptions() {+ optionService.createOption("textNoteEditorType", "ckeditor-classic", true);+}++/**+ * Creates a local-only option, i.e. one that is not propagated to the other instances of a sync+ * cluster. Deliberately offers no way to create a synced option, so that the contract of+ * {@link initNotSyncedOptions} cannot be broken by passing the wrong argument.+ */+function createNotSyncedOption<T extends OptionNames>(name: T, value: string | OptionDefinitions[T]) {+ optionService.createOption(name, value, false);}/**diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex aac8ae8316..d081e08c80 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -132,7 +132,7 @@ async function createInitialDatabase(skipDemoDb?: boolean, locale?: string) {let rootNote!: BNote;// We have to import async since options init requires keyboard actions which require translations.- const { initDocumentOptions, initNotSyncedOptions, initStartupOptions } = await import("./options_init.js");+ const { initDocumentOptions, initNewDocumentOptions, initNotSyncedOptions, initStartupOptions } = await import("./options_init.js");const { load: loadBecca } = await import("../becca/becca_loader.js");const sql = getSql();@@ -166,6 +166,9 @@ async function createInitialDatabase(skipDemoDb?: boolean, locale?: string) {// Bring in option init.initDocumentOptions();initNotSyncedOptions(true, {});+ // Only on this path, and never in `createDatabaseForSync`: these defaults are synced, so on a+ // database created for sync they would overwrite the server's values (see #10626).+ initNewDocumentOptions();initStartupOptions();// Persist the language chosen during setup, overriding the default ("en").if (isDisplayableLocale(locale)) {diff --git a/packages/trilium-core/src/services/sql_init_resetup.spec.ts b/packages/trilium-core/src/services/sql_init_resetup.spec.tsindex bb9611254c..e4952dcb77 100644--- a/packages/trilium-core/src/services/sql_init_resetup.spec.ts+++ b/packages/trilium-core/src/services/sql_init_resetup.spec.ts@@ -73,14 +73,7 @@ describe("createDatabaseForSync on a partially set-up database", () => {it("is a no-op wipe on a virgin database (no schema at all)", async () => {const sql = getSql();- // Reduce the DB to a truly empty file, as on a first-ever run.- sql.execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");- const objects = sql.getRows<{ name: string; type: string }>(- /*sql*/`SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%'`- );- for (const { name, type } of objects) {- sql.execute(`DROP ${type === "view" ? "VIEW" : "TABLE"} IF EXISTS "${name}"`);- }+ wipeToVirginDatabase();expect(sqlInit.schemaExists()).toBe(false);await cls.init(() => sqlInit.createDatabaseForSync(@@ -92,3 +85,52 @@ describe("createDatabaseForSync on a partially set-up database", () => {expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'documentSecret'")).toBe("virgin-secret");});});++/**+ * A database created to sync an existing document into is an empty shell: everything it ends up+ * containing must come from the server. Anything created locally beforehand is stamped with the+ * current time, so it beats the server's older row in the purely timestamp-based conflict+ * resolution of `sync_update#updateNormalEntity`, and the first push then propagates it to the+ * entire cluster — one freshly set-up client silently resetting a setting on every instance+ * (#10626).+ *+ * Asserted over the staged entity changes rather than over one known option, so that anything+ * created on this path, of any entity type, is caught.+ */+describe("createDatabaseForSync on a virgin database", () => {+ it("stages no change for push to the sync server", async () => {+ const sql = getSql();++ wipeToVirginDatabase();++ await cls.init(() => sqlInit.createDatabaseForSync(+ // The real seed is the server's own documentId/documentSecret rows, which are local-only+ // (`options_init#initDocumentOptions`) and so are not pushed back at it.+ [+ { name: "documentId", value: "seed-doc-id", isSynced: false, utcDateModified: "2026-07-18 00:00:00.000Z" },+ { name: "documentSecret", value: "seed-doc-secret", isSynced: false, utcDateModified: "2026-07-18 00:00:00.000Z" }+ ],+ "http://sync-server:8080"+ ));++ // `sync#pushChanges` sends exactly these rows, starting from lastSyncedPush = 0.+ const staged = sql.getRows<{ entityName: string; entityId: string }>(+ /*sql*/`SELECT entityName, entityId FROM entity_changes WHERE isSynced = 1`+ );+ expect(staged).toEqual([]);+ });+});++/** Reduces the database to a truly empty file, as on a first-ever run. */+function wipeToVirginDatabase() {+ const sql = getSql();++ sql.execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");++ const objects = sql.getRows<{ name: string; type: string }>(+ /*sql*/`SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%'`+ );+ for (const { name, type } of objects) {+ sql.execute(`DROP ${type === "view" ? "VIEW" : "TABLE"} IF EXISTS "${name}"`);+ }+}