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
client/db: store the backup encryption/compression options and the passphrase
Adorian Doran2c1379576b28
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex eeaa222a2b..6aa1859a8f 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -32,6 +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 { setupOneNoteHandlers } from "./services/onenote";import { setupPrintingHandlers } from "./services/printing";import ElectronRequestProvider from "./services/request";@@ -132,6 +133,7 @@ export async function main() {setupImportHandlers();setupDialogHandlers();registerSecurityIpcHandlers();+ registerBackupPassphraseIpcHandlers();setupStartupMetricsIpc();app.on("will-quit", () => {diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 4d6f305f2a..a46e80726f 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -611,6 +611,29 @@ describe("preload script", () => {});});+ describe("backupPassphrase", () => {+ const backupPassphrase = () => getGroup("backupPassphrase");++ it("getStatus invokes the corresponding IPC channel", async () => {+ await backupPassphrase().getStatus();+ expect(ipcRendererInvoked).toContainEqual({ channel: "backup-passphrase-status", args: [] });+ });++ it("set invokes the corresponding IPC channel", async () => {+ await backupPassphrase().set("hunter2");+ expect(ipcRendererInvoked).toContainEqual({ channel: "backup-passphrase-set", args: ["hunter2"] });+ });++ it("clear invokes the corresponding IPC channel", async () => {+ await backupPassphrase().clear();+ expect(ipcRendererInvoked).toContainEqual({ channel: "backup-passphrase-clear", args: [] });+ });++ it("exposes no way to read the passphrase back", () => {+ expect(Object.keys(backupPassphrase()).sort()).toEqual(["clear", "getStatus", "set"]);+ });+ });+describe("onenote", () => {const onenote = () => getGroup("onenote");diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex d668e1ffbe..2005eee604 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,4 +1,4 @@-import type { ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";+import type { BackupPassphraseStatus, ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";contextBridge.exposeInMainWorld("electronApi", {@@ -292,6 +292,19 @@ contextBridge.exposeInMainWorld("electronApi", {}},+ backupPassphrase: {+ getStatus(): Promise<BackupPassphraseStatus> {+ return ipcRenderer.invoke("backup-passphrase-status");+ },+ // No getter by design: the plaintext passphrase never comes back to the renderer.+ set(passphrase: string): Promise<boolean> {+ return ipcRenderer.invoke("backup-passphrase-set", passphrase);+ },+ clear(): Promise<void> {+ return ipcRenderer.invoke("backup-passphrase-clear");+ }+ },+onenote: {login(): Promise<OneNoteLoginResult> {return ipcRenderer.invoke("onenote-login");diff --git a/apps/desktop/src/services/backup_passphrase.spec.ts b/apps/desktop/src/services/backup_passphrase.spec.tsnew file mode 100644index 0000000000..339e6746f3--- /dev/null+++ b/apps/desktop/src/services/backup_passphrase.spec.ts@@ -0,0 +1,198 @@+import type fs from "fs";+import { beforeEach, describe, expect, it, vi } from "vitest";++const h = vi.hoisted(() => ({+ fileStore: new Map<string, Buffer>(),+ handlers: new Map<string, (event: unknown, ...args: unknown[]) => unknown>(),+ isReady: true,+ encryptionAvailable: true,+ storageBackend: "gnome_libsecret",+ platform: "linux",+ // Base64 rather than a readable prefix, so "never stored in the clear" is a real assertion.+ encrypt: vi.fn(async (plainText: string) => Buffer.from(Buffer.from(plainText, "utf8").toString("base64"), "utf8")),+ decrypt: vi.fn(async (buffer: Buffer) => ({+ result: Buffer.from(buffer.toString("utf8"), "base64").toString("utf8"),+ shouldReEncrypt: false+ })),+ errors: [] as string[]+}));++// In-memory shim for the passphrase file only, so the developer's real data directory is untouched.+const isPassphrasePath = (p: unknown) => String(p).includes("backup-passphrase.bin");+vi.mock("fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("fs") & { default?: typeof import("fs") }>();+ const real = actual.default ?? actual;+ const existsSync = (p: fs.PathLike) => (isPassphrasePath(p) ? h.fileStore.has(String(p)) : real.existsSync(p));+ const readFileSync = ((p: fs.PathLike, enc?: unknown) =>+ isPassphrasePath(p) ? h.fileStore.get(String(p)) : real.readFileSync(p, enc as never)) as typeof real.readFileSync;+ const writeFileSync = ((p: fs.PathLike, data: Buffer) => {+ h.fileStore.set(String(p), Buffer.from(data));+ }) as typeof real.writeFileSync;+ const renameSync = ((from: fs.PathLike, to: fs.PathLike) => {+ const data = h.fileStore.get(String(from));+ if (data) {+ h.fileStore.set(String(to), data);+ h.fileStore.delete(String(from));+ }+ }) as typeof real.renameSync;+ const rmSync = ((p: fs.PathLike) => {+ h.fileStore.delete(String(p));+ }) as typeof real.rmSync;+ const patched = { ...real, existsSync, readFileSync, writeFileSync, renameSync, rmSync };+ return { ...actual, default: patched, existsSync, readFileSync, writeFileSync, renameSync, rmSync };+});++vi.mock("electron", () => ({+ default: {+ app: { isReady: () => h.isReady },+ safeStorage: {+ isEncryptionAvailable: () => h.encryptionAvailable,+ getSelectedStorageBackend: () => h.storageBackend,+ encryptStringAsync: (plainText: string) => h.encrypt(plainText),+ decryptStringAsync: (buffer: Buffer) => h.decrypt(buffer)+ },+ ipcMain: {+ handle(channel: string, handler: (event: unknown, ...args: unknown[]) => unknown) {+ h.handlers.set(channel, handler);+ }+ }+ }+}));++vi.mock("@triliumnext/core", () => ({+ getLog: () => ({ error: (message: string) => h.errors.push(message) })+}));++const passphrase = await import("./backup_passphrase.js");++describe("backup passphrase storage", () => {+ beforeEach(() => {+ h.fileStore.clear();+ h.errors.length = 0;+ h.isReady = true;+ h.encryptionAvailable = true;+ h.storageBackend = "gnome_libsecret";+ Object.defineProperty(process, "platform", { value: h.platform, configurable: true });+ h.decrypt.mockClear();+ h.encrypt.mockClear();+ });++ it("stores a passphrase encrypted, and never in the clear", async () => {+ expect(await passphrase.storeBackupPassphrase("hunter2")).toBe(true);++ const stored = [...h.fileStore.values()];+ expect(stored).toHaveLength(1);+ expect(stored[0].toString()).not.toContain("hunter2");+ expect(h.encrypt).toHaveBeenCalledWith("hunter2");+ expect(await passphrase.getBackupPassphrase()).toBe("hunter2");+ });++ it("replaces an existing passphrase rather than accumulating files", async () => {+ await passphrase.storeBackupPassphrase("first");+ await passphrase.storeBackupPassphrase("second");++ expect(h.fileStore.size).toBe(1);+ expect(await passphrase.getBackupPassphrase()).toBe("second");+ });++ it("reports status without disclosing anything", () => {+ expect(passphrase.getBackupPassphraseStatus()).toEqual({ available: true, set: false });+ });++ it("forgets the passphrase on clear", async () => {+ await passphrase.storeBackupPassphrase("hunter2");+ passphrase.clearBackupPassphrase();++ expect(passphrase.isPassphraseSet()).toBe(false);+ expect(await passphrase.getBackupPassphrase()).toBeNull();+ });++ it("rewrites the file when the OS says its key rotated", async () => {+ await passphrase.storeBackupPassphrase("hunter2");+ h.decrypt.mockResolvedValueOnce({ result: "hunter2", shouldReEncrypt: true });+ h.encrypt.mockClear();++ expect(await passphrase.getBackupPassphrase()).toBe("hunter2");+ expect(h.encrypt).toHaveBeenCalledWith("hunter2");+ });++ it("returns null and logs, without the passphrase, when the blob cannot be decrypted", async () => {+ await passphrase.storeBackupPassphrase("hunter2");+ h.decrypt.mockRejectedValueOnce(new Error("keyring is locked"));++ expect(await passphrase.getBackupPassphrase()).toBeNull();+ expect(h.errors.join()).toContain("keyring is locked");+ expect(h.errors.join()).not.toContain("hunter2");+ });+});++describe("keyring availability", () => {+ beforeEach(() => {+ h.fileStore.clear();+ h.isReady = true;+ h.encryptionAvailable = true;+ h.storageBackend = "gnome_libsecret";+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });+ });++ it.each([+ ["the app is not ready yet", () => { h.isReady = false; }],+ ["the platform offers no encryption", () => { h.encryptionAvailable = false; }],+ ["Linux falls back to the hardcoded-password backend", () => { h.storageBackend = "basic_text"; }]+ ])("treats the keyring as unavailable when %s", async (_label, arrange) => {+ arrange();++ expect(passphrase.isKeyringAvailable()).toBe(false);+ expect(await passphrase.storeBackupPassphrase("hunter2")).toBe(false);+ expect(h.fileStore.size).toBe(0);+ });++ it("ignores the backend name away from Linux, where it is not reported", () => {+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });+ h.storageBackend = "basic_text";++ expect(passphrase.isKeyringAvailable()).toBe(true);+ });++ it("refuses an empty passphrase", async () => {+ expect(await passphrase.storeBackupPassphrase("")).toBe(false);+ expect(h.fileStore.size).toBe(0);+ });++ it("cannot read a stored passphrase once the keyring goes away", async () => {+ await passphrase.storeBackupPassphrase("hunter2");+ h.encryptionAvailable = false;++ expect(await passphrase.getBackupPassphrase()).toBeNull();+ });+});++describe("IPC handlers", () => {+ beforeEach(() => {+ h.fileStore.clear();+ h.handlers.clear();+ h.isReady = true;+ h.encryptionAvailable = true;+ h.storageBackend = "gnome_libsecret";+ passphrase.registerBackupPassphraseIpcHandlers();+ });++ it("registers status, set and clear, and nothing that reads the passphrase back", () => {+ expect([...h.handlers.keys()].sort()).toEqual([+ "backup-passphrase-clear",+ "backup-passphrase-set",+ "backup-passphrase-status"+ ]);+ });++ it("drives the whole lifecycle over IPC", async () => {+ const invoke = (channel: string, ...args: unknown[]) => h.handlers.get(channel)?.({}, ...args);++ expect(await invoke("backup-passphrase-status")).toEqual({ available: true, set: false });+ expect(await invoke("backup-passphrase-set", "hunter2")).toBe(true);+ expect(await invoke("backup-passphrase-status")).toEqual({ available: true, set: true });++ await invoke("backup-passphrase-clear");+ expect(await invoke("backup-passphrase-status")).toEqual({ available: true, set: false });+ });+});diff --git a/apps/desktop/src/services/backup_passphrase.ts b/apps/desktop/src/services/backup_passphrase.tsnew file mode 100644index 0000000000..29849b4abf--- /dev/null+++ b/apps/desktop/src/services/backup_passphrase.ts@@ -0,0 +1,94 @@+import type { BackupPassphraseStatus } from "@triliumnext/commons";+import { getLog } from "@triliumnext/core";+import dataDirs from "@triliumnext/server/src/services/data_dir.js";+import electron from "electron";+import fs from "fs";+import path from "path";++/**+ * The passphrase lives outside the database on purpose: the database is what a backup wraps, so a+ * passphrase kept there would travel inside the very container it protects, and would sync to every+ * other instance besides.+ */+const PASSPHRASE_PATH = path.join(dataDirs.TRILIUM_DATA_DIR, "backup-passphrase.bin");+const TEMP_PATH = `${PASSPHRASE_PATH}.tmp`;++/**+ * Whether the OS has somewhere safe to keep the passphrase.+ *+ * `isEncryptionAvailable()` alone is not enough. On Linux without a keyring the selected backend is+ * `basic_text`, which "encrypts" with a hardcoded password, so the file would be plaintext in all but+ * name. Both that and the backend name are only meaningful once the app is ready.+ */+export function isKeyringAvailable(): boolean {+ if (!electron.app.isReady() || !electron.safeStorage.isEncryptionAvailable()) {+ return false;+ }++ return process.platform !== "linux" || electron.safeStorage.getSelectedStorageBackend() !== "basic_text";+}++export function isPassphraseSet(): boolean {+ return fs.existsSync(PASSPHRASE_PATH);+}++export function getBackupPassphraseStatus(): BackupPassphraseStatus {+ return { available: isKeyringAvailable(), set: isPassphraseSet() };+}++/** Stores a passphrase, replacing any existing one. Returns `false` when there is no keyring to use. */+export async function storeBackupPassphrase(passphrase: string): Promise<boolean> {+ if (!isKeyringAvailable() || !passphrase) {+ return false;+ }++ const encrypted = await electron.safeStorage.encryptStringAsync(passphrase);++ // Written aside and renamed, so a crash cannot leave a half-written blob that reads as a+ // corrupted passphrase and silently turns off encryption on the next backup.+ fs.writeFileSync(TEMP_PATH, encrypted, { mode: 0o600 });+ fs.renameSync(TEMP_PATH, PASSPHRASE_PATH);++ return true;+}++export function clearBackupPassphrase(): void {+ fs.rmSync(PASSPHRASE_PATH, { force: true });+}++/**+ * Reads the passphrase back, for the main process alone. Never reachable from the renderer.+ *+ * Returns `null` when there is nothing stored, or when the blob cannot be decrypted — which happens+ * when the keyring is locked, or when the data directory was copied from another machine, since the+ * ciphertext is bound to the user account that wrote it.+ */+export async function getBackupPassphrase(): Promise<string | null> {+ if (!isPassphraseSet() || !isKeyringAvailable()) {+ return null;+ }++ try {+ const { result, shouldReEncrypt } = await electron.safeStorage.decryptStringAsync(fs.readFileSync(PASSPHRASE_PATH));++ // The OS rotated its key underneath us; rewrite now or the blob eventually stops decrypting.+ if (shouldReEncrypt) {+ await storeBackupPassphrase(result);+ }++ return result;+ } catch (e) {+ // The reason reaches the log, the passphrase never does.+ getLog().error(`Could not read the stored backup passphrase: ${e instanceof Error ? e.message : String(e)}`);+ return null;+ }+}++export function registerBackupPassphraseIpcHandlers(): void {+ electron.ipcMain.handle("backup-passphrase-status", (): BackupPassphraseStatus => getBackupPassphraseStatus());++ electron.ipcMain.handle("backup-passphrase-set", (_event, passphrase: string): Promise<boolean> =>+ storeBackupPassphrase(passphrase));++ electron.ipcMain.handle("backup-passphrase-clear", (): void => clearBackupPassphrase());+}diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 613b9e8005..1d54ad5955 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -492,6 +492,34 @@ export interface ElectronSecurityApi {setLanAccessEnabled(enabled: boolean): Promise<boolean>;}+/** What the Options UI needs to know about the stored backup passphrase. */+export interface BackupPassphraseStatus {+ /**+ * Whether the OS offers a keyring to keep the passphrase in. Without one it cannot be stored+ * safely, and since unattended backups cannot ask for it, encryption is unavailable altogether.+ */+ available: boolean;+ /** Whether a passphrase is currently stored. */+ set: boolean;+}++/**+ * The backup passphrase, kept encrypted by the OS keyring in a file outside the database (the database+ * is what ends up inside the backup, so a passphrase stored there would ride along inside the very+ * container it protects).+ *+ * Deliberately write-only: there is no way to read the passphrase back, so a frontend script cannot+ * exfiltrate it. Only the main process ever sees the plaintext again, when it writes a backup.+ */+export interface ElectronBackupPassphraseApi {+ /** Whether a passphrase can be stored on this system, and whether one already is. */+ getStatus(): Promise<BackupPassphraseStatus>;+ /** Stores a passphrase, replacing any existing one. Returns `false` when the OS has no keyring. */+ set(passphrase: string): Promise<boolean>;+ /** Forgets the stored passphrase. Existing backups keep the passphrase they were written with. */+ clear(): Promise<void>;+}+/** Outcome of a {@link ElectronOneNoteApi.login} attempt. */export interface OneNoteLoginResult {/** True if sign-in completed and a Microsoft Graph token was stored. */@@ -645,6 +673,8 @@ export interface ElectronApi {ws: ElectronWsApi;/** Security settings (backend scripting, SQL console) stored outside the DB. */security: ElectronSecurityApi;+ /** Write-only access to the backup passphrase, kept in the OS keyring. */+ backupPassphrase: ElectronBackupPassphraseApi;/** OneNote importer sign-in via a loopback OAuth redirect (desktop only). */onenote: ElectronOneNoteApi;/** Desktop-native subtree export that streams a `.zip` straight to a file. */diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 8a08fcd590..278e13e9a1 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -191,6 +191,16 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActidailyBackupEnabled: boolean;weeklyBackupEnabled: boolean;monthlyBackupEnabled: boolean;+ /**+ * Whether backups are gzip-compressed. Compression or encryption switches the backup from a plain+ * database file to a backup container; with both off, backups stay plain `.db` copies.+ */+ backupEnableCompression: boolean;+ /**+ * Whether backups are encrypted with the stored backup passphrase. Desktop only, and only where the+ * OS offers a keyring to keep that passphrase in, since unattended backups cannot ask for it.+ */+ backupEnableEncryption: boolean;compressImages: boolean;/*** Whether an image above {@link imageMaxWidthHeight} is scaled down on its way in. Off, thediff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 9c4210be24..9ba8cebe39 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -91,6 +91,8 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["weeklyBackupEnabled","monthlyBackupEnabled","customDbBackupDir",+ "backupEnableCompression",+ "backupEnableEncryption","motionEnabled","shadowsEnabled","smoothScrollEnabled",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex f047ed1a79..ae8e6865bd 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -211,6 +211,8 @@ const defaultOptions: DefaultOption[] = [{ name: "weeklyBackupEnabled", value: "true", isSynced: false },{ name: "monthlyBackupEnabled", value: "true", isSynced: false },{ name: "customDbBackupDir", value: "", isSynced: false },+ { name: "backupEnableCompression", value: "false", isSynced: false },+ { name: "backupEnableEncryption", value: "false", isSynced: false },{ name: "maxContentWidth", value: "1200", isSynced: false },{ name: "centerContent", value: "false", isSynced: false },{ name: "compressImages", value: "true", isSynced: true },