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/setup/backup: improve UI, add backup parameters (with compression toggle) for the desktop app as well
Adorian Doran611cb9ece0d8
diff --git a/apps/client/src/services/backup_download.ts b/apps/client/src/services/backup_download.tsindex 8675eccc29..a611959284 100644--- a/apps/client/src/services/backup_download.ts+++ b/apps/client/src/services/backup_download.ts@@ -1,6 +1,4 @@-import { defaultBackupName, type StandaloneDownloadResult } from "@triliumnext/commons";--import { tidyFilesystemFriendlyName } from "../widgets/react/FilesystemFriendlyName";+import { asFileName, defaultBackupName, type StandaloneDownloadResult } from "@triliumnext/commons";/*** Backing up by download, which is the standalone platform's one and only backup.@@ -16,9 +14,6 @@ import { tidyFilesystemFriendlyName } from "../widgets/react/FilesystemFriendlyN/** Every backup is a container, with or without a password, so every backup has this extension. */const BACKUP_EXTENSION = ".tnbackup";-/** Reserved device names on Windows, which cannot be a filename there whatever the extension. */-const RESERVED_FILE_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;-/** Whether this platform backs up by streaming a download, which is the standalone build. */export function isBackupDownloadSupported(): boolean {return !!window.standaloneApi;@@ -27,16 +22,13 @@ export function isBackupDownloadSupported(): boolean {/*** The file a name is written to.*- * The name arrives already tidied by the field it was typed into; this applies the same rules- * again, because a name can also arrive from somewhere that never saw that field, and adds the two- * things only a filename cares about: a name that is left empty, and the device names Windows- * reserves whatever the extension. Either falls back to the suggested name rather than failing.+ * The name arrives already tidied by the field it was typed into, and is put through the same rules+ * again here, because a name can also arrive from somewhere that never saw that field. What is left+ * of one that empties itself out, or that turns out to be a name the system keeps for itself, is+ * the suggested name rather than a failure.*/export function backupFileName(name: string): string {- const tidied = tidyFilesystemFriendlyName(name);- const usable = tidied && !RESERVED_FILE_NAMES.test(tidied) ? tidied : defaultBackupName(new Date());-- return `${usable}${BACKUP_EXTENSION}`;+ return `${asFileName(name) ?? defaultBackupName(new Date())}${BACKUP_EXTENSION}`;}/**diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsxindex 9435f42cea..1abb4451f5 100644--- a/apps/client/src/setup.spec.tsx+++ b/apps/client/src/setup.spec.tsx@@ -22,7 +22,7 @@ const serverMock = vi.hoisted(() => ({}));vi.mock("./services/server", () => ({ default: serverMock }));-import { initialState, renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";+import { initialState, openedAtRestore, renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";type Stats = { outstandingPullCount: number; totalPullCount: number | null; initialized: boolean; lastSyncError?: string | null };@@ -234,4 +234,13 @@ describe("where the wizard opens", () => {expect(initialState({ setupTargetScreen: "createNewDocumentEmpty" as never })).toBe("selectLanguage");});++ it("knows when the restore is the whole of what the wizard was opened for", () => {+ // Which decides whether that screen offers a way back: there is one only where the user+ // walked into the restore through the wizard's own menu.+ expect(openedAtRestore({ setupTargetScreen: "restore-backup" })).toBe(true);+ expect(openedAtRestore({ initialSetup: false, setupTargetScreen: "restore-backup" })).toBe(true);+ expect(openedAtRestore({})).toBe(false);+ expect(openedAtRestore({ setupTargetScreen: "backup-database" })).toBe(false);+ });});diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex 3a794b3d6d..674c4f9f1e 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -62,7 +62,15 @@ export function renderState(state: State, setState: (state: State) => void) {case "createNewDocumentOptions": return <CreateNewDocumentOptions setState={setState} />;case "createNewDocumentWithDemo": return <CreateNewDocumentInProgress withDemo />;case "createNewDocumentEmpty": return <CreateNewDocumentInProgress />;- case "restoreFromBackup": return <RestoreFromBackup onBack={() => setState("firstOptions")} onRestored={onSetupFinished} />;+ // No way back where the wizard was opened for this and nothing else: the menu it would+ // return to was never shown, and on an instance that had a database it is not a menu the+ // user asked for.+ case "restoreFromBackup": return (+ <RestoreFromBackup+ onBack={openedAtRestore(window.glob) ? undefined : () => setState("firstOptions")}+ onRestored={onSetupFinished}+ />+ );case "syncFromServer": return <SyncFromServer setState={setState} />;case "syncFromDesktop": return <SyncFromDesktop setState={setState} />;case "syncFromServerInProgress": return <SyncInProgress device="server" setState={setState} />;@@ -137,6 +145,14 @@ export function initialState(glob: SetupGlob): State {return afterExistingData(glob);}+/**+ * Whether the restore screen is where this wizard was sent, rather than somewhere the user walked+ * to through it. A marker naming it is the only way that happens.+ */+export function openedAtRestore(glob: SetupGlob): boolean {+ return glob.setupTargetScreen === "restore-backup";+}+/*** Where the wizard goes once there is nothing left to lose.*diff --git a/apps/client/src/setup_backup.spec.tsx b/apps/client/src/setup_backup.spec.tsxindex 485cb359f6..bd4dc45c7e 100644--- a/apps/client/src/setup_backup.spec.tsx+++ b/apps/client/src/setup_backup.spec.tsx@@ -1,3 +1,4 @@+import type { SetupBackupDefaults } from "@triliumnext/commons";import { render } from "preact";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -15,7 +16,7 @@ vi.mock("./services/backup_download", async (importOriginal) => ({startBackupDownload: mocks.startBackupDownload}));-import SetupBackupDatabase from "./setup_backup";+import SetupBackupDatabase, { BackupParameters } from "./setup_backup";let container: HTMLDivElement;const onDone = vi.fn();@@ -45,6 +46,20 @@ function passwordFields(): HTMLInputElement[] {return [ ...container.querySelectorAll<HTMLInputElement>("input[type=password]") ];}+/** The toggles, in the order they appear: the stored password, then compression. */+function toggles(): HTMLInputElement[] {+ return [ ...container.querySelectorAll<HTMLInputElement>("input.switch-toggle") ];+}++/** Operates a toggle the way a click on it does. */+function flip(toggle: HTMLInputElement | undefined) {+ if (!toggle) {+ throw new Error("the toggle is not on screen");+ }++ toggle.dispatchEvent(new Event("input", { bubbles: true }));+}+/** Types into a controlled text box the way the browser does: value, then an input event. */function type(input: HTMLInputElement | null, value: string) {if (!input) {@@ -162,6 +177,119 @@ describe("choosing what the backup is called and whether it is locked", () => {});});+describe("the questions a platform that writes its own backup can ask", () => {+ const onContinue = vi.fn();++ /** Renders just the parameters screen, which is the only part of this the platform changes. */+ async function renderParameters(defaults: SetupBackupDefaults | null) {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(<BackupParameters defaults={defaults} onContinue={onContinue} />, container);+ await settle();+ }++ beforeEach(() => onContinue.mockReset());++ it("asks nothing about the format where there is no format to choose", async () => {+ // The standalone platform, whose backup is a download: nothing stored to lock it with, and+ // compressing the stream is more than the devices it exists for can afford.+ await renderParameters(null);++ expect(container.textContent).toContain("setup.backup-name");+ expect(container.textContent).not.toContain("setup.backup-compress");+ expect(container.textContent).not.toContain("setup.backup-use-stored-password");+ expect(toggles()).toHaveLength(0);+ });++ it("starts from how the instance already backs up, rather than from nothing", async () => {+ await renderParameters({ storedPassphrase: true, encrypt: true, compress: true });++ const [ stored, compress ] = toggles();+ expect(stored.checked).toBe(true);+ expect(compress.checked).toBe(true);+ // Nothing to type, so nothing is asked for: the stored password is never shown, which is+ // why asking for it is a choice rather than a value, and the fields it stands in for have+ // no part left to play.+ expect(passwordFields()).toHaveLength(0);+ expect(container.textContent).not.toContain("setup.backup-password-description");+ expect(button("setup.continue")?.disabled).toBe(false);+ });++ it("offers the password fields where the instance encrypts nothing", async () => {+ await renderParameters({ storedPassphrase: true, encrypt: false, compress: false });++ const [ stored, compress ] = toggles();+ expect(stored.checked).toBe(false);+ expect(compress.checked).toBe(false);+ expect(passwordFields()).toHaveLength(2);+ });++ it("offers no stored password where there is none stored", async () => {+ // Every server deployment, and any desktop whose system has no keyring to keep one in.+ await renderParameters({ storedPassphrase: false, encrypt: true, compress: false });++ expect(container.textContent).not.toContain("setup.backup-use-stored-password");+ expect(container.textContent).toContain("setup.backup-compress");+ expect(passwordFields()).toHaveLength(2);+ });++ it("gives the fields back when the stored password is turned off again", async () => {+ await renderParameters({ storedPassphrase: true, encrypt: true, compress: false });++ flip(toggles()[0]);+ await settle();++ expect(passwordFields()).toHaveLength(2);+ type(passwordFields()[0], "hunter2");+ type(passwordFields()[1], "hunter2");+ await settle();++ button("setup.continue")?.click();+ expect(onContinue).toHaveBeenCalledWith(expect.objectContaining({+ passphrase: "hunter2",+ useStoredPassphrase: false+ }));+ });++ it("does not let a password that is no longer on screen hold up continuing", async () => {+ await renderParameters({ storedPassphrase: true, encrypt: false, compress: false });++ // Half-typed, which is the one state Continue must not accept...+ type(passwordFields()[0], "hunter2");+ await settle();+ expect(button("setup.continue")?.disabled).toBe(true);++ // ...until the fields go away with the choice that replaces them. What they were holding+ // goes with them, or Continue would stay disabled by a segment nobody can see.+ flip(toggles()[0]);+ await settle();+ expect(passwordFields()).toHaveLength(0);+ expect(button("setup.continue")?.disabled).toBe(false);++ button("setup.continue")?.click();+ expect(onContinue).toHaveBeenCalledWith(expect.objectContaining({+ passphrase: "",+ useStoredPassphrase: true+ }));+ });++ it("hands on every answer, so the backup is written as the user described it", async () => {+ await renderParameters({ storedPassphrase: false, encrypt: false, compress: false });++ type(nameField(), "Before the import");+ flip(toggles()[0]);+ await settle();++ button("setup.continue")?.click();+ expect(onContinue).toHaveBeenCalledWith({+ name: "Before the import",+ passphrase: "",+ useStoredPassphrase: false,+ compress: true+ });+ });+});+describe("backing up from the setup screen", () => {it("names the file up front and downloads nothing until asked", async () => {const chosen = await reachDownload();diff --git a/apps/client/src/setup_backup.tsx b/apps/client/src/setup_backup.tsxindex 55b9417388..a2bb0ea746 100644--- a/apps/client/src/setup_backup.tsx+++ b/apps/client/src/setup_backup.tsx@@ -1,6 +1,10 @@import "./setup_backup.css";-import { defaultBackupName } from "@triliumnext/commons";+import {+ defaultBackupName,+ type SetupBackupDefaults,+ type SetupBackupSettings+} from "@triliumnext/commons";import type { ComponentChildren } from "preact";import { useMemo, useState } from "preact/hooks";@@ -8,10 +12,11 @@ import { backupFileName, startBackupDownload } from "./services/backup_download"import { t } from "./services/i18n";import Admonition from "./widgets/react/Admonition";import Button from "./widgets/react/Button";-import { Card, CardSection } from "./widgets/react/Card";+import { Card, CardOption, CardSection } from "./widgets/react/Card";import FilesystemFriendlyName from "./widgets/react/FilesystemFriendlyName";import FormGroup from "./widgets/react/FormGroup";import FormPasswordWithConfirmation from "./widgets/react/FormPasswordWithConfirmation";+import FormToggle from "./widgets/react/FormToggle";import Icon from "./widgets/react/Icon";import SetupPage from "./widgets/react/SetupPage";@@ -28,14 +33,6 @@ import SetupPage from "./widgets/react/SetupPage";* @module*/-/** What the user settled on before the backup was taken. */-export interface BackupSettings {- /** What to call it, already reduced to characters a filename can hold. */- name: string;- /** Empty for a backup anyone can open; anything else encrypts it. */- passphrase: string;-}-/** Where the download stands, and the one thing that can be done about it. */export interface BackupDownload {fileName: string;@@ -45,8 +42,15 @@ export interface BackupDownload {start: () => void;}-/** Owns a download of the file `settings` describes. */-export function useBackupDownload(settings: BackupSettings): BackupDownload {+/**+ * Owns a download of the file `settings` describes.+ *+ * Only the name and the password are of any use here: the standalone platform produces its backup+ * by streaming the live database into a download, and compressing that stream is more than the+ * low-end devices it exists for can afford, so there is nothing for it to read a compression answer+ * out of. Nor is there a stored passphrase anywhere in a browser to be asked for.+ */+export function useBackupDownload(settings: SetupBackupSettings): BackupDownload {const fileName = useMemo(() => backupFileName(settings.name), [ settings.name ]);const [ state, setState ] = useState<BackupDownload["state"]>("idle");const [ error, setError ] = useState<string>();@@ -67,16 +71,23 @@ export function useBackupDownload(settings: BackupSettings): BackupDownload {}/**- * What the backup is called and whether it is locked, asked before it is taken.+ * What the backup is called, whether it is locked and whether it is compressed, asked before it is+ * taken.** The name matters more than it looks: a downloads folder two months from now is a list of* near-identical dated files, and the one thing that tells the user why they made this one is what- * they called it. It is prefilled so that answering nothing is a perfectly good answer.+ * they called it. It is prefilled so that answering nothing is a perfectly good answer, and so is+ * everything else here: a user who has already set up how this instance backs up is shown those+ * answers rather than asked to make them again.*+ * @param defaults how this instance already backs up, or `null` where none of it is up for+ * discussion — the standalone platform writes its backup by streaming it into a+ * download, which can be neither compressed nor locked with a stored passphrase.* @param onContinue the settings to back up under; the screen after this one does the work.*/-export function BackupParameters({ onContinue, footer }: {- onContinue: (settings: BackupSettings) => void;+export function BackupParameters({ defaults, onContinue, footer }: {+ defaults: SetupBackupDefaults | null;+ onContinue: (settings: SetupBackupSettings) => void;/** What sits beside Continue, which differs by the flow this screen was reached through. */footer?: ComponentChildren;}) {@@ -84,6 +95,9 @@ export function BackupParameters({ onContinue, footer }: {// Null while the two password fields disagree, which is the one state Continue must not accept:// a half-typed password would otherwise be dropped and the backup written unlocked.const [ passphrase, setPassphrase ] = useState<string | null>("");+ const [ useStoredPassphrase, setUseStoredPassphrase ] = useState(+ () => !!defaults?.storedPassphrase && defaults.encrypt);+ const [ compress, setCompress ] = useState(() => !!defaults?.compress);return (<SetupPage@@ -97,7 +111,12 @@ export function BackupParameters({ onContinue, footer }: {text={t("setup.continue")}kind="primary"disabled={passphrase === null}- onClick={() => onContinue({ name, passphrase: passphrase ?? "" })}+ onClick={() => onContinue({+ name,+ passphrase: passphrase ?? "",+ useStoredPassphrase,+ compress+ })}/></>}@@ -116,15 +135,52 @@ export function BackupParameters({ onContinue, footer }: {</FormGroup></CardSection>- <CardSection>- <FormPasswordWithConfirmation- optional- label={t("setup.backup-password")}- confirmationLabel={t("setup.backup-password-repeat")}- onChange={setPassphrase}- />- <small class="form-text">{t("setup.backup-password-description")}</small>- </CardSection>+ {/* Directly above the fields it replaces, because that is the whole of what it+ does: the stored passphrase cannot be shown, so choosing it is the only way+ to ask for the password the user has already set up. */}+ {defaults?.storedPassphrase && (+ <CardOption+ name="backup-use-stored-password"+ label={t("setup.backup-use-stored-password")}+ description={t("setup.backup-use-stored-password-description")}+ >+ <FormToggle+ currentValue={useStoredPassphrase}+ onChange={(enabled) => {+ setUseStoredPassphrase(enabled);+ // The fields leave with it, and a pair that is gone reports+ // nothing: a password left half-typed in them would otherwise+ // go on holding Continue disabled from a segment nobody can+ // see, with nothing on screen to explain it.+ if (enabled) {+ setPassphrase("");+ }+ }}+ />+ </CardOption>+ )}++ {!useStoredPassphrase && (+ <CardSection>+ <FormPasswordWithConfirmation+ optional+ label={t("setup.backup-password")}+ confirmationLabel={t("setup.backup-password-repeat")}+ onChange={setPassphrase}+ />+ <small class="form-text">{t("setup.backup-password-description")}</small>+ </CardSection>+ )}++ {defaults && (+ <CardOption+ name="backup-compress"+ label={t("setup.backup-compress")}+ description={t("setup.backup-compress-description")}+ >+ <FormToggle currentValue={compress} onChange={setCompress} />+ </CardOption>+ )}</Card></form></SetupPage>@@ -192,7 +248,7 @@ export function BackupDownloadPanel({ download }: { download: BackupDownload })* @param onDone the backup is over, one way or another; leave the wizard.*/export function BackupDownloadStep({ settings, onDone }: {- settings: BackupSettings;+ settings: SetupBackupSettings;onDone: () => void;}) {const download = useBackupDownload(settings);@@ -228,11 +284,14 @@ export function BackupDownloadStep({ settings, onDone }: {* @param onDone leave setup and open the database that was there all along.*/export default function SetupBackupDatabase({ onDone }: { onDone: () => void }) {- const [ settings, setSettings ] = useState<BackupSettings | null>(null);+ const [ settings, setSettings ] = useState<SetupBackupSettings | null>(null);if (!settings) {return (<BackupParameters+ // This screen is the standalone platform's, and its backup is a download: there is+ // no instance-wide format for it to follow and nothing stored to lock it with.+ defaults={null}onContinue={setSettings}footer={<Button text={t("setup.backup-finish")} onClick={onDone} />}/>diff --git a/apps/client/src/setup_existing.css b/apps/client/src/setup_existing.cssindex cab1f762be..5cb6817774 100644--- a/apps/client/src/setup_existing.css+++ b/apps/client/src/setup_existing.css@@ -1,16 +1,26 @@.page.existing-data,-.page.existing-data-backed-up,-.page.existing-data-downloading {+.page.existing-data-backed-up {.existing-data-warning {margin-top: 16px;}}+/* Set apart from the question, which now stands on its own without a paragraph between them. */+.page.existing-data .existing-data-choices {+ margin-top: 3em;+}+.page.existing-data .existing-data-choices .tn-card-section {padding-block: 12px;}+/* The answer that erases the knowledge base, in the colour the rest of the app gives an action+ that cannot be taken back. */+.page.existing-data .existing-data-destructive .tn-radio {+ color: var(--dropdown-item-icon-destructive-color);+}+/* The wait while a backup is written, centred under the icon like the restore's own steps. */.page.existing-data-backing-up .existing-data-progress {display: flex;diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsxindex 050c65ef85..514ea2c4e7 100644--- a/apps/client/src/setup_existing.spec.tsx+++ b/apps/client/src/setup_existing.spec.tsx@@ -8,8 +8,10 @@ const serverMock = vi.hoisted(() => ({get: vi.fn(async (url: string): Promise<unknown> =>(url === "setup/existing/status"? { state: "idle", fraction: null }- : url === "keyboard-actions" ? [] : {})),- post: vi.fn(async (_url: string): Promise<unknown> => ({}))+ : url === "setup/existing/backup-defaults"+ ? { storedPassphrase: false, encrypt: false, compress: false }+ : url === "keyboard-actions" ? [] : {})),+ post: vi.fn(async (_url: string, _body?: unknown): Promise<unknown> => ({}))}));vi.mock("./services/server", () => ({ default: serverMock }));@@ -31,8 +33,7 @@ const BACKUP = {fileName: "Backup 2026-08-07 10-32-21.tnbackup",filePath: "/mnt/usb/trilium/Backup 2026-08-07 10-32-21.tnbackup",directoryPath: "/mnt/usb/trilium",- fileSize: 209715200,- encrypted: false+ fileSize: 209715200};let container: HTMLDivElement;@@ -61,6 +62,37 @@ function button(label: string): HTMLButtonElement | undefined {.find((element) => element.textContent?.includes(label));}+/**+ * The button on the page that arrived, not the one that left: happy-dom never fires the animation+ * events that let SlidePages drop the leaving page, so after one transition both pages are in the+ * DOM and the arriving one renders second.+ */+function arrivingButton(label: string): HTMLButtonElement | undefined {+ return [ ...container.querySelectorAll("button") ]+ .filter((element) => element.textContent?.includes(label))+ .at(-1);+}++/** Chooses the backup and answers the parameters screen with everything as it was prefilled. */+async function askForBackup() {+ renderScreens();+ await settle();++ choose("back-up");+ await settle();+ button("setup.continue")?.click();+ await settle();++ arrivingButton("setup.continue")?.click();+ await settle();+}++/**+ * The last question before the erase, answered here so the tests get past it. happy-dom has no+ * `confirm` of its own, so it is stubbed rather than spied on.+ */+const confirmErase = vi.fn(() => true);+beforeEach(() => {vi.useFakeTimers();onProceed.mockReset();@@ -70,12 +102,15 @@ beforeEach(() => {openMock.download.mockClear();electronMock.isElectron.mockReset().mockReturnValue(false);electronMock.openPath.mockClear();+ confirmErase.mockReset().mockReturnValue(true);+ vi.stubGlobal("confirm", confirmErase);window.electronApi = undefined;});afterEach(() => {render(null, container);container.remove();+ vi.unstubAllGlobals();vi.useRealTimers();});@@ -138,7 +173,7 @@ describe("choosing what happens to the existing knowledge base", () => {expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");expect(onProceed).toHaveBeenCalled();// Nothing was backed up, since nothing was asked to be.- expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup");+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup", expect.anything());});it("leaves everything alone and reopens the database on cancel", async () => {@@ -157,27 +192,62 @@ describe("backing it up first", () => {/** Answers the status polls with `status`, leaving every other GET as the default mock has it. */function statusAnswers(status: unknown) {serverMock.get.mockImplementation(async (url: string) =>- (url === "setup/existing/status" ? status : url === "keyboard-actions" ? [] : {}));+ (url === "setup/existing/status"+ ? status+ : url === "setup/existing/backup-defaults"+ ? { storedPassphrase: false, encrypt: false, compress: false }+ : url === "keyboard-actions" ? [] : {}));}- /** Chooses the backup, sets it going, and rides out one poll interval. */+ /** Chooses the backup, answers its parameters, sets it going, and rides out one poll interval. */async function backUpAndWait() {+ await askForBackup();+ // The answer arrives over a poll, one interval after the backup was set going.+ await vi.advanceTimersByTimeAsync(1100);+ await settle();+ }++ it("asks what the backup should be before taking it, and sends those answers", async () => {+ serverMock.get.mockImplementation(async (url: string) =>+ (url === "setup/existing/backup-defaults"+ ? { storedPassphrase: true, encrypt: true, compress: true }+ : url === "setup/existing/status"+ ? { state: "done", fraction: 1, result: BACKUP }+ : url === "keyboard-actions" ? [] : {}));renderScreens();await settle();choose("back-up");await settle();button("setup.continue")?.click();- // The answer arrives over a poll, one interval after the backup was set going.+ await settle();++ // The questions this platform can ask, which the standalone one cannot: it writes the file+ // itself, so the format is a choice, and it has a passphrase of its own to offer.+ expect(container.textContent).toContain("setup.backup-name");+ expect(container.textContent).toContain("setup.backup-compress");+ expect(container.textContent).toContain("setup.backup-use-stored-password");+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup", expect.anything());++ arrivingButton("setup.continue")?.click();await vi.advanceTimersByTimeAsync(1100);await settle();- }++ // What the instance is already set up for, offered back and accepted unchanged.+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/backup", {+ name: expect.stringMatching(/^Trilium data \(/),+ passphrase: "",+ useStoredPassphrase: true,+ compress: true+ });+ });it("says what was written, and erases nothing until that is confirmed", async () => {statusAnswers({ state: "done", fraction: 1, result: BACKUP });await backUpAndWait();- expect(serverMock.post).toHaveBeenCalledWith("setup/existing/backup");+ expect(serverMock.post)+ .toHaveBeenCalledWith("setup/existing/backup", expect.objectContaining({ compress: false }));// The path in full: the option holding a custom backup directory is in the database that is// about to go, so this may be the last chance to read it.expect(container.textContent).toContain(BACKUP.fileName);@@ -189,21 +259,31 @@ describe("backing it up first", () => {button("setup.continue")?.click();await settle();+ expect(confirmErase).toHaveBeenCalledWith("setup.existing-data-erase-confirm");expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");expect(onProceed).toHaveBeenCalled();});+ it("erases nothing when the last question is answered no", async () => {+ confirmErase.mockReturnValue(false);+ statusAnswers({ state: "done", fraction: 1, result: BACKUP });+ await backUpAndWait();++ button("setup.continue")?.click();+ await settle();++ expect(confirmErase).toHaveBeenCalled();+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");+ expect(onProceed).not.toHaveBeenCalled();+ // Still on the screen it was answered from, so the backup can be taken again or kept.+ expect(container.textContent).toContain(BACKUP.fileName);+ });+it("shows how far along the write is, once the writer has said anything", async () => {// The write runs for minutes, so this screen would otherwise show a spinner and nothing// else for the whole of it.statusAnswers({ state: "running", fraction: null });- renderScreens();- await settle();-- choose("back-up");- await settle();- button("setup.continue")?.click();- await settle();+ await askForBackup();// Nothing to show yet, so the spinner stands in for the bar.expect(container.querySelector(".spinner-border")).not.toBeNull();@@ -230,14 +310,6 @@ describe("backing it up first", () => {expect.stringContaining(encodeURIComponent(BACKUP.filePath)));});- it("says to keep the backup password where the backup needs one", async () => {- statusAnswers({ state: "done", fraction: 1, result: { ...BACKUP, encrypted: true } });- await backUpAndWait();-- expect(container.querySelector(".existing-data-warning")?.textContent)- .toContain("setup.existing-data-encrypted-warning");- });-it("goes back to the question when the backup cannot even start", async () => {// Rejected the way the client's request layer rejects: the response body, not an Error.serverMock.post.mockImplementation(async (url: string) => {@@ -246,13 +318,7 @@ describe("backing it up first", () => {}return undefined;});- renderScreens();- await settle();-- choose("back-up");- await settle();- button("setup.continue")?.click();- await settle();+ await askForBackup();expect(container.querySelector(".page-error")?.textContent).toContain("the disk is full");expect(container.querySelector("input[type=radio]")).not.toBeNull();@@ -280,14 +346,12 @@ describe("backing it up first", () => {}return { state: "done", fraction: 1, result: BACKUP };}+ if (url === "setup/existing/backup-defaults") {+ return { storedPassphrase: false, encrypt: false, compress: false };+ }return url === "keyboard-actions" ? [] : {};});- renderScreens();- await settle();-- choose("back-up");- await settle();- button("setup.continue")?.click();+ await askForBackup();await vi.advanceTimersByTimeAsync(3500);await settle();@@ -310,22 +374,13 @@ describe("backing up straight to a download on standalone", () => {window.standaloneApi = undefined;});- /**- * The button on the page that arrived, not the one that left: happy-dom never fires the- * animation events that let SlidePages drop the leaving page, so after one transition both- * pages are in the DOM and the arriving one renders second.- */- function arrivingButton(label: string): HTMLButtonElement | undefined {- return [ ...container.querySelectorAll("button") ]- .filter((element) => element.textContent?.includes(label))- .at(-1);- }-/*** Chooses the backup, accepts the suggested name and no password, and arrives at the download* screen with nothing started yet.*/- async function reachDownloadScreen() {+ const reachDownloadScreen = askForBackup;++ it("asks nothing this platform cannot answer, and never asks the backend to write one", async () => {renderScreens();await settle();@@ -334,10 +389,12 @@ describe("backing up straight to a download on standalone", () => {button("setup.continue")?.click();await settle();- // The parameters screen, which the same Continue leaves as it was prefilled.- arrivingButton("setup.continue")?.click();- await settle();- }+ // No format to choose and no passphrase kept anywhere, so neither question is put.+ expect(container.textContent).toContain("setup.backup-name");+ expect(container.textContent).not.toContain("setup.backup-compress");+ expect(container.textContent).not.toContain("setup.backup-use-stored-password");+ expect(serverMock.get).not.toHaveBeenCalledWith("setup/existing/backup-defaults");+ });it("shows the download step without starting anything, and gates Continue on it", async () => {let finish: (result: unknown) => void = () => {};@@ -350,7 +407,7 @@ describe("backing up straight to a download on standalone", () => {expect(container.textContent).toContain("setup.backup-data");expect(downloadDatabase).not.toHaveBeenCalled();expect(arrivingButton("setup.continue")?.disabled).toBe(true);- expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup");+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup", expect.anything());arrivingButton("setup.backup-download")?.click();await settle();@@ -368,10 +425,27 @@ describe("backing up straight to a download on standalone", () => {arrivingButton("setup.continue")?.click();await settle();+ // Asked once more before the data goes, since this screen is about the copy rather than+ // about what continuing costs.+ expect(confirmErase).toHaveBeenCalledWith("setup.existing-data-erase-confirm");expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");expect(onProceed).toHaveBeenCalled();});+ it("keeps the data when that last question is answered no", async () => {+ confirmErase.mockReturnValue(false);+ downloadDatabase.mockResolvedValue({ status: "done" });+ await reachDownloadScreen();++ arrivingButton("setup.backup-download")?.click();+ await settle();+ arrivingButton("setup.continue")?.click();+ await settle();++ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");+ expect(onProceed).not.toHaveBeenCalled();+ });+it("shows what stopped a failed download, and keeps Continue out of reach", async () => {downloadDatabase.mockResolvedValue({ status: "failed", message: "the stream broke" });await reachDownloadScreen();diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsxindex dcb1c8c62b..460db5b937 100644--- a/apps/client/src/setup_existing.tsx+++ b/apps/client/src/setup_existing.tsx@@ -1,6 +1,11 @@import "./setup_existing.css";-import type { SetupExistingBackup, SetupExistingBackupStatus } from "@triliumnext/commons";+import type {+ SetupBackupDefaults,+ SetupBackupSettings,+ SetupExistingBackup,+ SetupExistingBackupStatus+} from "@triliumnext/commons";import { useEffect, useState } from "preact/hooks";import { isBackupDownloadSupported } from "./services/backup_download";@@ -8,6 +13,7 @@ import { t } from "./services/i18n";import open from "./services/open";import server from "./services/server";import { formatSize, isElectron } from "./services/utils";+import { BackupDownloadPanel, BackupParameters, useBackupDownload } from "./setup_backup";import Admonition from "./widgets/react/Admonition";import Button from "./widgets/react/Button";import { Card, CardOption, CardSection } from "./widgets/react/Card";@@ -15,12 +21,6 @@ import FormRadioGroup from "./widgets/react/FormRadioGroup";import Icon from "./widgets/react/Icon";import SetupPage from "./widgets/react/SetupPage";import SlidePages from "./widgets/react/SlidePages";-import {- BackupDownloadPanel,- BackupParameters,- type BackupSettings,- useBackupDownload-} from "./setup_backup";/*** What happens to the knowledge base that was already here.@@ -61,7 +61,8 @@ const STEP_ORDER: Step[] = [ "choice", "backup-parameters", "backing-up", "downlexport default function ExistingData({ onProceed, onKept }: { onProceed: () => void; onKept: () => void }) {const [ step, setStep ] = useState<Step>("choice");const [ backup, setBackup ] = useState<SetupExistingBackup | null>(null);- const [ settings, setSettings ] = useState<BackupSettings | null>(null);+ const [ settings, setSettings ] = useState<SetupBackupSettings | null>(null);+ const [ defaults, setDefaults ] = useState<SetupBackupDefaults | null>(null);const [ error, setError ] = useState<string>();const [ errorId, setErrorId ] = useState(0);@@ -81,20 +82,43 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v}}- async function backUp() {- // Standalone streams the backup straight into a browser download: the browser's own- // storage may not have room for a second copy of the database, but the disk does. It is- // named and locked first, then downloaded from its own button, so nothing lands in the- // downloads bar unannounced.- if (isBackupDownloadSupported()) {- setStep("backup-parameters");+ /**+ * The same, asked about first, for the screens reached by taking a backup.+ *+ * Those screens are about the copy that was just made, and the erasure is what Continue does+ * once the user is done reading about it — which is exactly the sort of thing a hand already+ * moving towards the button does not notice. The wizard has no dialog stack of its own, so this+ * is the browser's own, which is both unmissable and available on every platform.+ */+ async function confirmAndErase() {+ if (!window.confirm(t("setup.existing-data-erase-confirm"))) {return;}+ await erase();+ }++ /**+ * Asks what the backup should be before taking it, which every platform does.+ *+ * What can be asked differs: the standalone platform's backup is a download and has no format+ * to choose, while everywhere else the instance has settings of its own that the screen offers+ * back as its answers.+ */+ async function backUp() {+ if (!isBackupDownloadSupported()) {+ setDefaults(await getBackupDefaults());+ }++ setStep("backup-parameters");+ }++ /** Writes it where the platform keeps backups, which is everywhere but standalone. */+ async function runBackup(chosen: SetupBackupSettings) {setStep("backing-up");try {- setBackup(await backUpExistingData());+ setBackup(await backUpExistingData(chosen));setStep("backed-up");} catch (e) {// Back to the question with nothing done: there is no continuing past a backup that was@@ -129,9 +153,19 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v)}{shown === "backup-parameters" && (<BackupParameters+ defaults={defaults}onContinue={(chosen) => {setSettings(chosen);- setStep("downloading");++ // Standalone streams the backup straight into a browser download:+ // the browser's own storage may not have room for a second copy of+ // the database, but the disk does. It is downloaded from its own+ // button, so nothing lands in the downloads bar unannounced.+ if (isBackupDownloadSupported()) {+ setStep("downloading");+ } else {+ void runBackup(chosen);+ }}}footer={<Button text={t("setup.existing-data-cancel")} onClick={() => void keep()} />}/>@@ -140,14 +174,14 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v{shown === "downloading" && settings && (<ExistingDataDownloadingsettings={settings}- onContinue={() => void erase()}+ onContinue={() => void confirmAndErase()}onCancel={() => void keep()}/>)}{shown === "backed-up" && backup && (<ExistingDataBackedUpbackup={backup}- onContinue={() => void erase()}+ onContinue={() => void confirmAndErase()}onCancel={() => void keep()}/>)}@@ -205,8 +239,9 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCancereturn (<SetupPageclassName="existing-data"+ // A question and nothing else: the answer decides whether a knowledge base survives,+ // and a paragraph above it is the part someone in a hurry reads past.title={t("setup.existing-data")}- description={t("setup.existing-data-description")}illustration={<Icon icon="bx bx-data" className="illustration-icon" />}error={error}errorId={errorId}@@ -229,7 +264,9 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCanceis for, and one of the answers erases a knowledge base. Which is checked is heldhere rather than by the browser's own grouping, so the two stay exclusive. */}{CHOICES.map(({ value, label }) => (- <CardSection key={value}>+ // The answer that erases everything is coloured as such, so it is recognisable+ // before it is read rather than after.+ <CardSection key={value} className={value === "delete" ? "existing-data-destructive" : undefined}><FormRadioGroupname="existing-data-choice"currentValue={choice ?? ""}@@ -311,7 +348,7 @@ const PROGRESS_INTERVAL_MS = 1000;* browser's own download UI carrying the transfer itself.*/export function ExistingDataDownloading({ settings, onContinue, onCancel }: {- settings: BackupSettings;+ settings: SetupBackupSettings;onContinue: () => void;onCancel: () => void;}) {@@ -335,10 +372,6 @@ export function ExistingDataDownloading({ settings, onContinue, onCancel }: {}><BackupDownloadPanel download={download} />-- <Admonition type="caution" className="existing-data-warning">- {t("setup.existing-data-downloading-warning")}- </Admonition></SetupPage>);}@@ -389,12 +422,6 @@ export function ExistingDataBackedUp({ backup, onContinue, onCancel }: {/></CardSection></Card>-- {backup.encrypted && (- <Admonition type="warning" className="existing-data-warning">- {t("setup.existing-data-encrypted-warning")}- </Admonition>- )}</SetupPage>);}@@ -451,8 +478,10 @@ function downloadBackup(filePath: string) {* rather than believed, because the write blocks the standalone worker for long stretches in which* it answers nothing, and the backup is running all the while.*/-export async function backUpExistingData(): Promise<SetupExistingBackup> {- await server.post("setup/existing/backup");+export async function backUpExistingData(+ settings: SetupBackupSettings+): Promise<SetupExistingBackup> {+ await server.post("setup/existing/backup", settings);const deadline = Date.now() + BACKUP_TIMEOUT_MS;while (Date.now() < deadline) {@@ -480,6 +509,20 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+/**+ * How this instance already backs up, which is what the screen offers as its answers.+ *+ * A failure here is not worth stopping a backup over: what is lost is a set of prefilled answers,+ * not the ability to give them, so the screen falls back to offering the plainest backup there is.+ */+export async function getBackupDefaults(): Promise<SetupBackupDefaults> {+ try {+ return await server.get<SetupBackupDefaults>("setup/existing/backup-defaults");+ } catch {+ return { storedPassphrase: false, encrypt: false, compress: false };+ }+}+/** Erases it, which is the point of no return. */export function deleteExistingData(): Promise<void> {return server.post("setup/existing/delete");diff --git a/apps/client/src/setup_restore.spec.tsx b/apps/client/src/setup_restore.spec.tsxindex bd4b2b7729..d628a056b2 100644--- a/apps/client/src/setup_restore.spec.tsx+++ b/apps/client/src/setup_restore.spec.tsx@@ -40,7 +40,10 @@ let restore: { stage: string; fraction?: number; error?: string; reason?: stringfunction renderRestore(props: Partial<{ onBack: () => void; onRestored: () => void }> = {}) {container = document.createElement("div");document.body.appendChild(container);- render(<RestoreFromBackup onBack={props.onBack ?? vi.fn()} onRestored={props.onRestored ?? vi.fn()} />, container);+ // `onBack` is omitted only when the caller says so: passing it undefined is the case where+ // nothing led here, which is the whole point of some of the tests below.+ const onBack = "onBack" in props ? props.onBack : vi.fn();+ render(<RestoreFromBackup onBack={onBack} onRestored={props.onRestored ?? vi.fn()} />, container);return container;}@@ -285,6 +288,27 @@ describe("going back", () => {expect(onBack).toHaveBeenCalled();});+ it("offers no way back from the first step where nothing led here", async () => {+ // The wizard opened at this screen, so the step it would return to was never shown.+ renderRestore({ onBack: undefined });+ await flushEffects();++ expect(container.querySelector(".back-button")).toBeNull();+ });++ it("still goes back a step within the restore, wherever the restore was entered from", async () => {+ renderRestore({ onBack: undefined });+ await flushEffects();+ backupRow("backup-weekly.tnbackup")?.click();+ await flushEffects();+ expect(container.querySelector("input[type=password]")).toBeTruthy();++ goBack();+ await flushEffects();++ expect(container.querySelector(".restore-choose-file")).toBeTruthy();+ });+it("returns to the backups from the password prompt, rather than out of the flow", async () => {const onBack = vi.fn();renderRestore({ onBack });diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxindex 4ed580e0c6..5baad69445 100644--- a/apps/client/src/setup_restore.tsx+++ b/apps/client/src/setup_restore.tsx@@ -47,7 +47,15 @@ const STEP_ORDER: Step[] = [ "picking", "uploading", "passphrase", "restoring" ]/** Failures the same backup can still get past, which send the user back to the passphrase rather than to the start. */const PASSPHRASE_FAILURES = new Set([ "passphrase-required", "wrong-passphrase-or-damaged-header" ]);-export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () => void; onRestored: () => void }) {+export default function RestoreFromBackup({ onBack, onRestored }: {+ /**+ * Leaves the restore for the step of the wizard that led here. Omitted where nothing did: an+ * instance sent straight to this screen by a marker has no earlier step to be shown, so the+ * first step of the restore has nowhere to go back to and offers no way.+ */+ onBack?: () => void;+ onRestored: () => void;+}) {const [ step, setStep ] = useState<Step>("picking");const [ selection, setSelection ] = useState<Selection | null>(null);const [ upload, setUpload ] = useState<UploadState | null>(null);@@ -187,10 +195,16 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =if (previous) {setStep(previous);} else {- onBack();+ onBack?.();}}+ /**+ * Whether there is anywhere to go back to: an earlier step of the restore, or the step of the+ * wizard that led into it. The replacement itself has neither, and cannot be interrupted anyway.+ */+ const canGoBack = step !== "restoring" && (!!PREVIOUS_STEP[step] || !!onBack);+function onRestoreFailed(failure: { error?: string; reason?: string }) {if (failure.reason && PASSPHRASE_FAILURES.has(failure.reason)) {// The backup is still on the server, so only the passphrase has to be given again.@@ -211,8 +225,10 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =illustration={<Icon icon="bx bx-archive-in" className="illustration-icon" />}error={error}errorId={errorId}- // Nothing to go back to once the database is being replaced.- onBack={step === "restoring" ? undefined : goBack}+ // Offered only where there is somewhere to go: not once the database is being replaced,+ // and not from the first step of a restore that is the whole of what the wizard was+ // opened for.+ onBack={canGoBack ? goBack : undefined}>{/* In the flow rather than filling the page: each step is a different height, and theone arriving is what the page should be as tall as. */}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 433dcd8b18..a17dbeabfb 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3689,10 +3689,9 @@"language": "Language","continue": "Continue","your-ip-addresses": "Addresses for this device",- "existing-data": "You already have a knowledge base",- "existing-data-description": "Setting up again will replace it. Would you like to save a copy first?",- "existing-data-back-up": "Yes, back it up",- "existing-data-delete": "No, delete the existing data",+ "existing-data": "Save your existing data?",+ "existing-data-back-up": "Yes, create a backup",+ "existing-data-delete": "No, delete everything","existing-data-delete-warning": "Once you press Continue, the existing knowledge base is permanently erased. There is no way to recover it afterwards.","existing-data-cancel": "Cancel","existing-data-backing-up": "Backing up",@@ -3705,15 +3704,17 @@"existing-data-save-as": "Save a copy...","existing-data-download": "Download","existing-data-file-size": "Size",- "existing-data-encrypted-warning": "This backup is encrypted with the backup password you set in the options, which is not your Trilium password. If you no longer have that password, press Cancel now: nothing has been deleted yet, and you can change the password before trying again. Without it the backup cannot be restored.","existing-data-backup-failed": "The backup could not be created.",- "existing-data-downloading-warning": "Once the download has finished and you press Continue, the knowledge base it was taken from is permanently erased. Keep the downloaded file somewhere safe.","backup-data": "Backup your Trilium data","backup-name": "Backup name","backup-name-description": "Give this backup a name you will recognise later, or keep the suggested one.","backup-password": "Password (optional)","backup-password-repeat": "Repeat password","backup-password-description": "If you specify a password, the backup file will be encrypted. Keep the password somewhere safe: without it, the backup cannot be restored.",+ "backup-use-stored-password": "Use the password you already configured",+ "backup-use-stored-password-description": "Use the same encryption password you have previously set up in Options → Backup.",+ "backup-compress": "Compress the backup",+ "backup-compress-description": "Makes the file smaller, at the cost of some time while it is written.","backup-data-description": "In the Standalone version of Trilium Notes, backups are generated on the spot and downloaded directly to your device. They are not stored anywhere else, so make sure you save the file.","backup-file": "Backup will be saved as","backup-download": "Generate and download backup",@@ -3722,6 +3723,7 @@"backup-downloaded": "The download has completed. Press \"Finish\" to return to the application.","backup-download-failed": "The download did not finish.","backup-finish": "Finish",+ "existing-data-erase-confirm": "Now the existing data will be discarded. Make sure you keep the backup file somewhere safe. Continue?","existing-data-delete-failed": "The existing knowledge base could not be deleted.","existing-data-keep-failed": "The existing knowledge base could not be reopened.","restore-from-backup": "Restore from backup",diff --git a/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsx b/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsxindex 0b7ddb48da..90374fece3 100644--- a/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsx+++ b/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsx@@ -2,40 +2,10 @@ import { render } from "preact";import { useState } from "preact/hooks";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import FilesystemFriendlyName, {- tidyFilesystemFriendlyName,- toFilesystemFriendlyName-} from "./FilesystemFriendlyName";--describe("what a file name may hold", () => {- it("keeps everything a file name can carry, other scripts included", () => {- expect(toFilesystemFriendlyName("Backup 2026-08-08 16-30-32"))- .toBe("Backup 2026-08-08 16-30-32");- expect(toFilesystemFriendlyName("Sicherungskopie (Änderungen)"))- .toBe("Sicherungskopie (Änderungen)");- expect(toFilesystemFriendlyName("備份")).toBe("備份");- });-- it("drops what no filesystem would take", () => {- expect(toFilesystemFriendlyName('a<b>c:d"e/f\\g|h?i*j')).toBe("abcdefghij");- expect(toFilesystemFriendlyName("before\u0001after\u001Fend")).toBe("beforeafterend");- });-- it("leaves a half-typed name alone, since it runs on every keystroke", () => {- // A trailing space or dot is on its way to becoming a word; tidying here would delete what- // the user is in the middle of typing.- expect(toFilesystemFriendlyName("Before the ")).toBe("Before the ");- expect(toFilesystemFriendlyName("v1.")).toBe("v1.");- });-- it("tidies the edges only once the name is finished", () => {- expect(tidyFilesystemFriendlyName(" Before the import ")).toBe("Before the import");- // Legal to type, impossible to save on Windows.- expect(tidyFilesystemFriendlyName("My backup...")).toBe("My backup");- expect(tidyFilesystemFriendlyName("mixed. . ")).toBe("mixed");- });-});+import FilesystemFriendlyName from "./FilesystemFriendlyName";+// What a file name may and may not hold is tested where those rules live, in+// `@triliumnext/commons`; what is left here is the field's own behaviour as it is typed into.describe("FilesystemFriendlyName", () => {let container: HTMLDivElement | undefined;const onChange = vi.fn();diff --git a/apps/client/src/widgets/react/FilesystemFriendlyName.tsx b/apps/client/src/widgets/react/FilesystemFriendlyName.tsxindex 24075befa0..9549343cda 100644--- a/apps/client/src/widgets/react/FilesystemFriendlyName.tsx+++ b/apps/client/src/widgets/react/FilesystemFriendlyName.tsx@@ -1,45 +1,9 @@+import { tidyFilesystemFriendlyName, toFilesystemFriendlyName } from "@triliumnext/commons";import type { RefObject } from "preact";import { useLayoutEffect, useRef } from "preact/hooks";import FormTextBox, { type FormTextBoxProps } from "./FormTextBox";-/**- * A text box for something that becomes a file name, which refuses what a file name cannot hold.- *- * Add or remove characters here and both passes follow. Only what no major filesystem accepts- * belongs in this list: Windows refuses these outright, `/` is the separator everywhere else, and- * everything left out of it, accented letters and other scripts included, makes a perfectly good- * file name. Control characters are blocked as well, below, since they cannot be written down here.- */-const FORBIDDEN_CHARACTERS = '<>:"/\\|?*';--/** Trailing dots and spaces are legal to type and impossible to save on Windows. */-const FORBIDDEN_AT_THE_END = /[. ]+$/;--/** Whether a single character is one no file name may contain. */-function isForbidden(character: string): boolean {- return FORBIDDEN_CHARACTERS.includes(character)- || (character.codePointAt(0) ?? 0) < 0x20;-}--/**- * Drops every character a file name may not contain, and nothing else.- *- * Applied to each keystroke, so it must leave a half-typed name alone: anything that trimmed or- * rearranged here would fight the person typing.- */-export function toFilesystemFriendlyName(value: string): string {- return [ ...value ].filter((character) => !isForbidden(character)).join("");-}--/**- * The same, plus what can only be settled once the name is finished: surrounding whitespace and a- * trailing dot, which are legal mid-edit and refused at save time.- */-export function tidyFilesystemFriendlyName(value: string): string {- return toFilesystemFriendlyName(value).trim().replace(FORBIDDEN_AT_THE_END, "");-}-export interface FilesystemFriendlyNamePropsextends Omit<FormTextBoxProps, "currentValue" | "onBlur" | "onChange" | "type"> {currentValue: string;diff --git a/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsx b/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsxindex c29217837f..475a3b5a1d 100644--- a/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsx+++ b/apps/client/src/widgets/react/FormPasswordWithConfirmation.spec.tsx@@ -69,6 +69,7 @@ describe("FormPasswordWithConfirmation", () => {expect(password.type).toBe("password");expect(confirmation.type).toBe("password");});+});function renderFields() {diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.tsindex 75699ebfd0..60d625767d 100644--- a/apps/server/src/backup_provider.spec.ts+++ b/apps/server/src/backup_provider.spec.ts@@ -1,5 +1,5 @@import { readBackupContainer } from "@triliumnext/backup-container";-import type { OptionNames } from "@triliumnext/commons";+import type { OptionNames, SetupBackupSettings } from "@triliumnext/commons";import { getLog, getSql, ws } from "@triliumnext/core";import fs from "fs";import os from "os";@@ -58,6 +58,25 @@ function backupNamesIn(directory: string) {return fs.existsSync(directory) ? fs.readdirSync(directory).sort() : [];}+/** Unwraps a container back to the bytes the stub database was made of. */+async function unwrapContainer(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();+}+beforeEach(() => {copyDatabase = vi.spyOn(getSql(), "copyDatabase").mockImplementation(writeStubDatabase);vi.spyOn(ws, "sendMessageToAllClients").mockImplementation(() => {});@@ -125,25 +144,6 @@ 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 () => {const backupFile = await desktopService(CUSTOM_DIR).backupNow("now");@@ -157,7 +157,7 @@ describe("ServerBackupService: backup format", () => {const backupFile = await service.backupNow("now");expect(backupFile).toBe(path.join(CUSTOM_DIR, "backup-now.tnbackup"));- expect(await unwrap(backupFile)).toBe("db-bytes");+ expect(await unwrapContainer(backupFile)).toBe("db-bytes");});it("writes an encrypted container, which only the passphrase opens", async () => {@@ -170,8 +170,8 @@ describe("ServerBackupService: backup format", () => {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"))+ expect(await unwrapContainer(backupFile, PASSPHRASE)).toBe("db-bytes");+ await expect(unwrapContainer(backupFile, "wrong")).rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });});@@ -184,7 +184,7 @@ describe("ServerBackupService: backup format", () => {const backupFile = await service.backupNow("now");- expect(await unwrap(backupFile, PASSPHRASE)).toBe("db-bytes");+ expect(await unwrapContainer(backupFile, PASSPHRASE)).toBe("db-bytes");});it("keeps one file per backup name, whichever format it was last written in", async () => {@@ -272,6 +272,100 @@ describe("ServerBackupService: backup format", () => {});});+describe("ServerBackupService.backupAs: the backup the setup screen asked for", () => {+ const PASSPHRASE = "correct horse battery staple";+ const withPassphrase: Partial<ServerBackupConfig> = { getPassphrase: async () => PASSPHRASE };++ /** What the screen sends, with the plainest backup there is as the starting point. */+ function asked(overrides: Partial<SetupBackupSettings> = {}): SetupBackupSettings {+ return {+ name: "Before the import",+ passphrase: "",+ useStoredPassphrase: false,+ compress: false,+ ...overrides+ };+ }++ it("writes it under the name the user gave it, spaces and all", async () => {+ const written = await desktopService(CUSTOM_DIR).backupAs(asked());++ // A plain database copy rather than a container, which is what nothing asked for looks like.+ expect(written.fileName).toBe("Before the import.db");+ expect(written.directoryPath).toBe(CUSTOM_DIR);+ });++ it("locks it with the password typed on the screen, over anything the instance is set up for", async () => {+ // Encryption is off in the options, and there is a stored passphrase that is not this one:+ // what the user typed while asking is what the backup is written with.+ const service = desktopService(CUSTOM_DIR, {}, withPassphrase);++ const written = await service.backupAs(asked({ passphrase: "typed-here" }));++ expect(written.fileName).toBe("Before the import.tnbackup");+ expect(await unwrapContainer(written.filePath, "typed-here")).toBe("db-bytes");+ await expect(unwrapContainer(written.filePath, PASSPHRASE))+ .rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });+ });++ it("locks it with the stored passphrase where that is what was asked for", async () => {+ // The one the screen cannot show and so cannot have sent: asking for it is the only way.+ const service = desktopService(CUSTOM_DIR, {}, withPassphrase);++ const written = await service.backupAs(asked({ useStoredPassphrase: true, passphrase: "ignored" }));++ expect(written.fileName).toBe("Before the import.tnbackup");+ expect(await unwrapContainer(written.filePath, PASSPHRASE)).toBe("db-bytes");+ });++ it("leaves it unlocked where the user cleared the password, however the instance backs up", async () => {+ const service = desktopService(+ CUSTOM_DIR,+ { backupEnableEncryption: "true", backupEnableCompression: "true" },+ withPassphrase+ );++ const written = await service.backupAs(asked());++ // Neither locked nor wrapped, so not a container at all: a plain database copy.+ expect(written.fileName).toBe("Before the import.db");+ });++ it("compresses because the screen said so, not because the option says so", async () => {+ const compressed = await desktopService(CUSTOM_DIR).backupAs(asked({ compress: true }));+ expect(compressed.fileName).toBe("Before the import.tnbackup");+ expect(await unwrapContainer(compressed.filePath)).toBe("db-bytes");++ const plain = await desktopService(CUSTOM_DIR, { backupEnableCompression: "true" })+ .backupAs(asked({ name: "Plain" }));+ expect(plain.fileName).toBe("Plain.db");+ });++ it("falls back to an unencrypted local copy where the stored passphrase turns out to be unreadable", async () => {+ // Only reachable if the keyring fails between the screen being told there is a passphrase+ // and the backup asking for it. A backup is still worth more than no backup.+ const service = desktopService(CUSTOM_DIR, {}, { getPassphrase: async () => null });++ const written = await service.backupAs(asked({ useStoredPassphrase: true }));++ // Unlocked, and so kept out of the chosen directory: that one is typically a synced folder,+ // which is the very thing encryption was turned on to keep a readable database out of.+ expect(written.fileName).toBe("Before the import.db");+ expect(written.directoryPath).toBe(DEFAULT_DIR);+ expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(+ expect.objectContaining({ type: "toast", message: expect.stringContaining("not encrypted") })+ );+ });++ it("says whether there is a stored passphrase, which is all the screen is allowed to learn", async () => {+ await expect(desktopService("", {}, withPassphrase).hasStoredPassphrase()).resolves.toBe(true);+ await expect(desktopService("", {}, { getPassphrase: async () => null }).hasStoredPassphrase())+ .resolves.toBe(false);+ // A build with no keyring behind it at all, which is every server deployment.+ await expect(desktopService("").hasStoredPassphrase()).resolves.toBe(false);+ });+});+describe("ServerBackupService: when the backup passphrase cannot be read", () => {const noPassphrase: Partial<ServerBackupConfig> = { getPassphrase: async () => null };diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.tsindex f203ed76a3..845d0d5810 100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@ -3,11 +3,15 @@ import {peekBackupContainer,writeBackupContainer} from "@triliumnext/backup-container";-import type { DatabaseBackup, SetupExistingBackup } from "@triliumnext/commons";+import type {+ DatabaseBackup,+ SetupBackupSettings,+ SetupExistingBackup+} from "@triliumnext/commons";import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService, utils as coreUtils, ws } from "@triliumnext/core";+import type { Response } from "express";import fs from "fs";import fsp from "fs/promises";-import type { Response } from "express";import { t } from "i18next";import path from "path";@@ -105,37 +109,30 @@ export default class ServerBackupService extends BackupService {}/**- * Writes a backup under the given name, and says what was written.+ * Writes the backup the setup screen asked for, and says what was written.*- * The name is used as it stands, spaces and all, because the setup screen shows it to the user- * and the user then goes looking for it in a file manager. It never reaches a shell, and the- * directory is this instance's own, so the sanitising `backupNow` does for names that arrive- * from a schedule would only make this one harder to read.+ * The name is used as it stands, spaces and all, because the screen shows it to the user and+ * the user then goes looking for it in a file manager. It is safe to use that way because it+ * has already been reduced to a single file name on its way in, which is what keeps a name+ * arriving over a request from naming somewhere else entirely.*/override async backupAs(- baseName: string,+ settings: SetupBackupSettings,onProgress?: (fraction: number) => void): Promise<SetupExistingBackup> {- const written = await syncMutexService.doExclusively(async () => {- const format = await this.resolveFormat();+ const filePath = await syncMutexService.doExclusively(async () => {+ const format = await this.resolveFormat(settings);const directory = (format.keepLocal ? null : this.getCustomBackupDir()) ?? getDefaultBackupDir();- return {- filePath: await writeBackup(directory, baseName, format, "default", onProgress),- // What was actually written, not what was asked for: encryption falls back to an- // unencrypted local copy where the passphrase cannot be read, and the screen that- // tells the user to keep their password safe must not appear over one of those.- encrypted: format.passphrase !== null- };+ return await writeBackup(directory, settings.name, format, "default", onProgress);});- const stat = fs.statSync(written.filePath);+ const stat = fs.statSync(filePath);return {- fileName: path.basename(written.filePath),- filePath: written.filePath,- directoryPath: path.dirname(written.filePath),- fileSize: stat.size,- encrypted: written.encrypted+ fileName: path.basename(filePath),+ filePath,+ directoryPath: path.dirname(filePath),+ fileSize: stat.size};}@@ -181,20 +178,38 @@ export default class ServerBackupService extends BackupService {return fs.existsSync(resolvedPath) ? resolvedPath : null;}+ /** Whether there is a passphrase to be had, without letting the caller learn what it is. */+ override async hasStoredPassphrase(): Promise<boolean> {+ return !!(await this.config.getPassphrase?.());+ }+/**- * 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.+ * Settles what the backup is written as, from what the user asked for where they were asked at+ * all, and from the instance's own options where they were not.+ *+ * Compression needs nothing but the answer. Encryption also needs a passphrase, and where the+ * stored one was asked for and cannot be read the backup falls back to being unencrypted and+ * local rather than not being taken at all.+ *+ * @param settings what the setup screen asked for; absent for the scheduled backups, which run+ * with nobody there to ask.*/- private async resolveFormat(): Promise<BackupFormat> {+ private async resolveFormat(settings?: SetupBackupSettings): 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 compress = settings?.compress ?? isEnabled("backupEnableCompression");++ // A backup someone asked for carries the password they typed while asking. Wanting the+ // stored one instead is a request rather than a value, since the passphrase is kept where+ // the interface that asked cannot read it.+ const useStored = settings+ ? settings.useStoredPassphrase+ : isEnabled("backupEnableEncryption");+ if (!useStored) {+ return { compress, passphrase: settings?.passphrase || null, keepLocal: false };}const passphrase = (await this.config.getPassphrase?.()) ?? null;diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 8be85cc33f..42a9d03a14 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -28,6 +28,7 @@ export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";// barrel is imported by virtually every client module. Import them via their subpath instead,// e.g. "@triliumnext/commons/src/lib/spreadsheet/render_to_html".export * from "./lib/backup_name.js";+export * from "./lib/filesystem_name.js";export * from "./lib/electron_api_interface.js";export * from "./lib/setup_marker.js";export * from "./lib/standalone_api_interface.js";diff --git a/packages/commons/src/lib/filesystem_name.spec.ts b/packages/commons/src/lib/filesystem_name.spec.tsnew file mode 100644index 0000000000..1378e39df8--- /dev/null+++ b/packages/commons/src/lib/filesystem_name.spec.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";++import { asFileName, tidyFilesystemFriendlyName, toFilesystemFriendlyName } from "./filesystem_name.js";++describe("what a file name may hold", () => {+ it("keeps everything a file name can carry, other scripts included", () => {+ expect(toFilesystemFriendlyName("Backup 2026-08-08 16-30-32"))+ .toBe("Backup 2026-08-08 16-30-32");+ expect(toFilesystemFriendlyName("Sicherungskopie (Änderungen)"))+ .toBe("Sicherungskopie (Änderungen)");+ expect(toFilesystemFriendlyName("備份")).toBe("備份");+ });++ it("drops what no filesystem would take", () => {+ expect(toFilesystemFriendlyName('a<b>c:d"e/f\\g|h?i*j')).toBe("abcdefghij");+ // Control characters, which cannot be written down as themselves here.+ expect(toFilesystemFriendlyName(`before${String.fromCharCode(1)}after${String.fromCharCode(31)}end`))+ .toBe("beforeafterend");+ });++ it("leaves a half-typed name alone, since it runs on every keystroke", () => {+ // A trailing space or dot is on its way to becoming a word; tidying here would delete what+ // the user is in the middle of typing.+ expect(toFilesystemFriendlyName("Before the ")).toBe("Before the ");+ expect(toFilesystemFriendlyName("v1.")).toBe("v1.");+ });++ it("tidies the edges only once the name is finished", () => {+ expect(tidyFilesystemFriendlyName(" Before the import ")).toBe("Before the import");+ // Legal to type, impossible to save on Windows.+ expect(tidyFilesystemFriendlyName("My backup...")).toBe("My backup");+ expect(tidyFilesystemFriendlyName("mixed. . ")).toBe("mixed");+ });+});++describe("asFileName", () => {+ it("hands back the tidied name where there is one to be had", () => {+ expect(asFileName(" Trilium data (2026-08-08 16-30-32) ")).toBe("Trilium data (2026-08-08 16-30-32)");+ });++ it("refuses a name that nothing usable is left of", () => {+ expect(asFileName("")).toBeNull();+ expect(asFileName(" /// ")).toBeNull();+ expect(asFileName("...")).toBeNull();+ });++ it("refuses the device names Windows keeps for itself, in any case", () => {+ // A file called this cannot be created there whatever extension is put on the end of it.+ expect(asFileName("NUL")).toBeNull();+ expect(asFileName("com1")).toBeNull();+ expect(asFileName("Aux")).toBeNull();+ // Only the names themselves, not everything starting with them.+ expect(asFileName("nullify")).toBe("nullify");+ });++ it("never answers with something that reaches outside the directory it is resolved against", () => {+ // A name arriving over a request is not a name any field has vetted, and the side that+ // opens the file resolves it against a directory of its own choosing.+ expect(asFileName("../../etc/passwd")).toBe("....etcpasswd");+ expect(asFileName("..\\..\\Windows\\System32")).toBe("....WindowsSystem32");+ expect(asFileName("/absolute/path")).toBe("absolutepath");+ expect(asFileName("..")).toBeNull();+ });+});diff --git a/packages/commons/src/lib/filesystem_name.ts b/packages/commons/src/lib/filesystem_name.tsnew file mode 100644index 0000000000..4f5a349d2a--- /dev/null+++ b/packages/commons/src/lib/filesystem_name.ts@@ -0,0 +1,66 @@+/**+ * Turning something a user typed into something a file can be called.+ *+ * Shared rather than kept beside the field that asks for the name, because the name is asked for in+ * one place and written in another: the setup screen types it, and the backend writes the file. A+ * name arriving over a request is not a name the field has vetted, so the side that opens the file+ * applies these rules again rather than trusting that it did.+ *+ * @module+ */++/**+ * Characters no file name may contain.+ *+ * Only what no major filesystem accepts belongs in this list: Windows refuses these outright and+ * `/` is the separator everywhere else. Everything left out of it, accented letters and other+ * scripts included, makes a perfectly good file name. Control characters are refused as well,+ * below, since they cannot be written down here.+ */+export const FORBIDDEN_FILE_NAME_CHARACTERS = '<>:"/\\|?*';++/** Trailing dots and spaces are legal to type and impossible to save on Windows. */+const FORBIDDEN_AT_THE_END = /[. ]+$/;++/** Reserved device names on Windows, which cannot be a file name there whatever the extension. */+const RESERVED_FILE_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;++/**+ * Drops every character a file name may not contain, and nothing else.+ *+ * Applied to each keystroke where a name is being typed, so it must leave a half-typed name alone:+ * anything that trimmed or rearranged here would fight the person typing.+ */+export function toFilesystemFriendlyName(value: string): string {+ return [ ...value ].filter((character) => !isForbidden(character)).join("");+}++/**+ * The same, plus what can only be settled once the name is finished: surrounding whitespace and a+ * trailing dot, which are legal mid-edit and refused at save time.+ */+export function tidyFilesystemFriendlyName(value: string): string {+ return toFilesystemFriendlyName(value).trim().replace(FORBIDDEN_AT_THE_END, "");+}++/**+ * What the file ends up called, or `null` where nothing usable is left of what was given.+ *+ * The two cases a caller has to have an answer for are a name that empties itself out and one of+ * the device names Windows reserves; both leave the caller to fall back on a name of its own rather+ * than on a file that cannot be created.+ *+ * Separators are among the characters dropped, so what comes back is a single name and never a+ * path: a caller may resolve it against a directory of its choosing without it reaching outside.+ */+export function asFileName(value: string): string | null {+ const tidied = tidyFilesystemFriendlyName(value);++ return tidied && !RESERVED_FILE_NAMES.test(tidied) ? tidied : null;+}++/** Whether a single character is one no file name may contain. */+function isForbidden(character: string): boolean {+ return FORBIDDEN_FILE_NAME_CHARACTERS.includes(character)+ || (character.codePointAt(0) ?? 0) < 0x20;+}diff --git a/packages/commons/src/lib/setup_marker.ts b/packages/commons/src/lib/setup_marker.tsindex 342feeb819..87d382b6d6 100644--- a/packages/commons/src/lib/setup_marker.ts+++ b/packages/commons/src/lib/setup_marker.ts@@ -24,6 +24,50 @@ export const SETUP_MARKER_FILE_NAME = "setup.json";*/export type SetupTargetScreen = "restore-backup" | "backup-database";+/**+ * What the user settled on before a backup taken from the setup screen was written.+ *+ * Everything here is a question the screen asked, so that a backup taken by hand is not silently+ * governed by settings meant for the unattended ones: this is the moment a user is deciding what+ * happens to their data, and it is the one moment worth asking in.+ */+export interface SetupBackupSettings {+ /** What to call it, before the extension the format decides on. */+ name: string;+ /**+ * The password to lock it with. Empty leaves it unlocked, unless {@link useStoredPassphrase}.+ */+ passphrase: string;+ /**+ * Lock it with the passphrase the instance already keeps, rather than with {@link passphrase}.+ *+ * That passphrase lives in the OS keyring and is deliberately never readable from the interface+ * — only the backend ever sees it again. So a user asking for the password they already+ * configured can only ask for it, not type it back, which is what this is.+ */+ useStoredPassphrase: boolean;+ /** Whether to compress it. */+ compress: boolean;+}++/**+ * What the instance is already configured for, which is what the screen offers as its answers.+ *+ * Read from the options of the database the wizard was booted away from, so a user who has set all+ * of this up once is not asked to decide it again from scratch.+ */+export interface SetupBackupDefaults {+ /**+ * Whether there is a stored passphrase to lock the backup with, and so whether the screen has a+ * "use the one I configured" to offer at all.+ */+ storedPassphrase: boolean;+ /** Whether the instance encrypts its backups, which decides whether that is offered ticked. */+ encrypt: boolean;+ /** Whether the instance compresses its backups. */+ compress: boolean;+}+/** A backup the setup screen took of the database it is about to replace. */export interface SetupExistingBackup {fileName: string;@@ -37,8 +81,6 @@ export interface SetupExistingBackup {*/directoryPath: string;fileSize: number;- /** Whether it is encrypted, which decides whether the user needs their backup password to use it. */- encrypted: boolean;}/**diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex caf78a6800..f2ad8d403c 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -3,6 +3,7 @@ import setupService from "../../services/setup.js";import { getRunningSetupOperation, withSetupLock } from "../../services/setup_lock.js";import {deleteExistingData,+ getExistingBackupDefaults,getExistingBackupStatus,keepExistingData,startBackUpExistingData@@ -63,9 +64,24 @@ async function bootToSetup(req: Request) {* on a large database, and on standalone a request rides the service worker, whose fetches the* browser reclaims after a few minutes no matter how patient the caller is. The screen follows the* write, and learns where it went, through {@link existingBackupStatus}.+ *+ * What the user chose on the way in arrives in the body, and is treated as a request rather than as+ * an instruction: nothing in it is trusted, and anything missing falls back to what the instance is+ * already configured for.+ */+function backUpExisting(req: Request) {+ startBackUpExistingData(new Date(), req.body);+}++/**+ * What the screen asking those questions offers as its answers: how this instance already backs up.+ *+ * Says whether a passphrase is stored rather than what it is. The passphrase is kept where the+ * interface cannot read it, which is exactly why the screen has to offer using it as a choice+ * instead of filling it into a box.*/-function backUpExisting() {- startBackUpExistingData(new Date());+function existingBackupDefaults() {+ return getExistingBackupDefaults();}/**@@ -175,6 +191,7 @@ export default {getStatus,bootToSetup,backUpExisting,+ existingBackupDefaults,existingBackupStatus,deleteExisting,keepExisting,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 7e4922c1e3..069d45535f 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -176,6 +176,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans// Without a transaction, on every platform: the backup runs for minutes with the database in// use, and erasing or keeping it closes the connection any transaction would belong to.asyncRouteWithoutTransaction(PST, "/api/setup/existing/backup", [checkAppNotInitialized], setupApiRoute.backUpExisting, apiResultHandler);+ asyncRouteWithoutTransaction(GET, "/api/setup/existing/backup-defaults", [checkAppNotInitialized], setupApiRoute.existingBackupDefaults, apiResultHandler);asyncRouteWithoutTransaction(GET, "/api/setup/existing/status", [checkAppNotInitialized], setupApiRoute.existingBackupStatus, apiResultHandler);asyncRouteWithoutTransaction(PST, "/api/setup/existing/delete", [checkAppNotInitialized], setupApiRoute.deleteExisting, apiResultHandler);asyncRouteWithoutTransaction(PST, "/api/setup/existing/keep", [checkAppNotInitialized], setupApiRoute.keepExisting, apiResultHandler);diff --git a/packages/trilium-core/src/services/backup.ts b/packages/trilium-core/src/services/backup.tsindex cc5ac8d674..b64179b59c 100644--- a/packages/trilium-core/src/services/backup.ts+++ b/packages/trilium-core/src/services/backup.ts@@ -1,4 +1,10 @@-import type { DatabaseBackup, FilterOptionsByType, OptionNames, SetupExistingBackup } from "@triliumnext/commons";+import type {+ DatabaseBackup,+ FilterOptionsByType,+ OptionNames,+ SetupBackupSettings,+ SetupExistingBackup+} from "@triliumnext/commons";import type { Response } from "express";import { getContext } from "./context.js";@@ -31,17 +37,33 @@ export default abstract class BackupService {abstract backupNow(name: string): Promise<string>;/**- * Create a backup under a name of the caller's choosing, reporting what was written.+ * Create a backup the user has just described, reporting what was written.** For the setup screen's offer to save the existing database before replacing it, where the user* is shown the file afterwards and so has to be told its name, its path and its size. Left out by* platforms with nowhere to write a file the user could then find.*+ * Unlike {@link backupNow}, which runs to a schedule and so can only follow the instance's+ * options, this one is asked for by a person who was standing there answering questions about+ * it. What they answered arrives in `settings` and is what the backup is written as.+ ** @param onProgress how far through the write it is, from 0 to 1. A backup of a large knowledge* base runs for minutes, and a screen with nothing to show for that long is* indistinguishable from one that has stopped.*/- backupAs?(baseName: string, onProgress?: (fraction: number) => void): Promise<SetupExistingBackup>;+ backupAs?(+ settings: SetupBackupSettings,+ onProgress?: (fraction: number) => void+ ): Promise<SetupExistingBackup>;++ /**+ * Whether a passphrase is stored that a backup could be locked with.+ *+ * Answers with a yes or a no and never with the passphrase itself, which is the whole point:+ * the screen offering "use the password I configured" has to know whether there is one, and+ * must not be able to learn what it is. Left out by platforms that keep no passphrase.+ */+ hasStoredPassphrase?(): Promise<boolean>;/*** Perform regular scheduled backups (daily, weekly, monthly).diff --git a/packages/trilium-core/src/services/setup_existing.spec.ts b/packages/trilium-core/src/services/setup_existing.spec.tsindex 0d23d6a048..cd2ad9cc1a 100644--- a/packages/trilium-core/src/services/setup_existing.spec.ts+++ b/packages/trilium-core/src/services/setup_existing.spec.ts@@ -1,12 +1,16 @@+import type { SetupBackupSettings } from "@triliumnext/commons";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getBackup } from "./backup.js";+import optionService from "./options.js";import {backUpExistingData,deleteExistingData,+ getExistingBackupDefaults,getExistingBackupProgress,getExistingBackupStatus,keepExistingData,+ resolveBackupSettings,startBackUpExistingData} from "./setup_existing.js";import { enterSetupMode, initSetupPlatform, leaveSetupMode } from "./setup_mode.js";@@ -17,6 +21,14 @@ const platform = {removeDatabase: vi.fn(async () => {})};+/** Whatever the screen would have sent, for the tests that are not about the settings themselves. */+const ANY_SETTINGS: SetupBackupSettings = {+ name: "Backup",+ passphrase: "",+ useStoredPassphrase: false,+ compress: false+};+beforeEach(() => {Object.values(platform).forEach((fn) => fn.mockClear());initSetupPlatform(platform);@@ -31,18 +43,23 @@ afterEach(() => {describe("what becomes of the existing database", () => {it("backs it up through the platform's own backup service", async () => {- const written = { fileName: "Backup.tnbackup", filePath: "/b/Backup.tnbackup", fileSize: 12, encrypted: true };- const backupAs = vi.fn(async (_name: string, _onProgress?: (fraction: number) => void) => written);+ const written = { fileName: "Backup.tnbackup", filePath: "/b/Backup.tnbackup", fileSize: 12 };+ const backupAs = vi.fn(async (_settings: SetupBackupSettings, _onProgress?: (fraction: number) => void) => written);// Assigned rather than spied: the method is optional, and a platform without one is exactly// what the service checks for.const backup = getBackup() as { backupAs?: typeof backupAs };const previous = backup.backupAs;backup.backupAs = backupAs;- await expect(backUpExistingData(new Date(2026, 7, 7, 10, 32, 21))).resolves.toEqual(written);- // The name every platform suggests, which commons settles and its own tests cover.- expect(backupAs)- .toHaveBeenCalledWith("Trilium data (2026-08-07 10-32-21)", expect.any(Function));+ const settings: SetupBackupSettings = {+ name: "Before the import",+ passphrase: "hunter2",+ useStoredPassphrase: false,+ compress: true+ };+ await expect(backUpExistingData(settings)).resolves.toEqual(written);+ // Handed on as it stands: what the user answered is what the backup is written as.+ expect(backupAs).toHaveBeenCalledWith(settings, expect.any(Function));// Nothing is erased by taking a copy of it.expect(platform.removeDatabase).not.toHaveBeenCalled();@@ -53,14 +70,14 @@ describe("what becomes of the existing database", () => {const seen: (number | null)[] = [];const backup = getBackup() as { backupAs?: unknown };const previous = backup.backupAs;- backup.backupAs = async (_name: string, onProgress?: (fraction: number) => void) => {+ backup.backupAs = async (_settings: SetupBackupSettings, onProgress?: (fraction: number) => void) => {seen.push(getExistingBackupProgress());onProgress?.(0.5);seen.push(getExistingBackupProgress());- return { fileName: "b", filePath: "/b", fileSize: 1, encrypted: false };+ return { fileName: "b", filePath: "/b", fileSize: 1 };};- await backUpExistingData(new Date());+ await backUpExistingData(ANY_SETTINGS);expect(seen).toEqual([ 0, 0.5 ]);// Nothing is running any more, which is what the screen needs to stop drawing a bar.@@ -86,7 +103,7 @@ describe("what becomes of the existing database", () => {it("refuses every one of them where there is no existing database to act on", async () => {leaveSetupMode();- await expect(backUpExistingData(new Date())).rejects.toThrow(/first time/);+ await expect(backUpExistingData(ANY_SETTINGS)).rejects.toThrow(/first time/);await expect(deleteExistingData()).rejects.toThrow(/first time/);await expect(keepExistingData()).rejects.toThrow(/first time/);expect(platform.removeDatabase).not.toHaveBeenCalled();@@ -94,12 +111,114 @@ describe("what becomes of the existing database", () => {});});+describe("what a backup asked for over a request is written as", () => {+ const now = new Date(2026, 7, 7, 10, 32, 21);+ const SUGGESTED_NAME = "Trilium data (2026-08-07 10-32-21)";++ /** Makes the instance's own backup settings say what the fallbacks are read out of. */+ function instanceBacksUp({ compress = false, encrypt = false }) {+ vi.spyOn(optionService, "getOptionOrNull").mockImplementation((name) => {+ if (name === "backupEnableCompression") return compress ? "true" : "false";+ if (name === "backupEnableEncryption") return encrypt ? "true" : "false";+ return null;+ });+ }++ it("takes the answers the screen sent", () => {+ expect(resolveBackupSettings(now, {+ name: "Before the import",+ passphrase: "hunter2",+ useStoredPassphrase: false,+ compress: true+ })).toEqual({+ name: "Before the import",+ passphrase: "hunter2",+ useStoredPassphrase: false,+ compress: true+ });+ });++ it("names it after the moment where nothing usable was asked for", () => {+ expect(resolveBackupSettings(now, {}).name).toBe(SUGGESTED_NAME);+ expect(resolveBackupSettings(now, { name: " " }).name).toBe(SUGGESTED_NAME);+ expect(resolveBackupSettings(now, undefined).name).toBe(SUGGESTED_NAME);+ // A caller may send anything at all, including something that is not an object.+ expect(resolveBackupSettings(now, "a backup, please").name).toBe(SUGGESTED_NAME);+ });++ it("reduces a name that would have named somewhere else to one that names a file", () => {+ // The name crosses a request boundary and is then resolved against the backup directory, so+ // it is the one field here that could reach outside it if it were taken at its word.+ expect(resolveBackupSettings(now, { name: "../../etc/passwd" }).name).toBe("....etcpasswd");+ expect(resolveBackupSettings(now, { name: "..\\..\\Windows" }).name).toBe("....Windows");+ expect(resolveBackupSettings(now, { name: ".." }).name).toBe(SUGGESTED_NAME);+ });++ it("reads no answer out of anything that is not one", () => {+ instanceBacksUp({});++ expect(resolveBackupSettings(now, { passphrase: 42, compress: "yes", useStoredPassphrase: 1 }))+ .toMatchObject({ passphrase: "", compress: false, useStoredPassphrase: false });+ });++ it("falls back on how the instance already backs up, where the caller said nothing", () => {+ // Which is what keeps a caller that knows nothing of these questions — anything older than+ // the screen that asks them — backing up exactly as it did before.+ instanceBacksUp({ compress: true, encrypt: true });++ expect(resolveBackupSettings(now, {}))+ .toMatchObject({ useStoredPassphrase: true, compress: true });+ });++ it("lets the screen turn off what the instance turns on", () => {+ instanceBacksUp({ compress: true, encrypt: true });++ expect(resolveBackupSettings(now, { useStoredPassphrase: false, compress: false }))+ .toMatchObject({ useStoredPassphrase: false, compress: false });+ });+});++describe("what the screen is offered as its answers", () => {+ /** Puts a stored passphrase in place, or takes the whole notion of one away. */+ function stubStoredPassphrase(hasOne: boolean | undefined) {+ const backup = getBackup() as { hasStoredPassphrase?: (() => Promise<boolean>) | undefined };+ const previous = backup.hasStoredPassphrase;+ backup.hasStoredPassphrase = hasOne === undefined ? undefined : async () => hasOne;++ return () => {+ backup.hasStoredPassphrase = previous;+ };+ }++ it("reports how the instance backs up, and whether there is a passphrase rather than what it is", async () => {+ vi.spyOn(optionService, "getOptionOrNull").mockImplementation((name) =>+ name === "backupEnableEncryption" ? "true" : "false");+ const restore = stubStoredPassphrase(true);++ await expect(getExistingBackupDefaults()).resolves.toEqual({+ storedPassphrase: true,+ encrypt: true,+ compress: false+ });++ restore();+ });++ it("offers nothing of the sort where the platform keeps no passphrase", async () => {+ const restore = stubStoredPassphrase(undefined);++ await expect(getExistingBackupDefaults()).resolves.toMatchObject({ storedPassphrase: false });++ restore();+ });+});+describe("the started backup, followed through its status", () => {/** Puts a controllable backupAs in place and gives back the strings to pull. */function stubBackup(behaviour: (onProgress?: (fraction: number) => void) => Promise<unknown>) {const backup = getBackup() as { backupAs?: unknown };const previous = backup.backupAs;- backup.backupAs = (_name: string, onProgress?: (fraction: number) => void) =>+ backup.backupAs = (_settings: SetupBackupSettings, onProgress?: (fraction: number) => void) =>behaviour(onProgress);return () => {@@ -108,7 +227,7 @@ describe("the started backup, followed through its status", () => {}it("runs with a live fraction, joins a second start, and ends holding what was written", async () => {- const written = { fileName: "b", filePath: "/b", fileSize: 1, encrypted: false };+ const written = { fileName: "b", filePath: "/b", fileSize: 1 };let report: ((fraction: number) => void) | undefined;let finish!: (value: typeof written) => void;const restore = stubBackup((onProgress) => new Promise((resolve) => {diff --git a/packages/trilium-core/src/services/setup_existing.ts b/packages/trilium-core/src/services/setup_existing.tsindex e879f37c6f..767f09e801 100644--- a/packages/trilium-core/src/services/setup_existing.ts+++ b/packages/trilium-core/src/services/setup_existing.ts@@ -1,8 +1,16 @@-import { defaultBackupName, type SetupExistingBackup, type SetupExistingBackupStatus } from "@triliumnext/commons";+import {+ asFileName,+ defaultBackupName,+ type SetupBackupDefaults,+ type SetupBackupSettings,+ type SetupExistingBackup,+ type SetupExistingBackupStatus+} from "@triliumnext/commons";import { getBackup } from "./backup.js";import eventService from "./events.js";import { getLog } from "./log.js";+import optionService from "./options.js";import { getSetupPlatform, isInitialSetup, leaveSetupMode } from "./setup_mode.js";import sqlInit from "./sql_init.js";@@ -25,14 +33,13 @@ import sqlInit from "./sql_init.js";/*** Backs the existing database up, and says where it went.*- * The format is the one the instance is already configured for: compressed or not, encrypted or not,- * in the chosen directory or the default one. Nothing is asked again here, because the answer is in- * the options the user already gave, and this is not the moment to be asking about formats.- *- * @param now the moment to name the backup after; passed in so the name is the caller's to decide.+ * @param settings what the user answered on the screen before this one; already resolved by+ * {@link resolveBackupSettings}, so nothing here has to guess at a missing answer.* @throws Error where the platform cannot write a backup, or the write itself failed.*/-export async function backUpExistingData(now: Date): Promise<SetupExistingBackup> {+export async function backUpExistingData(+ settings: SetupBackupSettings+): Promise<SetupExistingBackup> {requireExistingData();const backup = getBackup();@@ -44,7 +51,7 @@ export async function backUpExistingData(now: Date): Promise<SetupExistingBackupprogress = 0;try {- const written = await backup.backupAs(defaultBackupName(now), reportProgress);+ const written = await backup.backupAs(settings, reportProgress);getLog().info(`Setup: the existing database was backed up (${written.fileSize} bytes).`);return written;@@ -53,6 +60,61 @@ export async function backUpExistingData(now: Date): Promise<SetupExistingBackup}}+/**+ * What the instance is already set up to do, which is what the screen offers as its answers.+ *+ * The stored passphrase is reported as a yes or a no and never as itself: a screen that could read+ * it could be made to hand it over, and it is the one thing standing between a stolen backup and+ * the knowledge base inside it.+ */+export async function getExistingBackupDefaults(): Promise<SetupBackupDefaults> {+ const backup = getBackup();++ return {+ storedPassphrase: (await backup.hasStoredPassphrase?.()) ?? false,+ encrypt: isOptionEnabled("backupEnableEncryption"),+ compress: isOptionEnabled("backupEnableCompression")+ };+}++/**+ * Settles what a backup asked for over a request is actually written as.+ *+ * Every field is treated as something a caller may have got wrong or left out rather than as an+ * answer: what arrives here has crossed a request boundary, and the name in particular goes on to+ * become a path. Anything missing falls back to what the instance is configured for, so a caller+ * that asks for nothing at all still gets the backup it would have got before there was anything to+ * ask.+ *+ * @param now the moment to name the backup after, where the caller named nothing usable.+ */+export function resolveBackupSettings(now: Date, requested: unknown): SetupBackupSettings {+ const asked = (typeof requested === "object" && requested !== null+ ? requested+ : {}) as Partial<Record<keyof SetupBackupSettings, unknown>>;++ return {+ // Reduced to a single name that no directory can be escaped from, whatever was sent.+ name: asFileName(typeof asked.name === "string" ? asked.name : "")+ ?? defaultBackupName(now),+ passphrase: typeof asked.passphrase === "string" ? asked.passphrase : "",+ useStoredPassphrase: typeof asked.useStoredPassphrase === "boolean"+ ? asked.useStoredPassphrase+ : isOptionEnabled("backupEnableEncryption"),+ compress: typeof asked.compress === "boolean"+ ? asked.compress+ : isOptionEnabled("backupEnableCompression")+ };+}++/**+ * Reads leniently, the way the backup itself does: setup runs against a database that has not been+ * migrated, so an option added by a newer version may not be there to read at all.+ */+function isOptionEnabled(name: "backupEnableCompression" | "backupEnableEncryption"): boolean {+ return optionService.getOptionOrNull(name) === "true";+}+/*** Starts the backup and answers at once, leaving the outcome to be polled for.*@@ -65,8 +127,11 @@ export async function backUpExistingData(now: Date): Promise<SetupExistingBackup* A backup already running is joined rather than doubled. What can be refused outright (no* existing database, a platform with nowhere to write) still throws from here, so the starting* request carries the reason.+ *+ * @param now the moment to name the backup after, where `requested` named nothing usable.+ * @param requested what the user answered on the screen before this one, as it arrived.*/-export function startBackUpExistingData(now: Date): void {+export function startBackUpExistingData(now: Date, requested?: unknown): void {if (status.state === "running") {return;}@@ -77,7 +142,7 @@ export function startBackUpExistingData(now: Date): void {}status = { state: "running", fraction: null };- backUpExistingData(now)+ backUpExistingData(resolveBackupSettings(now, requested)).then((written) => {status = { state: "done", fraction: 1, result: written };})