Skip to content

Build your personal knowledge base with Trilium Notes

core/db backup: set up the backup provider to support backup containers

Adorian Doran887a60ee560a
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 6aa1859a8f..50bae5ad1c 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -32,7 +32,7 @@ import { setupReferer } from "./services/referer";
import { setupDialogHandlers } from "./services/dialog";
import { setupExportHandlers } from "./services/export";
import { setupImportHandlers } from "./services/import";
-import { registerBackupPassphraseIpcHandlers } from "./services/backup_passphrase";
+import { getBackupPassphrase, registerBackupPassphraseIpcHandlers } from "./services/backup_passphrase";
import { setupOneNoteHandlers } from "./services/onenote";
import { setupPrintingHandlers } from "./services/printing";
import ElectronRequestProvider from "./services/request";
@@ -262,7 +262,7 @@ export async function main() {
inAppHelp: new NodejsInAppHelpProvider(),
log: new ServerLogService(),
// Only the desktop lets the user pick where backups go; the server uses TRILIUM_BACKUP_DIR.
- backup: new ServerBackupService(options, { allowCustomDirectory: true }),
+ backup: new ServerBackupService(options, { allowCustomDirectory: true, getPassphrase: getBackupPassphrase }),
image: (await import("@triliumnext/server/src/services/image_provider.js")).serverImageProvider,
config,
extraAppInfo: {
diff --git a/apps/server/package.json b/apps/server/package.json
index 96574a5029..5e58423eb3 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -48,6 +48,7 @@
},
"devDependencies": {
"@braintree/sanitize-url": "7.1.2",
+ "@triliumnext/backup-container": "workspace:*",
"@triliumnext/commons": "workspace:*",
"@triliumnext/core": "workspace:*",
"@triliumnext/express-partial-content": "workspace:*",
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index d3bacd8508..f16cf54c74 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -401,7 +401,8 @@
"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."
+ "custom_directory_unwritable": "Database backup failed: unable to write to {{- location}}. Backing up to the default location instead.",
+ "passphrase_unavailable": "The backup password could not be read, so this backup is not encrypted. It has been saved to the default location instead of the chosen one."
},
"dialog": {
"select_directory": "Select folder"
diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.ts
index 350f213f00..98b0563e3b 100644
--- a/apps/server/src/backup_provider.spec.ts
+++ b/apps/server/src/backup_provider.spec.ts
@@ -5,7 +5,10 @@ import os from "os";
import path from "path";
import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";
-import ServerBackupService from "./backup_provider.js";
+import { readBackupContainer } from "@triliumnext/backup-container";
+import { Readable, Writable } from "stream";
+
+import ServerBackupService, { type ServerBackupConfig } from "./backup_provider.js";
import dataDir from "./services/data_dir.js";
const DEFAULT_DIR = path.resolve(dataDir.BACKUP_DIR);
@@ -20,8 +23,8 @@ async function writeStubDatabase(target: string) {
}
/** A desktop service (custom directory honoured) reading the given option value. */
-function desktopService(customDbBackupDir: string | null) {
- return new ServerBackupService(optionsWith(customDbBackupDir), { allowCustomDirectory: true });
+function desktopService(customDbBackupDir: string | null, extraOptions: OptionOverrides = {}, config: Partial<ServerBackupConfig> = {}) {
+ return new ServerBackupService(optionsWith(customDbBackupDir, extraOptions), { allowCustomDirectory: true, ...config });
}
/** A server service, which ignores the option entirely. */
@@ -29,10 +32,14 @@ function serverService(customDbBackupDir: string | null) {
return new ServerBackupService(optionsWith(customDbBackupDir));
}
-function optionsWith(customDbBackupDir: string | null) {
+type OptionOverrides = Partial<Record<OptionNames, string>>;
+
+function optionsWith(customDbBackupDir: string | null, extraOptions: OptionOverrides = {}) {
+ const values: Partial<Record<OptionNames, string | null>> = { customDbBackupDir, ...extraOptions };
+
return {
- getOption: (name: OptionNames) => (name === "customDbBackupDir" ? customDbBackupDir ?? "" : ""),
- getOptionOrNull: (name: OptionNames) => (name === "customDbBackupDir" ? customDbBackupDir : null),
+ getOption: (name: OptionNames) => values[name] ?? "",
+ getOptionOrNull: (name: OptionNames) => values[name] ?? null,
getOptionBool: () => false,
setOption: () => {}
};
@@ -104,6 +111,136 @@ describe("ServerBackupService: backup location", () => {
});
});
+describe("ServerBackupService: backup format", () => {
+ const PASSPHRASE = "correct horse battery staple";
+ const withPassphrase: Partial<ServerBackupConfig> = { getPassphrase: async () => PASSPHRASE };
+
+ /** Unwraps a container back to the bytes the stub database was made of. */
+ async function unwrap(filePath: string, passphrase?: string) {
+ const chunks: Buffer[] = [];
+ const sink = new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ chunks.push(Buffer.from(chunk));
+ callback();
+ }
+ });
+
+ await readBackupContainer(Readable.from([fs.readFileSync(filePath)]), sink, {
+ passphrase,
+ // The stub standing in for the online backup is not a real database.
+ requireSqliteHeader: false
+ });
+
+ return Buffer.concat(chunks).toString();
+ }
+
+ it("writes a plain database when neither compression nor encryption is on", async () => {
+ expect(await desktopService(CUSTOM_DIR).backupNow("now")).toBe(path.join(CUSTOM_DIR, "backup-now.db"));
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-now.db"]);
+ });
+
+ it("writes a compressed container, which unwraps to the database again", async () => {
+ const service = desktopService(CUSTOM_DIR, { backupEnableCompression: "true" });
+
+ const backupFile = await service.backupNow("now");
+
+ expect(backupFile).toBe(path.join(CUSTOM_DIR, "backup-now.tnbackup"));
+ expect(await unwrap(backupFile)).toBe("db-bytes");
+ });
+
+ it("writes an encrypted container, which only the passphrase opens", async () => {
+ const service = desktopService(CUSTOM_DIR, { backupEnableEncryption: "true" }, withPassphrase);
+
+ const backupFile = await service.backupNow("now");
+
+ expect(backupFile).toBe(path.join(CUSTOM_DIR, "backup-now.tnbackup"));
+ expect(await unwrap(backupFile, PASSPHRASE)).toBe("db-bytes");
+ await expect(unwrap(backupFile, "wrong")).rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });
+ });
+
+ it("compresses and encrypts together when both are on", async () => {
+ const service = desktopService(CUSTOM_DIR, { backupEnableCompression: "true", backupEnableEncryption: "true" }, withPassphrase);
+
+ const backupFile = await service.backupNow("now");
+
+ expect(await unwrap(backupFile, PASSPHRASE)).toBe("db-bytes");
+ });
+
+ it("keeps one file per backup name, whichever format it was last written in", async () => {
+ await desktopService(CUSTOM_DIR).backupNow("daily");
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);
+
+ await desktopService(CUSTOM_DIR, { backupEnableCompression: "true" }).backupNow("daily");
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.tnbackup"]);
+
+ await desktopService(CUSTOM_DIR).backupNow("daily");
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);
+ });
+
+ it("leaves no snapshot behind in the data directory", async () => {
+ await desktopService(CUSTOM_DIR, { backupEnableCompression: "true" }).backupNow("now");
+
+ expect(fs.readdirSync(dataDir.TMP_DIR).filter((name) => name.includes("snapshot"))).toEqual([]);
+ });
+
+ it("cleans up after a failure, leaving neither a snapshot nor a partial container", async () => {
+ copyDatabase.mockRejectedValue(new Error("EIO: i/o error"));
+
+ await expect(desktopService("", { backupEnableCompression: "true" }).backupNow("now")).rejects.toThrow("EIO");
+
+ expect(fs.readdirSync(dataDir.TMP_DIR).filter((name) => name.includes("snapshot"))).toEqual([]);
+ expect(backupNamesIn(DEFAULT_DIR)).toEqual([]);
+ });
+
+ it("lists containers alongside plain backups", async () => {
+ await desktopService("", { backupEnableCompression: "true" }).backupNow("daily");
+ await desktopService("").backupNow("weekly");
+
+ const backups = await desktopService("").getExistingBackups();
+
+ expect(backups.map((b) => b.fileName).sort()).toEqual(["backup-daily.tnbackup", "backup-weekly.db"]);
+ });
+});
+
+describe("ServerBackupService: when the backup passphrase cannot be read", () => {
+ const noPassphrase: Partial<ServerBackupConfig> = { getPassphrase: async () => null };
+
+ it("keeps the unencrypted backup out of the chosen directory and says so", async () => {
+ const service = desktopService(CUSTOM_DIR, { backupEnableEncryption: "true" }, noPassphrase);
+
+ const backupFile = await service.backupNow("daily");
+
+ // The chosen directory is typically a synced folder, which is what encryption was avoiding.
+ // With nothing left to wrap, the backup is a plain database again rather than an empty container.
+ expect(backupFile).toBe(path.join(DEFAULT_DIR, "backup-daily.db"));
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual([]);
+ expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "toast", message: expect.stringContaining("not encrypted") })
+ );
+ });
+
+ it("still honours compression, so the backup is only missing what could not be done", async () => {
+ const service = desktopService(CUSTOM_DIR, { backupEnableCompression: "true", backupEnableEncryption: "true" }, noPassphrase);
+
+ const backupFile = await service.backupNow("daily");
+
+ expect(backupFile).toBe(path.join(DEFAULT_DIR, "backup-daily.tnbackup"));
+ });
+
+ it("says nothing and encrypts nothing when encryption was never asked for", async () => {
+ await desktopService(CUSTOM_DIR, {}, noPassphrase).backupNow("daily");
+
+ expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-daily.db"]);
+ expect(ws.sendMessageToAllClients).not.toHaveBeenCalled();
+ });
+
+ it("treats a service with no passphrase provider at all the same way", async () => {
+ const service = desktopService(CUSTOM_DIR, { backupEnableEncryption: "true" });
+
+ expect(await service.backupNow("daily")).toBe(path.join(DEFAULT_DIR, "backup-daily.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"));
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.ts
index d97b3ab41b..f6af28db92 100644
--- a/apps/server/src/backup_provider.ts
+++ b/apps/server/src/backup_provider.ts
@@ -1,12 +1,18 @@
+import { writeBackupContainer } from "@triliumnext/backup-container";
import type { DatabaseBackup } from "@triliumnext/commons";
import { BackupOptionsService, BackupService, utils as coreUtils, getLog, sync_mutex as syncMutexService, ws } from "@triliumnext/core";
import fs from "fs";
+import fsp from "fs/promises";
import { t } from "i18next";
import path from "path";
import dataDir from "./services/data_dir.js";
import sql from "./services/sql.js";
+/** Backups that are compressed, encrypted or both are containers rather than plain database copies. */
+const CONTAINER_EXTENSION = ".tnbackup";
+const DATABASE_EXTENSION = ".db";
+
export interface ServerBackupConfig {
/**
* Whether the `customDbBackupDir` option is honoured. Set by the desktop application, where the user
@@ -14,6 +20,23 @@ export interface ServerBackupConfig {
* configured through the `TRILIUM_BACKUP_DIR` environment variable instead.
*/
allowCustomDirectory?: boolean;
+ /**
+ * Reads the stored backup passphrase, or `null` when there is none to be had. Set by the desktop
+ * application, which is the only one with an OS keyring to keep a passphrase in.
+ */
+ getPassphrase?: () => Promise<string | null>;
+}
+
+/** How a backup is to be written, once the options and the passphrase have both had their say. */
+interface BackupFormat {
+ compress: boolean;
+ passphrase: string | null;
+ /**
+ * Set when encryption was asked for and could not be delivered. The backup is still worth having,
+ * but it must stay in the default directory: the chosen one is typically a synced folder, and
+ * putting an unencrypted database there is the very thing encryption was turned on to avoid.
+ */
+ keepLocal: boolean;
}
export default class ServerBackupService extends BackupService {
@@ -45,15 +68,16 @@ 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`;
+ const baseName = `backup-${sanitizedName}`;
// we don't want to back up DB in the middle of sync with potentially inconsistent DB state
return await syncMutexService.doExclusively(async () => {
- const customDir = this.getCustomBackupDir();
+ const format = await this.resolveFormat();
+ const customDir = format.keepLocal ? null : this.getCustomBackupDir();
if (customDir) {
try {
- return await writeBackup(customDir, fileName, "custom");
+ return await writeBackup(customDir, baseName, format, "custom");
} 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. The reason
@@ -67,7 +91,7 @@ export default class ServerBackupService extends BackupService {
}
}
- return await writeBackup(getDefaultBackupDir(), fileName, "default");
+ return await writeBackup(getDefaultBackupDir(), baseName, format, "default");
});
}
@@ -86,6 +110,36 @@ export default class ServerBackupService extends BackupService {
return fs.readFileSync(resolvedPath);
}
+ /**
+ * Settles what the backup is written as. Compression alone needs nothing but the option; encryption
+ * also needs a passphrase, and where that cannot be read the backup falls back to being unencrypted
+ * and local rather than not being taken at all.
+ */
+ private async resolveFormat(): Promise<BackupFormat> {
+ // Read leniently: the pre-migration backup runs before the options added by newer versions exist.
+ const isEnabled = (name: "backupEnableCompression" | "backupEnableEncryption") =>
+ this.options.getOptionOrNull(name) === "true";
+
+ const compress = isEnabled("backupEnableCompression");
+ if (!isEnabled("backupEnableEncryption")) {
+ return { compress, passphrase: null, keepLocal: false };
+ }
+
+ const passphrase = (await this.config.getPassphrase?.()) ?? null;
+ if (passphrase) {
+ return { compress, passphrase, keepLocal: false };
+ }
+
+ getLog().error("Could not read the backup passphrase; backing up unencrypted to the default location.");
+ ws.sendMessageToAllClients({
+ type: "toast",
+ message: t("backup.passphrase_unavailable"),
+ timeout: 15000
+ });
+
+ return { compress, passphrase: null, keepLocal: true };
+ }
+
/** The directory the user chose to back up to, or `null` when the default one applies. */
private getCustomBackupDir(): string | null {
if (!this.config.allowCustomDirectory) {
@@ -135,8 +189,9 @@ function listBackupsIn(directory: string): DatabaseBackup[] {
}
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"))
+ // The extension check excludes intermediate files (e.g. *.db-journal, *.part) created while a
+ // backup is in progress.
+ .filter((fileName) => fileName.includes("backup") && (fileName.endsWith(DATABASE_EXTENSION) || fileName.endsWith(CONTAINER_EXTENSION)))
.flatMap((fileName) => {
const filePath = path.resolve(directory, fileName);
const stat = fs.statSync(filePath, { throwIfNoEntry: false });
@@ -148,25 +203,73 @@ function listBackupsIn(directory: string): DatabaseBackup[] {
});
}
-async function writeBackup(directory: string, fileName: string, location: "default" | "custom"): Promise<string> {
+async function writeBackup(directory: string, baseName: string, format: BackupFormat, location: "default" | "custom"): Promise<string> {
+ const isContainer = format.compress || format.passphrase !== null;
+ const fileName = `${baseName}${isContainer ? CONTAINER_EXTENSION : DATABASE_EXTENSION}`;
const backupFile = path.resolve(directory, fileName);
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
getLog().info("Creating backup...");
try {
- await sql.copyDatabase(backupFile);
+ if (isContainer) {
+ await writeContainer(backupFile, baseName, format);
+ } else {
+ await sql.copyDatabase(backupFile);
+ }
} catch (e) {
- // Whatever was written before the failure is not a usable database, and would otherwise be
+ // Whatever was written before the failure is not a usable backup, and would otherwise be
// listed and offered for download as if it were one.
fs.rmSync(backupFile, { force: true });
throw new Error(withoutDirectory(e, directory));
}
+
+ // One backup name, one file: a container retires the plain copy it replaces, and the other way round.
+ fs.rmSync(path.resolve(directory, `${baseName}${isContainer ? DATABASE_EXTENSION : CONTAINER_EXTENSION}`), { force: true });
+
getLog().info(`Created backup .${path.sep}${fileName}${location === "custom" ? " in the custom backup location." : ""}`);
return backupFile;
}
+/**
+ * Wraps the database into a container.
+ *
+ * SQLite's backup API writes to a path rather than a stream, so a snapshot has to land somewhere
+ * before it can be fed to the writer. It lands in the data directory's temp folder and is deleted
+ * straight after, so the backup directory never holds a plain database even for a moment.
+ */
+async function writeContainer(backupFile: string, baseName: string, format: BackupFormat): Promise<void> {
+ const snapshot = path.resolve(dataDir.TMP_DIR, `${baseName}.snapshot.db`);
+ const partial = `${backupFile}.part`;
+
+ try {
+ await sql.copyDatabase(snapshot);
+
+ await writeBackupContainer(fs.createReadStream(snapshot), fs.createWriteStream(partial), {
+ compress: format.compress,
+ passphrase: format.passphrase ?? undefined,
+ plaintextSize: fs.statSync(snapshot).size,
+ // The digest is only known once the payload is written, so it is patched in afterwards.
+ patchHeader: async (offset, data) => {
+ const handle = await fsp.open(partial, "r+");
+ try {
+ await handle.write(data, 0, data.length, offset);
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ }
+ });
+
+ // Renamed last, so a half-written container is never mistaken for a finished one.
+ fs.renameSync(partial, backupFile);
+ } finally {
+ fs.rmSync(snapshot, { force: true });
+ fs.rmSync(partial, { force: true });
+ }
+}
+
/**
* Keeps the backup directory out of anything that reaches the log. It carries the user's name on most
* platforms, and the backend log is meant to be shareable for diagnostics without having to be censored
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d91e6382a0..065306dcf0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -630,6 +630,9 @@ importers:
'@braintree/sanitize-url':
specifier: 7.1.2
version: 7.1.2
+ '@triliumnext/backup-container':
+ specifier: workspace:*
+ version: link:../../packages/trilium-backup-container
'@triliumnext/commons':
specifier: workspace:*
version: link:../../packages/commons