Skip to content

Build your personal knowledge base with Trilium Notes

client/options/backup: show a native warning box before the stored passphrase changes, to prevent scripts to update the password

Adorian Doranedc290d36207
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index 9245f54054..00ae653036 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -167,7 +167,13 @@ export function BackupOptions() {
useEffect(() => { refreshPassphrase(); }, [refreshPassphrase]);
async function storePassword(password: string) {
- if (!await window.electronApi?.backupPassphrase.set(password)) {
+ const result = await window.electronApi?.backupPassphrase.set(password);
+
+ // Declined at the OS confirmation: the user has said no, which needs no telling back.
+ if (result === "cancelled") {
+ return;
+ }
+ if (result !== "applied") {
toast.showError(t("backup.password_not_stored"));
return;
}
@@ -182,9 +188,13 @@ export function BackupOptions() {
// and leaving it behind would mean a passphrase nobody remembers setting. Backups already written
// keep the one they were written with.
async function disableEncryption() {
- await window.electronApi?.backupPassphrase.clear();
- await setEncryptionEnabled(false);
+ const result = await window.electronApi?.backupPassphrase.clear();
+
+ // Re-read either way: a declined confirmation has to put the switch back where it was.
await refreshPassphrase();
+ if (result === "applied") {
+ await setEncryptionEnabled(false);
+ }
}
return (
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 2005eee604..b70c972211 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -1,4 +1,4 @@
-import type { BackupPassphraseStatus, ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";
+import type { BackupPassphraseChange, BackupPassphraseStatus, ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";
import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";
contextBridge.exposeInMainWorld("electronApi", {
@@ -297,10 +297,10 @@ contextBridge.exposeInMainWorld("electronApi", {
return ipcRenderer.invoke("backup-passphrase-status");
},
// No getter by design: the plaintext passphrase never comes back to the renderer.
- set(passphrase: string): Promise<boolean> {
+ set(passphrase: string): Promise<BackupPassphraseChange> {
return ipcRenderer.invoke("backup-passphrase-set", passphrase);
},
- clear(): Promise<void> {
+ clear(): Promise<BackupPassphraseChange> {
return ipcRenderer.invoke("backup-passphrase-clear");
}
},
diff --git a/apps/desktop/src/services/backup_passphrase.spec.ts b/apps/desktop/src/services/backup_passphrase.spec.ts
index 339e6746f3..c34c3c32cd 100644
--- a/apps/desktop/src/services/backup_passphrase.spec.ts
+++ b/apps/desktop/src/services/backup_passphrase.spec.ts
@@ -4,6 +4,7 @@ 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>(),
+ showMessageBox: vi.fn(async (_options: Record<string, unknown>) => ({ response: 1 })),
isReady: true,
encryptionAvailable: true,
storageBackend: "gnome_libsecret",
@@ -42,9 +43,12 @@ vi.mock("fs", async (importOriginal) => {
return { ...actual, default: patched, existsSync, readFileSync, writeFileSync, renameSync, rmSync };
});
+vi.mock("i18next", () => ({ t: (key: string) => key }));
+
vi.mock("electron", () => ({
default: {
app: { isReady: () => h.isReady },
+ dialog: { showMessageBox: h.showMessageBox },
safeStorage: {
isEncryptionAvailable: () => h.encryptionAvailable,
getSelectedStorageBackend: () => h.storageBackend,
@@ -168,12 +172,16 @@ describe("keyring availability", () => {
});
describe("IPC handlers", () => {
+ const invoke = (channel: string, ...args: unknown[]) => h.handlers.get(channel)?.({}, ...args);
+
beforeEach(() => {
h.fileStore.clear();
h.handlers.clear();
h.isReady = true;
h.encryptionAvailable = true;
h.storageBackend = "gnome_libsecret";
+ h.showMessageBox.mockClear();
+ h.showMessageBox.mockResolvedValue({ response: 1 });
passphrase.registerBackupPassphraseIpcHandlers();
});
@@ -186,13 +194,56 @@ describe("IPC handlers", () => {
});
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-set", "hunter2")).toBe("applied");
expect(await invoke("backup-passphrase-status")).toEqual({ available: true, set: true });
- await invoke("backup-passphrase-clear");
+ expect(await invoke("backup-passphrase-clear")).toBe("applied");
expect(await invoke("backup-passphrase-status")).toEqual({ available: true, set: false });
});
+
+ it.each([
+ ["set", ["backup-passphrase-set", "hunter2"]],
+ ["clear", ["backup-passphrase-clear"]]
+ ] as [string, [string, ...unknown[]]][])("asks the OS before it %ss, and offers no way to stop being asked", async (_label, call) => {
+ await invoke(...call);
+
+ expect(h.showMessageBox).toHaveBeenCalledOnce();
+ const options = h.showMessageBox.mock.calls[0][0];
+ expect(options).toMatchObject({ type: "warning", cancelId: 0 });
+ // The security settings offer "don't ask again"; skipping the question is the vulnerability here.
+ expect(options).not.toHaveProperty("checkboxLabel");
+ });
+
+ it("stores nothing when the confirmation is declined", async () => {
+ h.showMessageBox.mockResolvedValue({ response: 0 });
+
+ expect(await invoke("backup-passphrase-set", "hunter2")).toBe("cancelled");
+ expect(h.fileStore.size).toBe(0);
+ });
+
+ it("keeps the stored passphrase when a clear is declined", async () => {
+ await invoke("backup-passphrase-set", "hunter2");
+ h.showMessageBox.mockResolvedValue({ response: 0 });
+
+ expect(await invoke("backup-passphrase-clear")).toBe("cancelled");
+ expect(await invoke("backup-passphrase-status")).toEqual({ available: true, set: true });
+ });
+
+ it("does not ask about something it could not do anyway", async () => {
+ h.encryptionAvailable = false;
+
+ expect(await invoke("backup-passphrase-set", "hunter2")).toBe("unavailable");
+ expect(await invoke("backup-passphrase-set", "")).toBe("unavailable");
+ expect(h.showMessageBox).not.toHaveBeenCalled();
+ });
+
+ it("never asks when the OS rotates its key under a backup, which runs unattended", async () => {
+ await invoke("backup-passphrase-set", "hunter2");
+ h.showMessageBox.mockClear();
+ h.decrypt.mockResolvedValueOnce({ result: "hunter2", shouldReEncrypt: true });
+
+ expect(await passphrase.getBackupPassphrase()).toBe("hunter2");
+ expect(h.showMessageBox).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/services/backup_passphrase.ts b/apps/desktop/src/services/backup_passphrase.ts
index 29849b4abf..178e8b267e 100644
--- a/apps/desktop/src/services/backup_passphrase.ts
+++ b/apps/desktop/src/services/backup_passphrase.ts
@@ -1,8 +1,9 @@
-import type { BackupPassphraseStatus } from "@triliumnext/commons";
+import type { BackupPassphraseChange, 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 { t } from "i18next";
import path from "path";
/**
@@ -84,11 +85,52 @@ export async function getBackupPassphrase(): Promise<string | null> {
}
}
+/**
+ * Asks the user through the operating system, not through the app.
+ *
+ * A frontend script can reach the IPC channel behind this, but it cannot press a button in a window
+ * the OS drew, which is the whole point: without the question, a script could quietly replace the
+ * passphrase with one it knows and every later backup would be encrypted to it.
+ *
+ * Deliberately without the "don't ask again" escape the security settings offer. That exists there to
+ * stop a script from fatiguing the user through repetition; here the question is rare enough that
+ * being asked every time costs nothing, and skipping it is the whole vulnerability.
+ */
+async function confirmChange(action: "set" | "clear"): Promise<boolean> {
+ const { response } = await electron.dialog.showMessageBox({
+ type: "warning",
+ buttons: [t("backup-password-dialog.cancel"), t(`backup-password-dialog.${action}-confirm`)],
+ defaultId: 1,
+ cancelId: 0,
+ title: t(`backup-password-dialog.${action}-title`),
+ message: t(`backup-password-dialog.${action}-message`),
+ detail: t(`backup-password-dialog.${action}-detail`)
+ });
+
+ return response === 1;
+}
+
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-set", async (_event, passphrase: string): Promise<BackupPassphraseChange> => {
+ // Nothing to confirm when it could not be honoured anyway.
+ if (!isKeyringAvailable() || !passphrase) {
+ return "unavailable";
+ }
+ if (!await confirmChange("set")) {
+ return "cancelled";
+ }
+
+ return await storeBackupPassphrase(passphrase) ? "applied" : "unavailable";
+ });
+
+ electron.ipcMain.handle("backup-passphrase-clear", async (): Promise<BackupPassphraseChange> => {
+ if (!await confirmChange("clear")) {
+ return "cancelled";
+ }
+ clearBackupPassphrase();
- electron.ipcMain.handle("backup-passphrase-clear", (): void => clearBackupPassphrase());
+ return "applied";
+ });
}
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index f16cf54c74..fc738e9be4 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -478,6 +478,17 @@
"unrecognized-expression": "Unrecognized expression \"{{- token}}\""
}
},
+ "backup-password-dialog": {
+ "cancel": "Cancel",
+ "set-title": "Set the backup password?",
+ "set-message": "Future backups will be encrypted with this password.",
+ "set-detail": "Trilium cannot show this password again, so keep a copy somewhere safe: without it, a backup cannot be restored.\n\nIf you were not expecting to be asked, cancel — a note or a script may have requested this.",
+ "set-confirm": "Set password",
+ "clear-title": "Forget the backup password?",
+ "clear-message": "Backups will no longer be encrypted.",
+ "clear-detail": "Backups already written keep the password they were made with, and can still be restored with it.\n\nIf you were not expecting to be asked, cancel — a note or a script may have requested this.",
+ "clear-confirm": "Forget password"
+ },
"security-dialog": {
"enable-title": "Enable {{settingLabel}}",
"enable-message": "Are you sure you want to enable {{settingLabel}}?",
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 1d54ad5955..20d90814b7 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -503,6 +503,15 @@ export interface BackupPassphraseStatus {
set: boolean;
}
+/** What became of a request to change the stored backup passphrase. */
+export type BackupPassphraseChange =
+ /** The change was confirmed and carried out. */
+ | "applied"
+ /** The user declined the OS confirmation, so nothing changed. */
+ | "cancelled"
+ /** There is no keyring on this system to keep a passphrase in. */
+ | "unavailable";
+
/**
* 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
@@ -510,14 +519,18 @@ export interface BackupPassphraseStatus {
*
* 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.
+ *
+ * Both changes are also gated on a native OS confirmation, which a script can request but cannot
+ * answer. Without that, a script could quietly swap in a passphrase of its own and every later backup
+ * would be encrypted to it.
*/
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>;
+ /** Stores a passphrase, replacing any existing one, once the user has confirmed it. */
+ set(passphrase: string): Promise<BackupPassphraseChange>;
/** Forgets the stored passphrase. Existing backups keep the passphrase they were written with. */
- clear(): Promise<void>;
+ clear(): Promise<BackupPassphraseChange>;
}
/** Outcome of a {@link ElectronOneNoteApi.login} attempt. */