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/options/backup: add a UI to configure backup encryption/compression and the passphrase
Adorian Doran7e45b518ea78
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 8c364cedfa..49b442b6ec 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2039,7 +2039,25 @@"path": "Path","database_backed_up_to": "Database has been backed up to {{- backupFilePath}}","no_backup_yet": "no backup yet",- "download": "Download"+ "download": "Download",+ "options_title": "Backup options",+ "enable_compression": "Enable compression",+ "enable_compression_description": "Makes each backup considerably smaller, at the cost of some time while it is written.",+ "enable_encryption": "Enable encryption",+ "enable_encryption_description": "Locks each backup with a password of your own, so that nobody else can read it. Worth turning on when backups are written to a synced folder.",+ "no_keyring": "A keyring is not available in your system. That means the password cannot be securely stored, so encrypting backups is not available.",+ "turn_on_encryption": "Turn on encryption",+ "change_password": "Change password",+ "password_modal_title": "Backup password",+ "password_modal_description": "Keep a copy of this password somewhere safe. Trilium cannot show it again, and without it a backup cannot be restored.",+ "save_password": "Save password",+ "password_stored": "The backup password has been saved.",+ "password_not_stored": "The backup password could not be saved."+ },+ "password_with_confirmation": {+ "password": "Password",+ "repeat_password": "Repeat password",+ "mismatch": "The passwords do not match."},"open": {"directory_failed": "Could not open {{- directory}}: {{- reason}}"diff --git a/apps/client/src/widgets/dialogs/OptionsDialog.css b/apps/client/src/widgets/dialogs/OptionsDialog.cssindex 2f1d782a4e..22abcbac46 100644--- a/apps/client/src/widgets/dialogs/OptionsDialog.css+++ b/apps/client/src/widgets/dialogs/OptionsDialog.css@@ -1,22 +1,33 @@-body.desktop .modal.options-dialog .modal-dialog {+/*+ * A dialog opened from within the settings (a password prompt, say) is nested in this dialog's own+ * markup, so a descendant selector here would lay it out like the settings themselves: full height,+ * no padding, its header floated away. Every rule that shapes the dialog frame is therefore written+ * against this dialog's own parts, down the child chain.+ *+ * The chain forks once: with a sidebar the body sits inside `.modal-main`, without one it is a direct+ * child of `.modal-content`. Both forms are listed where it matters.+ */++body.desktop .modal.options-dialog > .modal-dialog {max-width: min(1300px, 75vw);}/* Keep the sidebar background within the rounded corners. */-.modal.options-dialog .modal-content {+.modal.options-dialog > .modal-dialog > .modal-content {overflow: hidden;}-.modal.options-dialog .modal-body {+.modal.options-dialog > .modal-dialog > .modal-content > .modal-main > .modal-body,+.modal.options-dialog > .modal-dialog > .modal-content > .modal-body {padding: 0;height: 75vh;}-.modal.options-dialog .modal-sidebar {+.modal.options-dialog > .modal-dialog > .modal-content > .modal-sidebar {background-color: var(--card-background-color);}-.modal.options-dialog .modal-sidebar .settings-navigation {+.modal.options-dialog > .modal-dialog > .modal-content > .modal-sidebar .settings-navigation {flex: 1 1 0;min-height: 0;overflow: auto;@@ -26,7 +37,7 @@ body.desktop .modal.options-dialog .modal-dialog {/* The main header only carries the window (maximize/close) buttons, with the title moved into thesidebar. Float it over the content so it doesn't leave a tall empty band at the top. */-body.desktop .modal.options-dialog .modal-main > .modal-header {+body.desktop .modal.options-dialog > .modal-dialog > .modal-content > .modal-main > .modal-header {position: absolute;top: 0;right: 4px;@@ -39,7 +50,8 @@ body.desktop .modal.options-dialog .modal-main > .modal-header {/* The dialog fills the full mobile page (isFullPageOnMobile), so the body stretches instead ofusing the fixed desktop height. Applies to both the master-detail and the tablet layout. */-body.mobile .modal.options-dialog .modal-body {+body.mobile .modal.options-dialog > .modal-dialog > .modal-content > .modal-main > .modal-body,+body.mobile .modal.options-dialog > .modal-dialog > .modal-content > .modal-body {height: auto;flex: 1 1 auto;}@@ -47,11 +59,11 @@ body.mobile .modal.options-dialog .modal-body {/* On wider mobile viewports (tablets) the dialog keeps the desktop-style sidebar layout; undo thegeneric bottom-strip arrangement that style.css applies to sidebar modals on mobile. The sidebaronly exists outside the master-detail flow, so no extra scoping is needed. */-body.mobile .modal.options-dialog .modal-content-with-sidebar {+body.mobile .modal.options-dialog > .modal-dialog > .modal-content-with-sidebar {flex-direction: row !important;}-body.mobile .modal.options-dialog .modal-content-with-sidebar > .modal-sidebar {+body.mobile .modal.options-dialog > .modal-dialog > .modal-content-with-sidebar > .modal-sidebar {order: 0;height: auto;border-right: 1px solid var(--main-border-color);@@ -59,7 +71,7 @@ body.mobile .modal.options-dialog .modal-content-with-sidebar > .modal-sidebar {}/* On tablets, don't take up the full page height like the master-detail flow does. */-body.mobile .modal.options-dialog:not(.mobile-master-detail) .modal-dialog {+body.mobile .modal.options-dialog:not(.mobile-master-detail) > .modal-dialog {height: 90vh;}@@ -76,7 +88,8 @@ body.mobile .modal.options-dialog.mobile-master-detail {}}-body.mobile .modal.options-dialog .modal-header {+body.mobile .modal.options-dialog > .modal-dialog > .modal-content > .modal-main > .modal-header,+body.mobile .modal.options-dialog > .modal-dialog > .modal-content > .modal-header {border-bottom: 1px solid var(--main-border-color);}diff --git a/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsx b/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsxnew file mode 100644index 0000000000..c29217837f--- /dev/null+++ b/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsx@@ -0,0 +1,92 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++// i18next is not initialised under test, where `t` answers undefined; echoing the key back keeps the+// rendered strings truthy and lets the assertions name the keys the component is expected to use.+vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));++import FormPasswordWithConfirmation from "./FormPasswordWithConfirmation";++describe("FormPasswordWithConfirmation", () => {+ it("reports the password only once both fields agree", () => {+ const { password, confirmation, onChange } = renderFields();++ type(password, "hunter2");+ expect(onChange).toHaveBeenLastCalledWith(null);++ type(confirmation, "hunter");+ expect(onChange).toHaveBeenLastCalledWith(null);++ type(confirmation, "hunter2");+ expect(onChange).toHaveBeenLastCalledWith("hunter2");+ });++ it("withdraws the password again when the fields stop agreeing", () => {+ const { password, confirmation, onChange } = renderFields();++ type(password, "hunter2");+ type(confirmation, "hunter2");+ expect(onChange).toHaveBeenLastCalledWith("hunter2");++ type(password, "hunter3");+ expect(onChange).toHaveBeenLastCalledWith(null);+ });++ it("never reports an empty password, even when both fields are empty", () => {+ const { password, confirmation, onChange } = renderFields();++ type(password, "a");+ type(password, "");+ type(confirmation, "");++ expect(onChange).not.toHaveBeenCalledWith("");+ expect(onChange).toHaveBeenLastCalledWith(null);+ });++ it("states the mismatch on the second field, and stops once it is resolved", () => {+ const { container, password, confirmation } = renderFields();++ type(password, "hunter2");+ type(confirmation, "hunter");+ expect(container.querySelector(".text-danger")?.textContent).toBe("password_with_confirmation.mismatch");++ type(confirmation, "hunter2");+ expect(container.querySelector(".text-danger")).toBeNull();+ });++ it("says nothing while the confirmation is still empty", () => {+ const { container, password } = renderFields();++ type(password, "hunter2");++ expect(container.querySelector(".text-danger")).toBeNull();+ });++ it("masks both fields", () => {+ const { password, confirmation } = renderFields();++ expect(password.type).toBe("password");+ expect(confirmation.type).toBe("password");+ });+});++function renderFields() {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const onChange = vi.fn();++ act(() => render(<FormPasswordWithConfirmation onChange={onChange} />, container));++ const inputs = [...container.querySelectorAll("input")];++ return { container, onChange, password: inputs[0], confirmation: inputs[1] };+}++/** Typing, then flushing, since the value only reaches the host through an effect. */+function type(input: HTMLInputElement, value: string) {+ act(() => {+ input.value = value;+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+}diff --git a/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsx b/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsxnew file mode 100644index 0000000000..cac86dd40a--- /dev/null+++ b/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsx@@ -0,0 +1,67 @@+import type { RefObject } from "preact";+import { useEffect, useRef, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import FormGroup from "./FormGroup";+import FormTextBox from "./FormTextBox";++export interface FormPasswordWithConfirmationProps {+ /** Label of the first field. Defaults to a plain "Password". */+ label?: string;+ /** Label of the second field. Defaults to a plain "Repeat password". */+ confirmationLabel?: string;+ /** Focus target, for a host that wants the first field focused when it opens. */+ inputRef?: RefObject<HTMLInputElement>;+ /**+ * Receives the password once both fields agree and neither is empty, and `null` at every other+ * moment. A host enables its confirm action on a non-null value and needs no validation of its own.+ */+ onChange(password: string | null): void;+}++/**+ * A password and its confirmation, for choosing a password rather than entering a known one.+ *+ * The pair reports one value rather than two, so what a host has to reason about is "is there a+ * password yet", not which of the two fields is behind. The mismatch is stated on the second field,+ * where it is caused.+ */+export default function FormPasswordWithConfirmation({ label, confirmationLabel, inputRef, onChange }: FormPasswordWithConfirmationProps) {+ const [password, setPassword] = useState("");+ const [confirmation, setConfirmation] = useState("");++ // Held in a ref so an inline callback does not re-run the effect on every render of the host.+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;++ useEffect(() => {+ onChangeRef.current(password.length > 0 && password === confirmation ? password : null);+ }, [password, confirmation]);++ return (+ <>+ <FormGroup name="password" label={label ?? t("password_with_confirmation.password")}>+ <FormTextBox+ inputRef={inputRef}+ type="password"+ autoComplete="new-password"+ currentValue={password}+ onChange={setPassword}+ />+ </FormGroup>++ <FormGroup+ name="password-confirmation"+ label={confirmationLabel ?? t("password_with_confirmation.repeat_password")}+ error={confirmation.length > 0 && password !== confirmation ? t("password_with_confirmation.mismatch") : undefined}+ >+ <FormTextBox+ type="password"+ autoComplete="new-password"+ currentValue={confirmation}+ onChange={setConfirmation}+ />+ </FormGroup>+ </>+ );+}diff --git a/apps/client/src/widgets/react/Modal.spec.tsx b/apps/client/src/widgets/react/Modal.spec.tsxnew file mode 100644index 0000000000..725a8c7056--- /dev/null+++ b/apps/client/src/widgets/react/Modal.spec.tsx@@ -0,0 +1,67 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++import Modal from "./Modal";++/**+ * Bootstrap's modal events are native events, so they bubble, and a modal opened from inside another+ * one is a DOM descendant of it. The listeners must therefore answer only for their own element.+ */+describe("Modal stacking", () => {+ it("does not report a nested modal's closing as its own", () => {+ const { outer, inner, onOuterHidden, onInnerHidden } = renderNested();++ fire(inner, "hidden.bs.modal");++ expect(onInnerHidden).toHaveBeenCalledOnce();+ expect(onOuterHidden).not.toHaveBeenCalled();++ fire(outer, "hidden.bs.modal");+ expect(onOuterHidden).toHaveBeenCalledOnce();+ });++ it("does not report a nested modal's opening as its own", () => {+ const { inner, onOuterShown, onInnerShown } = renderNested();++ fire(inner, "shown.bs.modal");++ expect(onInnerShown).toHaveBeenCalledOnce();+ expect(onOuterShown).not.toHaveBeenCalled();+ });+});++function renderNested() {+ const container = document.createElement("div");+ document.body.appendChild(container);++ const onOuterHidden = vi.fn();+ const onInnerHidden = vi.fn();+ const onOuterShown = vi.fn();+ const onInnerShown = vi.fn();++ // Kept in the DOM while hidden, so the pair is nested without Bootstrap having to run.+ act(() => render(+ <Modal className="outer-modal" size="lg" title="Outer" show={false} keepInDom onHidden={onOuterHidden} onShown={onOuterShown}>+ <Modal className="inner-modal" size="sm" title="Inner" show={false} keepInDom stackable onHidden={onInnerHidden} onShown={onInnerShown}>+ inner body+ </Modal>+ </Modal>,+ container+ ));++ const outer = container.querySelector<HTMLElement>(".outer-modal");+ const inner = container.querySelector<HTMLElement>(".inner-modal");+ if (!outer || !inner) {+ throw new Error("both modals should be in the DOM");+ }+ expect(outer.contains(inner)).toBe(true);++ return { outer, inner, onOuterHidden, onInnerHidden, onOuterShown, onInnerShown };+}++function fire(element: HTMLElement, type: string) {+ act(() => {+ element.dispatchEvent(new CustomEvent(type, { bubbles: true }));+ });+}diff --git a/apps/client/src/widgets/react/Modal.tsx b/apps/client/src/widgets/react/Modal.tsxindex 651cb32dac..7464076a03 100644--- a/apps/client/src/widgets/react/Modal.tsx+++ b/apps/client/src/widgets/react/Modal.tsx@@ -116,21 +116,33 @@ export default function Modal({ children, className, size, title, customTitleBarconst modalElement = modalRef.current;if (!modalElement) return;- if (onShown) {- modalElement.addEventListener("shown.bs.modal", onShown);- }+ /*+ * Bootstrap's modal events are native events, and native events bubble. A stacked modal is a+ * DOM descendant of the one it opened over, so without this its opening and closing would be+ * reported to every modal underneath as their own — closing the Options dialog the moment a+ * dialog opened from inside it is dismissed.+ */+ const ownEvent = (handler: () => void) => (event: Event) => {+ if (event.target === modalElement) {+ handler();+ }+ };- function onModalHidden() {+ const onModalShown = onShown && ownEvent(onShown);+ const onModalHidden = ownEvent(() => {onHidden();if (elementToFocus.current && "focus" in elementToFocus.current) {(elementToFocus.current as HTMLElement).focus();}- }+ });+ if (onModalShown) {+ modalElement.addEventListener("shown.bs.modal", onModalShown);+ }modalElement.addEventListener("hidden.bs.modal", onModalHidden);return () => {- if (onShown) {- modalElement.removeEventListener("shown.bs.modal", onShown);+ if (onModalShown) {+ modalElement.removeEventListener("shown.bs.modal", onModalShown);}modalElement.removeEventListener("hidden.bs.modal", onModalHidden);};diff --git a/apps/client/src/widgets/type_widgets/options/backup.css b/apps/client/src/widgets/type_widgets/options/backup.cssindex 3e39baa2c2..b7e908af5c 100644--- a/apps/client/src/widgets/type_widgets/options/backup.css+++ b/apps/client/src/widgets/type_widgets/options/backup.css@@ -1,3 +1,38 @@+/* Bootstrap's small modal (300px) is cramped for two fields and the sentence above them. */+.modal.backup-password-modal > .modal-dialog {+ --bs-modal-width: 400px;+}++/* One row per setting: what it is on the leading edge, what switches it on the trailing one. */+.backup-options-row {+ display: flex;+ align-items: center;+ gap: 8px;++ /* The controls keep their natural width. Left to shrink, a button's nowrap label spills across+ its own padding and ends up reading as though it had none; the label below gives instead. */+ > * {+ flex-shrink: 0;+ }++ .backup-options-label {+ display: flex;+ flex: 1 1 auto;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }++ .backup-options-description {+ font-size: .85em;+ opacity: .7;+ }++ .btn {+ white-space: nowrap;+ }+}+.backup-location .tn-card-section {display: grid;grid-template-columns: auto 1fr auto;diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsxindex f6af73f91e..ce375f2c8f 100644--- a/apps/client/src/widgets/type_widgets/options/backup.tsx+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx@@ -1,7 +1,7 @@import "./backup.css";-import { BackupDatabaseNowResponse, DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commons";-import { useCallback, useEffect, useState } from "preact/hooks";+import { BackupDatabaseNowResponse, BackupPassphraseStatus, DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commons";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import dialogService from "../../../services/dialog";import { t } from "../../../services/i18n";@@ -11,8 +11,12 @@ import { isElectron } from "../../../services/utils";import Button from "../../react/Button";import { Card, CardSection } from "../../react/Card";import DirectoryLink from "../../react/DirectoryLink";+import FormPasswordWithConfirmation from "../../react/FormPasswordWithConfirmation";+import FormText from "../../react/FormText";+import FormToggle from "../../react/FormToggle";import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import Icon from "../../react/Icon";+import Modal from "../../react/Modal";import DatabaseFileList, { type DatabaseFile } from "./components/DatabaseFileList";import OptionsPageHeader from "./components/OptionsPageHeader";import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";@@ -37,6 +41,8 @@ export default function BackupSettings() {<BackupConfiguration />{/* Absent where there is no user-accessible location at all, e.g. backups kept in OPFS. */}{backupFolderPath && <BackupLocation backupFolderPath={backupFolderPath} refreshCallback={refreshBackups} />}+ {/* Desktop only: the passphrase needs an OS keyring to live in, which only the desktop has. */}+ {isElectron() && <BackupOptions />}<BackupList backups={backups} backupFolderPath={backupFolderPath} refreshCallback={refreshBackups} /></>);@@ -137,6 +143,129 @@ export function BackupLocation({ backupFolderPath, refreshCallback }: { backupFo);}+/**+ * What a backup is written as: a plain database copy, or a backup container that is compressed,+ * encrypted, or both.+ *+ * Encryption hangs off a passphrase the OS keyring holds, so the controls follow what that keyring+ * can do. Without one there is nowhere safe to keep the passphrase, and an unattended backup cannot+ * ask for it, so the whole feature is unavailable rather than half-working.+ */+export function BackupOptions() {+ const [compressionEnabled, setCompressionEnabled] = useTriliumOptionBool("backupEnableCompression");+ const [encryptionEnabled, setEncryptionEnabled] = useTriliumOptionBool("backupEnableEncryption");+ const [passphrase, setPassphrase] = useState<BackupPassphraseStatus>({ available: false, set: false });+ const [passwordModalShown, setPasswordModalShown] = useState(false);++ const refreshPassphrase = useCallback(async () => {+ const status = await window.electronApi?.backupPassphrase.getStatus();+ if (status) {+ setPassphrase(status);+ }+ }, []);++ useEffect(() => { refreshPassphrase(); }, [refreshPassphrase]);++ async function storePassword(password: string) {+ if (!await window.electronApi?.backupPassphrase.set(password)) {+ toast.showError(t("backup.password_not_stored"));+ return;+ }++ await refreshPassphrase();+ await setEncryptionEnabled(true);+ setPasswordModalShown(false);+ toast.showMessage(t("backup.password_stored"));+ }++ // Switching encryption off forgets the passphrase with it: there is nothing left to keep it for,+ // 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);+ await refreshPassphrase();+ }++ return (+ <div className="options-section backup-options">+ <Card heading={t("backup.options_title")}>+ <CardSection className="backup-options-row">+ <span className="backup-options-label">+ {t("backup.enable_compression")}+ <small className="backup-options-description">{t("backup.enable_compression_description")}</small>+ </span>++ <FormToggle currentValue={compressionEnabled} onChange={setCompressionEnabled} />+ </CardSection>++ <CardSection className="backup-options-row">+ <span className="backup-options-label">+ {t("backup.enable_encryption")}+ <small className="backup-options-description">+ {passphrase.available ? t("backup.enable_encryption_description") : t("backup.no_keyring")}+ </small>+ </span>++ {passphrase.set ? (+ <>+ <Button+ name="change-backup-password-button"+ text={t("backup.change_password")}+ size="micro"+ onClick={() => setPasswordModalShown(true)}+ />+ <FormToggle+ currentValue={encryptionEnabled}+ onChange={(enabled) => enabled ? setEncryptionEnabled(true) : disableEncryption()}+ />+ </>+ ) : (+ <Button+ name="turn-on-backup-encryption-button"+ text={t("backup.turn_on_encryption")}+ size="micro"+ disabled={!passphrase.available}+ onClick={() => setPasswordModalShown(true)}+ />+ )}+ </CardSection>+ </Card>++ <BackupPasswordModal+ show={passwordModalShown}+ onHidden={() => setPasswordModalShown(false)}+ onSave={storePassword}+ />+ </div>+ );+}++/** Asks for a backup password twice over, for setting the first one or replacing the one in place. */+function BackupPasswordModal({ show, onHidden, onSave }: { show: boolean; onHidden: () => void; onSave: (password: string) => void }) {+ const [password, setPassword] = useState<string | null>(null);+ const inputRef = useRef<HTMLInputElement>(null);++ return (+ <Modal+ className="backup-password-modal"+ title={t("backup.password_modal_title")}+ size="sm"+ // Options can themselves be a dialog; without this, showing here closes the one behind.+ stackable+ show={show}+ onShown={() => inputRef.current?.focus()}+ onHidden={onHidden}+ onSubmit={() => password && onSave(password)}+ footer={<Button text={t("backup.save_password")} kind="primary" disabled={!password} />}+ >+ <FormText>{t("backup.password_modal_description")}</FormText>++ <FormPasswordWithConfirmation inputRef={inputRef} onChange={setPassword} />+ </Modal>+ );+}+export function BackupList({ backups, backupFolderPath, refreshCallback }: { backups: DatabaseBackup[]; backupFolderPath: string | null; refreshCallback: () => void }) {const [backupInProgress, setBackupInProgress] = useState(false);const [customDir] = useTriliumOption("customDbBackupDir");