Skip to content

Build your personal knowledge base with Trilium Notes

core/db: allow custom location for the backup directory, defined as an option

Adorian Doran9ab80e6f185f
diff --git a/apps/build-docs/src/build-docs.ts b/apps/build-docs/src/build-docs.ts
index 133b2b91e4..8cd8800e82 100644
--- a/apps/build-docs/src/build-docs.ts
+++ b/apps/build-docs/src/build-docs.ts
@@ -17,6 +17,7 @@ class StubBackupService extends BackupService {
constructor() {
super({
getOption: () => "",
+ getOptionOrNull: () => null,
getOptionBool: () => false,
setOption: () => {}
});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index e3dfa9f3e3..e7a22e583e 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -257,7 +257,8 @@ export async function main() {
getDemoArchive: async () => fs.readFileSync(path.join(RESOURCE_DIR, "db", "demo.zip")),
inAppHelp: new NodejsInAppHelpProvider(),
log: new ServerLogService(),
- backup: new ServerBackupService(options),
+ // Only the desktop lets the user pick where backups go; the server uses TRILIUM_BACKUP_DIR.
+ backup: new ServerBackupService(options, { allowCustomDirectory: true }),
image: (await import("@triliumnext/server/src/services/image_provider.js")).serverImageProvider,
config,
extraAppInfo: {
diff --git a/apps/edit-docs/src/utils.ts b/apps/edit-docs/src/utils.ts
index 1015d8531d..b1b6ab6249 100644
--- a/apps/edit-docs/src/utils.ts
+++ b/apps/edit-docs/src/utils.ts
@@ -24,7 +24,7 @@ registerTriliumAppScheme();
// Stub backup service (not used in edit-docs, but required by initializeCore)
class StubBackupService extends BackupService {
constructor() {
- super({ getOption: () => "", getOptionBool: () => false, setOption: () => {} });
+ super({ getOption: () => "", getOptionOrNull: () => null, getOptionBool: () => false, setOption: () => {} });
}
scheduleBackups(): void {}
async backupNow(_name: string): Promise<string> {
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 4c168ddde6..c8280d66ec 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -400,6 +400,9 @@
"show-windows": "Show windows",
"open_new_window": "Open new window"
},
+ "backup": {
+ "custom_directory_unwritable": "Database backup failed: unable to write to {{- location}}. Backing up to the default location instead."
+ },
"migration": {
"old_version": "Direct migration from your current version is not supported. Please upgrade to the latest v0.60.4 first and only then to this version.",
"error_message": "Error during migration to version {{version}}: {{stack}}",
diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.ts
index fcd784ebca..be799d85ea 100644
--- a/apps/server/src/backup_provider.spec.ts
+++ b/apps/server/src/backup_provider.spec.ts
@@ -1,42 +1,241 @@
+import type { OptionNames } from "@triliumnext/commons";
+import { getSql, ws } from "@triliumnext/core";
import fs from "fs";
+import os from "os";
import path from "path";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";
import ServerBackupService from "./backup_provider.js";
import dataDir from "./services/data_dir.js";
-const service = new ServerBackupService({
- getOption: () => "",
- getOptionBool: () => false,
- setOption: () => {}
+const DEFAULT_DIR = path.resolve(dataDir.BACKUP_DIR);
+const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-backup-spec-"));
+const CUSTOM_DIR = path.join(tempRoot, "custom");
+
+/** Stands in for the real online backup: writes a small file at the destination. */
+let copyDatabase: MockInstance<(target: string) => Promise<void>>;
+
+async function writeStubDatabase(target: string) {
+ fs.writeFileSync(target, "db-bytes");
+}
+
+/** A desktop service (custom directory honoured) reading the given option value. */
+function desktopService(customDbBackupDir: string | null) {
+ return new ServerBackupService(optionsWith(customDbBackupDir), { allowCustomDirectory: true });
+}
+
+/** A server service, which ignores the option entirely. */
+function serverService(customDbBackupDir: string | null) {
+ return new ServerBackupService(optionsWith(customDbBackupDir));
+}
+
+function optionsWith(customDbBackupDir: string | null) {
+ return {
+ getOption: (name: OptionNames) => (name === "customDbBackupDir" ? customDbBackupDir ?? "" : ""),
+ getOptionOrNull: (name: OptionNames) => (name === "customDbBackupDir" ? customDbBackupDir : null),
+ getOptionBool: () => false,
+ setOption: () => {}
+ };
+}
+
+function backupNamesIn(directory: string) {
+ return fs.existsSync(directory) ? fs.readdirSync(directory).sort() : [];
+}
+
+beforeEach(() => {
+ copyDatabase = vi.spyOn(getSql(), "copyDatabase").mockImplementation(writeStubDatabase);
+ vi.spyOn(ws, "sendMessageToAllClients").mockImplementation(() => {});
+
+ fs.rmSync(tempRoot, { recursive: true, force: true });
+ fs.mkdirSync(tempRoot, { recursive: true });
+ fs.rmSync(DEFAULT_DIR, { recursive: true, force: true });
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+afterAll(() => {
+ fs.rmSync(tempRoot, { recursive: true, force: true });
+ fs.rmSync(DEFAULT_DIR, { recursive: true, force: true });
+});
+
+describe("ServerBackupService: backup location", () => {
+ it("uses the default directory when no custom one is configured", async () => {
+ const service = desktopService("");
+
+ expect(service.getBackupFolderPath()).toBe(DEFAULT_DIR);
+ expect(await service.backupNow("now")).toBe(path.join(DEFAULT_DIR, "backup-now.db"));
+ });
+
+ it("uses the custom directory on the desktop, creating it if needed", async () => {
+ const service = desktopService(CUSTOM_DIR);
+
+ expect(service.getBackupFolderPath()).toBe(CUSTOM_DIR);
+ expect(await service.backupNow("daily")).toBe(path.join(CUSTOM_DIR, "backup-daily.db"));
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);
+ expect(backupNamesIn(DEFAULT_DIR)).toEqual([]);
+ });
+
+ it("ignores the custom directory on the server, which is configured via TRILIUM_BACKUP_DIR", async () => {
+ const service = serverService(CUSTOM_DIR);
+
+ expect(service.getBackupFolderPath()).toBe(DEFAULT_DIR);
+ expect(await service.backupNow("daily")).toBe(path.join(DEFAULT_DIR, "backup-daily.db"));
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([]);
+ });
+
+ it("falls back to the default directory for a blank, whitespace-only or missing option", () => {
+ expect(desktopService("").getBackupFolderPath()).toBe(DEFAULT_DIR);
+ expect(desktopService(" ").getBackupFolderPath()).toBe(DEFAULT_DIR);
+ // The option row does not exist yet, e.g. the pre-migration backup of an older database.
+ expect(desktopService(null).getBackupFolderPath()).toBe(DEFAULT_DIR);
+ });
+
+ it("resolves a relative custom directory against the working directory", () => {
+ expect(desktopService("./my-backups").getBackupFolderPath()).toBe(path.resolve("./my-backups"));
+ });
+
+ it("treats a custom directory equal to the default one as no custom directory", async () => {
+ const service = desktopService(DEFAULT_DIR);
+
+ expect(service.getBackupFolderPath()).toBe(DEFAULT_DIR);
+ await service.backupNow("now");
+ // Listed once, not once per configured directory.
+ expect((await service.getExistingBackups()).map((b) => b.fileName)).toEqual(["backup-now.db"]);
+ });
+});
+
+describe("ServerBackupService: fallback when the custom directory cannot be written to", () => {
+ it("backs up to the default directory and notifies the user", async () => {
+ copyDatabase.mockRejectedValueOnce(new Error("ENOSPC: no space left on device"));
+
+ expect(await desktopService(CUSTOM_DIR).backupNow("daily")).toBe(path.join(DEFAULT_DIR, "backup-daily.db"));
+ expect(backupNamesIn(DEFAULT_DIR)).toEqual(["backup-daily.db"]);
+
+ expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: "toast",
+ message: `Database backup failed: unable to write to ${CUSTOM_DIR}. Backing up to the default location instead.`
+ })
+ );
+ });
+
+ it("falls back when the custom directory itself cannot be created", async () => {
+ // A file where the directory should be: mkdir fails on every platform.
+ const blocked = path.join(tempRoot, "blocked");
+ fs.writeFileSync(blocked, "not-a-directory");
+
+ const service = desktopService(path.join(blocked, "backups"));
+
+ expect(await service.backupNow("now")).toBe(path.join(DEFAULT_DIR, "backup-now.db"));
+ expect(ws.sendMessageToAllClients).toHaveBeenCalledOnce();
+ });
+
+ it("leaves no half-written file behind in the custom directory", async () => {
+ copyDatabase.mockImplementationOnce(async (target: string) => {
+ fs.writeFileSync(target, "partial");
+ throw new Error("EIO: i/o error");
+ });
+
+ await desktopService(CUSTOM_DIR).backupNow("daily");
+
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([]);
+ expect(backupNamesIn(DEFAULT_DIR)).toEqual(["backup-daily.db"]);
+ });
+
+ it("propagates the failure when the default directory fails too", async () => {
+ copyDatabase.mockRejectedValue(new Error("EACCES: permission denied"));
+
+ await expect(desktopService(CUSTOM_DIR).backupNow("now")).rejects.toThrow("EACCES");
+ });
+
+ it("does not notify when there is no custom directory to fall back from", async () => {
+ copyDatabase.mockRejectedValue(new Error("EACCES: permission denied"));
+
+ await expect(desktopService("").backupNow("now")).rejects.toThrow("EACCES");
+ expect(ws.sendMessageToAllClients).not.toHaveBeenCalled();
+ });
});
-const dbFile = path.join(dataDir.BACKUP_DIR, "backup-spec-list.db");
-const journalFile = path.join(dataDir.BACKUP_DIR, "backup-spec-list.db-journal");
+describe("ServerBackupService.backupNow: naming", () => {
+ it("rejects a name with no usable characters", async () => {
+ await expect(desktopService("").backupNow("../..")).rejects.toThrow("Invalid backup name");
+ });
-describe("ServerBackupService", () => {
- afterAll(() => {
- fs.rmSync(dbFile, { force: true });
- fs.rmSync(journalFile, { force: true });
+ it("strips path traversal from the name", async () => {
+ expect(await desktopService(CUSTOM_DIR).backupNow("../../evil")).toBe(path.join(CUSTOM_DIR, "backup-evil.db"));
});
+});
+describe("ServerBackupService.getExistingBackups", () => {
it("lists .db backups with their size, excluding intermediate SQLite files", async () => {
- fs.mkdirSync(dataDir.BACKUP_DIR, { recursive: true });
- fs.writeFileSync(dbFile, "backup-bytes");
- fs.writeFileSync(journalFile, "journal-bytes");
+ fs.mkdirSync(DEFAULT_DIR, { recursive: true });
+ fs.writeFileSync(path.join(DEFAULT_DIR, "backup-spec-list.db"), "backup-bytes");
+ fs.writeFileSync(path.join(DEFAULT_DIR, "backup-spec-list.db-journal"), "journal-bytes");
+
+ const backups = await desktopService("").getExistingBackups();
+
+ expect(backups.map((b) => b.fileName)).toEqual(["backup-spec-list.db"]);
+ expect(backups[0].fileSize).toBe("backup-bytes".length);
+ expect(backups[0].filePath).toBe(path.join(DEFAULT_DIR, "backup-spec-list.db"));
+ expect(backups[0].mtime).toBeInstanceOf(Date);
+ });
+
+ it("merges the custom and the default directory, so redirected backups stay reachable", async () => {
+ fs.mkdirSync(CUSTOM_DIR, { recursive: true });
+ fs.mkdirSync(DEFAULT_DIR, { recursive: true });
+ fs.writeFileSync(path.join(CUSTOM_DIR, "backup-daily.db"), "a");
+ fs.writeFileSync(path.join(DEFAULT_DIR, "backup-weekly.db"), "b");
+
+ const backups = await desktopService(CUSTOM_DIR).getExistingBackups();
+
+ expect(backups.map((b) => b.filePath).sort()).toEqual(
+ [path.join(CUSTOM_DIR, "backup-daily.db"), path.join(DEFAULT_DIR, "backup-weekly.db")].sort()
+ );
+ });
+
+ it("tolerates a custom directory that does not exist", async () => {
+ await expect(desktopService(path.join(tempRoot, "gone")).getExistingBackups()).resolves.toEqual([]);
+ });
+});
+
+describe("ServerBackupService.getBackupContent", () => {
+ it("reads a backup from the default directory", async () => {
+ fs.mkdirSync(DEFAULT_DIR, { recursive: true });
+ const file = path.join(DEFAULT_DIR, "backup-now.db");
+ fs.writeFileSync(file, "db-bytes");
+
+ expect(await desktopService("").getBackupContent(file)).toEqual(Buffer.from("db-bytes"));
+ });
+
+ it("reads a backup from the custom directory", async () => {
+ fs.mkdirSync(CUSTOM_DIR, { recursive: true });
+ const file = path.join(CUSTOM_DIR, "backup-now.db");
+ fs.writeFileSync(file, "db-bytes");
+
+ expect(await desktopService(CUSTOM_DIR).getBackupContent(file)).toEqual(Buffer.from("db-bytes"));
+ });
+
+ it("refuses a path outside the backup directories", async () => {
+ const outside = path.join(tempRoot, "secret.db");
+ fs.writeFileSync(outside, "secret");
+
+ expect(await desktopService(CUSTOM_DIR).getBackupContent(outside)).toBeNull();
+ expect(await desktopService(CUSTOM_DIR).getBackupContent(path.join(DEFAULT_DIR, "..", "document.db"))).toBeNull();
+ // The directory itself is not a backup.
+ expect(await desktopService(CUSTOM_DIR).getBackupContent(CUSTOM_DIR)).toBeNull();
+ // The custom directory is only allowed while it is the configured one.
+ expect(await desktopService("").getBackupContent(path.join(CUSTOM_DIR, "backup-now.db"))).toBeNull();
+ });
- const backups = await service.getExistingBackups();
- const names = backups.map((b) => b.fileName);
- expect(names).toContain("backup-spec-list.db");
- expect(names).not.toContain("backup-spec-list.db-journal");
+ it("accepts a custom directory given with a trailing separator", async () => {
+ fs.mkdirSync(CUSTOM_DIR, { recursive: true });
+ const file = path.join(CUSTOM_DIR, "backup-now.db");
+ fs.writeFileSync(file, "db-bytes");
- const entry = backups.find((b) => b.fileName === "backup-spec-list.db");
- expect(entry?.fileSize).toBe("backup-bytes".length);
- expect(entry?.filePath).toBe(path.resolve(dataDir.BACKUP_DIR, "backup-spec-list.db"));
- expect(entry?.mtime).toBeInstanceOf(Date);
+ expect(await desktopService(CUSTOM_DIR + path.sep).getBackupContent(file)).toEqual(Buffer.from("db-bytes"));
});
- it("reports the backup folder path", () => {
- expect(service.getBackupFolderPath()).toBe(path.resolve(dataDir.BACKUP_DIR));
+ it("returns null for a missing file inside the backup directory", async () => {
+ expect(await desktopService("").getBackupContent(path.join(DEFAULT_DIR, "backup-absent.db"))).toBeNull();
});
});
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.ts
index 76797fde16..6846d70d0e 100644
--- a/apps/server/src/backup_provider.ts
+++ b/apps/server/src/backup_provider.ts
@@ -1,35 +1,32 @@
import type { DatabaseBackup } from "@triliumnext/commons";
-import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService } from "@triliumnext/core";
+import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService, ws } from "@triliumnext/core";
import fs from "fs";
+import { t } from "i18next";
import path from "path";
import dataDir from "./services/data_dir.js";
import sql from "./services/sql.js";
+export interface ServerBackupConfig {
+ /**
+ * Whether the `customDbBackupDir` option is honoured. Set by the desktop application, where the user
+ * picks the directory themselves; on the server the backup location is part of the deployment and is
+ * configured through the `TRILIUM_BACKUP_DIR` environment variable instead.
+ */
+ allowCustomDirectory?: boolean;
+}
+
export default class ServerBackupService extends BackupService {
- constructor(options: BackupOptionsService) {
+ constructor(options: BackupOptionsService, private readonly config: ServerBackupConfig = {}) {
super(options);
}
override async getExistingBackups(): Promise<DatabaseBackup[]> {
- if (!fs.existsSync(dataDir.BACKUP_DIR)) {
- return [];
- }
-
- return fs
- .readdirSync(dataDir.BACKUP_DIR)
- // The .db check excludes intermediate SQLite files (e.g. *.db-journal) created while a backup is in progress.
- .filter((fileName) => fileName.includes("backup") && fileName.endsWith(".db"))
- .map((fileName) => {
- const filePath = path.resolve(dataDir.BACKUP_DIR, fileName);
- const stat = fs.statSync(filePath);
-
- return { fileName, filePath, mtime: stat.mtime, fileSize: stat.size };
- });
+ return this.getBackupDirectories().flatMap(listBackupsIn);
}
override getBackupFolderPath(): string {
- return path.resolve(dataDir.BACKUP_DIR);
+ return this.getCustomBackupDir() ?? getDefaultBackupDir();
}
override scheduleBackups(): void {
@@ -48,28 +45,36 @@ export default class ServerBackupService extends BackupService {
throw new Error("Invalid backup name: must contain at least one alphanumeric character, hyphen, or underscore.");
}
+ const fileName = `backup-${sanitizedName}.db`;
+
// we don't want to back up DB in the middle of sync with potentially inconsistent DB state
return await syncMutexService.doExclusively(async () => {
- const backupFile = path.resolve(`${dataDir.BACKUP_DIR}/backup-${sanitizedName}.db`);
-
- if (!fs.existsSync(dataDir.BACKUP_DIR)) {
- fs.mkdirSync(dataDir.BACKUP_DIR, 0o700);
+ const customDir = this.getCustomBackupDir();
+
+ if (customDir) {
+ try {
+ return await writeBackup(customDir, fileName);
+ } catch (e) {
+ // A backup that cannot reach the chosen location is still worth having, so the
+ // default one takes over instead of the backup being lost altogether.
+ getLog().error(`Could not back up to '${customDir}', falling back to the default directory: ${e}`);
+ ws.sendMessageToAllClients({
+ type: "toast",
+ message: t("backup.custom_directory_unwritable", { location: customDir }),
+ timeout: 15000
+ });
+ }
}
- getLog().info("Creating backup...");
- await sql.copyDatabase(backupFile);
- getLog().info(`Created backup at ${backupFile}`);
-
- return backupFile;
+ return await writeBackup(getDefaultBackupDir(), fileName);
});
}
override async getBackupContent(filePath: string): Promise<Uint8Array | null> {
const resolvedPath = path.resolve(filePath);
- const backupDir = path.resolve(dataDir.BACKUP_DIR);
- // Security check: ensure the path is within the backup directory
- if (!resolvedPath.startsWith(backupDir + path.sep)) {
+ // Security check: ensure the path is within one of the backup directories
+ if (!this.getBackupDirectories().some((dir) => isInsideDirectory(dir, resolvedPath))) {
return null;
}
@@ -79,4 +84,84 @@ export default class ServerBackupService extends BackupService {
return fs.readFileSync(resolvedPath);
}
+
+ /** The directory the user chose to back up to, or `null` when the default one applies. */
+ private getCustomBackupDir(): string | null {
+ if (!this.config.allowCustomDirectory) {
+ return null;
+ }
+
+ const customDir = this.options.getOptionOrNull("customDbBackupDir")?.trim();
+ if (!customDir) {
+ return null;
+ }
+
+ const resolved = path.resolve(customDir);
+ return resolved !== getDefaultBackupDir() ? resolved : null;
+ }
+
+ /**
+ * Every directory that may hold backups. The default one stays in the list next to a custom
+ * directory, since it still holds the backups taken before the custom one was chosen, as well as
+ * the ones redirected there after a failed write.
+ */
+ private getBackupDirectories(): string[] {
+ const customDir = this.getCustomBackupDir();
+ const defaultDir = getDefaultBackupDir();
+
+ return customDir ? [customDir, defaultDir] : [defaultDir];
+ }
+}
+
+function getDefaultBackupDir(): string {
+ return path.resolve(dataDir.BACKUP_DIR);
+}
+
+/** Both paths must already be resolved. Unlike a prefix comparison, this also holds at a drive root. */
+function isInsideDirectory(directory: string, filePath: string): boolean {
+ const relative = path.relative(directory, filePath);
+
+ return !!relative && !relative.startsWith("..") && !path.isAbsolute(relative);
+}
+
+function listBackupsIn(directory: string): DatabaseBackup[] {
+ let fileNames: string[];
+ try {
+ fileNames = fs.readdirSync(directory);
+ } catch {
+ // Missing or unreadable, e.g. a custom directory on a drive that is no longer plugged in.
+ return [];
+ }
+
+ return fileNames
+ // The .db check excludes intermediate SQLite files (e.g. *.db-journal) created while a backup is in progress.
+ .filter((fileName) => fileName.includes("backup") && fileName.endsWith(".db"))
+ .flatMap((fileName) => {
+ const filePath = path.resolve(directory, fileName);
+ const stat = fs.statSync(filePath, { throwIfNoEntry: false });
+ if (!stat) {
+ return [];
+ }
+
+ return [{ fileName, filePath, mtime: stat.mtime, fileSize: stat.size }];
+ });
+}
+
+async function writeBackup(directory: string, fileName: string): Promise<string> {
+ const backupFile = path.resolve(directory, fileName);
+
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
+
+ getLog().info("Creating backup...");
+ try {
+ await sql.copyDatabase(backupFile);
+ } catch (e) {
+ // Whatever was written before the failure is not a usable database, and would otherwise be
+ // listed and offered for download as if it were one.
+ fs.rmSync(backupFile, { force: true });
+ throw e;
+ }
+ getLog().info(`Created backup at ${backupFile}`);
+
+ return backupFile;
}
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index ad194f9a72..8a08fcd590 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -55,6 +55,12 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
lastDailyBackupDate: string;
lastWeeklyBackupDate: string;
lastMonthlyBackupDate: string;
+ /**
+ * Directory the database backups are written to, replacing the default one inside the data
+ * directory. Empty means "use the default". Honoured on the desktop application only; the server
+ * is configured through the `TRILIUM_BACKUP_DIR` environment variable instead.
+ */
+ customDbBackupDir: string;
dbVersion: string;
theme: string;
syncServerHost: string;
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 6186af0f0b..9c4210be24 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -90,6 +90,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([
"dailyBackupEnabled",
"weeklyBackupEnabled",
"monthlyBackupEnabled",
+ "customDbBackupDir",
"motionEnabled",
"shadowsEnabled",
"smoothScrollEnabled",
diff --git a/packages/trilium-core/src/services/backup.spec.ts b/packages/trilium-core/src/services/backup.spec.ts
index 006c27001a..1862f426b7 100644
--- a/packages/trilium-core/src/services/backup.spec.ts
+++ b/packages/trilium-core/src/services/backup.spec.ts
@@ -7,7 +7,7 @@ import dateUtils from "./utils/date.js";
/**
* A simple in-memory options service used to drive the abstract backup logic.
- * Mirrors the three methods the real BackupOptionsService exposes.
+ * Mirrors the methods the real BackupOptionsService exposes.
*/
class FakeOptions implements BackupOptionsService {
private readonly store: Record<string, string>;
@@ -20,6 +20,10 @@ class FakeOptions implements BackupOptionsService {
return this.store[name] ?? "";
}
+ getOptionOrNull(name: OptionNames): string | null {
+ return this.store[name] ?? null;
+ }
+
getOptionBool(name: FilterOptionsByType<boolean>): boolean {
return this.store[name] === "true";
}
diff --git a/packages/trilium-core/src/services/backup.ts b/packages/trilium-core/src/services/backup.ts
index fe1a94d503..ad554a21bb 100644
--- a/packages/trilium-core/src/services/backup.ts
+++ b/packages/trilium-core/src/services/backup.ts
@@ -6,6 +6,11 @@ type BackupType = "daily" | "weekly" | "monthly";
export interface BackupOptionsService {
getOption(name: OptionNames): string;
+ /**
+ * Reads an option without throwing when it does not exist yet — the pre-migration backup runs
+ * before {@link options_init.initStartupOptions} has filled in the options added by newer versions.
+ */
+ getOptionOrNull(name: OptionNames): string | null;
getOptionBool(name: FilterOptionsByType<boolean>): boolean;
setOption(name: OptionNames, value: string): void;
}
diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.ts
index 5f22c020a2..f047ed1a79 100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@ -210,6 +210,7 @@ const defaultOptions: DefaultOption[] = [
{ name: "dailyBackupEnabled", value: "true", isSynced: false },
{ name: "weeklyBackupEnabled", value: "true", isSynced: false },
{ name: "monthlyBackupEnabled", value: "true", isSynced: false },
+ { name: "customDbBackupDir", value: "", isSynced: false },
{ name: "maxContentWidth", value: "1200", isSynced: false },
{ name: "centerContent", value: "false", isSynced: false },
{ name: "compressImages", value: "true", isSynced: true },