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/backup import: use a native file picker for the desktop client
Adorian Dorana1e3b3d77b0f
diff --git a/apps/client/src/setup_restore.css b/apps/client/src/setup_restore.cssindex b608359ec3..cd545281c7 100644--- a/apps/client/src/setup_restore.css+++ b/apps/client/src/setup_restore.css@@ -1,4 +1,20 @@.page.restore-from-backup {+ /* Two lines, not one sentence: what happened, then what the server said about it. */+ .page-error {+ .restore-error-headline {+ display: block;+ }++ .restore-error-detail {+ display: block;+ margin-top: 0.4em;+ opacity: 0.75;+ font-size: 0.85em;+ /* Filesystem errors arrive as one long line with no spaces to break at. */+ overflow-wrap: anywhere;+ }+ }+.restore-backup-row {display: flex;align-items: center;diff --git a/apps/client/src/setup_restore.spec.tsx b/apps/client/src/setup_restore.spec.tsxindex bc05d15f38..7a7a601573 100644--- a/apps/client/src/setup_restore.spec.tsx+++ b/apps/client/src/setup_restore.spec.tsx@@ -144,7 +144,7 @@ describe("uploading a backup", () => {fileName: "backup.db"}));expect(serverMock.post).toHaveBeenCalledWith("setup/restore/start", {- source: "uploaded",+ source: "pending",filePath: undefined,passphrase: undefined});@@ -168,11 +168,77 @@ describe("uploading a backup", () => {await chooseFile(new File([ "database bytes" ], "backup.db"));- expect(container.textContent).toContain("setup.restore-upload-failed");+ expect(container.querySelector(".restore-error-headline")?.textContent).toBe("setup.restore-error-upload-failed");+ expect(container.querySelector(".restore-error-detail")?.textContent).toBe("the disk is full");expect(container.querySelector(".restore-file-input")).toBeTruthy();});});+describe("choosing a backup on the desktop", () => {+ const pickBackup = vi.fn();++ beforeEach(() => {+ window.electronApi = { restore: { pickBackup } } as unknown as typeof window.electronApi;+ });++ afterEach(() => {+ window.electronApi = undefined;+ });++ it("uses the native picker instead of a file input, and restores what it puts forward", async () => {+ pickBackup.mockResolvedValue({ status: "selected", fileName: "backup-daily.db", encrypted: false });+ renderRestore();+ await flushEffects();++ // Nothing to upload: the file never leaves the disk it is already on.+ expect(container.querySelector(".restore-file-input")).toBeFalsy();+ container.querySelector<HTMLElement>(".restore-file-section button")?.click();+ await flushEffects();++ expect(uploadMock.uploadInChunks).not.toHaveBeenCalled();+ expect(serverMock.post).toHaveBeenCalledWith("setup/restore/start", {+ source: "pending",+ filePath: undefined,+ passphrase: undefined+ });+ });++ it("asks for the password when the picked backup turns out to be encrypted", async () => {+ pickBackup.mockResolvedValue({ status: "selected", fileName: "backup.tnbackup", encrypted: true });+ renderRestore();+ await flushEffects();++ container.querySelector<HTMLElement>(".restore-file-section button")?.click();+ await flushEffects();++ expect(serverMock.post).not.toHaveBeenCalled();+ expect(container.querySelector("input[type=password]")).toBeTruthy();+ });++ it("stays where it is when the dialog is dismissed", async () => {+ pickBackup.mockResolvedValue({ status: "cancelled" });+ renderRestore();+ await flushEffects();++ container.querySelector<HTMLElement>(".restore-file-section button")?.click();+ await flushEffects();++ expect(serverMock.post).not.toHaveBeenCalled();+ expect(container.querySelector(".restore-error-headline")).toBeFalsy();+ });++ it("reports a refusal from the other side of the bridge", async () => {+ pickBackup.mockResolvedValue({ status: "error", message: "setup is already busy with 'new-document'" });+ renderRestore();+ await flushEffects();++ container.querySelector<HTMLElement>(".restore-file-section button")?.click();+ await flushEffects();++ expect(container.querySelector(".restore-error-detail")?.textContent).toBe("setup is already busy with 'new-document'");+ });+});+describe("following the restore", () => {async function startRestore() {renderRestore({ onRestored });@@ -236,4 +302,30 @@ describe("following the restore", () => {expect(container.textContent).toContain("The database is version 999.");expect(container.querySelector(".restore-file-input")).toBeTruthy();});++ it("leads with what went wrong in the user's terms, keeping the technical detail underneath", async () => {+ await startRestore();++ restore = { stage: "failed", reason: "not-a-database", error: "The file is not a SQLite database." };+ await nextPoll();++ // The reason chooses the sentence; the server's own words are kept, but not as the whole+ // message, since "not a SQLite database" answers a question the user never asked.+ expect(container.querySelector(".restore-error-headline")?.textContent).toBe("setup.restore-error-unusable");+ expect(container.querySelector(".restore-error-detail")?.textContent).toBe("The file is not a SQLite database.");+ });++ it("says something of its own for the failures where the backup is not what is at fault", async () => {+ await startRestore();+ const headline = () => container.querySelector(".restore-error-headline")?.textContent;++ restore = { stage: "failed", reason: "swap-failed", error: "EPERM" };+ await nextPoll();+ expect(headline()).toBe("setup.restore-error-swap-failed");++ await startRestore();+ restore = { stage: "failed", reason: "database-too-old", error: "version 200" };+ await nextPoll();+ expect(headline()).toBe("setup.restore-error-too-old");+ });});diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxindex 150fc63286..55302342d9 100644--- a/apps/client/src/setup_restore.tsx+++ b/apps/client/src/setup_restore.tsx@@ -1,6 +1,7 @@import "./setup_restore.css";import type { DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commons";+import type { ComponentChildren } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { uploadInChunks } from "./services/chunked_upload";@@ -38,12 +39,12 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =const [ step, setStep ] = useState<Step>("picking");const [ selection, setSelection ] = useState<Selection | null>(null);const [ upload, setUpload ] = useState<UploadState | null>(null);- const [ error, setError ] = useState<string | null>(null);+ const [ error, setError ] = useState<ComponentChildren>(null);const [ errorId, setErrorId ] = useState(0);const [ wrongPassphrase, setWrongPassphrase ] = useState(false);- const raiseError = useCallback((message: string) => {- setError(message);+ const raiseError = useCallback((headline: string, detail?: string) => {+ setError(<Failure headline={headline} detail={detail} />);setErrorId((id) => id + 1);}, []);@@ -65,7 +66,7 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =setStep("restoring");} catch (e) {setStep("picking");- raiseError(e instanceof Error ? e.message : String(e));+ raiseError(t("setup.restore-error-could-not-start"), detailOf(e));}}, [ raiseError ]);@@ -81,10 +82,10 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =onProgress: ({ sentBytes, totalBytes, fraction }) => setUpload({ sentBytes, totalBytes, fraction })});- await restore({ source: "uploaded", fileName: uploaded.fileName, encrypted: uploaded.encrypted });+ await restore({ source: "pending", fileName: uploaded.fileName, encrypted: uploaded.encrypted });} catch (e) {setStep("picking");- raiseError(t("setup.restore-upload-failed", { message: e instanceof Error ? e.message : String(e) }));+ raiseError(t("setup.restore-error-upload-failed"), detailOf(e));}}@@ -97,7 +98,7 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =}setStep("picking");- raiseError(failure.error ?? t("setup.restore-failed-generic"));+ raiseError(headlineFor(failure.reason), failure.error);}return (@@ -110,7 +111,7 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =errorId={errorId}onBack={step === "restoring" ? undefined : onBack}>- {step === "picking" && <PickBackup onPick={restore} onUpload={uploadAndRestore} />}+ {step === "picking" && <PickBackup onPick={restore} onUpload={uploadAndRestore} onFailure={raiseError} />}{step === "uploading" && upload && <UploadProgress upload={upload} />}{step === "passphrase" && selection && (<AskPassphrase@@ -129,9 +130,54 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =);}+/**+ * A failure as the user needs it: what went wrong in a sentence about backups, with the technical+ * detail kept underneath.+ *+ * The detail is not dropped, because it is what a bug report is made of and what tells two identical-+ * looking failures apart. It is just no longer the whole message: "The file is not a SQLite database"+ * answers a question nobody standing in front of this screen asked.+ */+function Failure({ headline, detail }: { headline: string; detail?: string }) {+ return (+ <>+ <span class="restore-error-headline">{headline}</span>+ {detail && <small class="restore-error-detail selectable-text">{detail}</small>}+ </>+ );+}++/** What a thrown failure has to say for itself, for the detail line under the headline. */+function detailOf(e: unknown): string | undefined {+ const message = e instanceof Error ? e.message : String(e);++ return message || undefined;+}++/**+ * The sentence for a failure, chosen from the reason the server reported rather than from its+ * message, which is fixed English meant for the log.+ *+ * Most of the reasons say the same thing to a user: the file cannot be used. The ones listed here are+ * the ones where that would be misleading, because something other than the backup is at fault or+ * because there is something the user could go and do about it.+ */+function headlineFor(reason: string | undefined): string {+ switch (reason) {+ case "database-too-new": return t("setup.restore-error-too-new");+ case "database-too-old": return t("setup.restore-error-too-old");+ case "database-not-initialized": return t("setup.restore-error-unfinished");+ case "swap-failed": return t("setup.restore-error-swap-failed");+ case "migration-failed": return t("setup.restore-error-would-not-open");+ case "restore-refused": return t("setup.restore-error-refused");+ default: return t("setup.restore-error-unusable");+ }+}+/** Which backup is being restored, and where it is. */interface Selection {- source: "uploaded" | "existing";+ /** `existing` names a backup on this device; `pending` is one the server already holds. */+ source: "pending" | "existing";fileName: string;/** Only for a backup already on the server. */filePath?: string;@@ -145,9 +191,29 @@ interface UploadState {}/** The backups already on this device, and the way to a file that is not. */-function PickBackup({ onPick, onUpload }: { onPick: (selection: Selection) => void; onUpload: (file: File) => void }) {+function PickBackup({ onPick, onUpload, onFailure }: {+ onPick: (selection: Selection) => void;+ onUpload: (file: File) => void;+ onFailure: (headline: string, detail?: string) => void;+}) {const [ backups, setBackups ] = useState<DatabaseBackup[] | null>(null);const fileInput = useRef<HTMLInputElement>(null);+ // The desktop can read the file where it lies; a browser has to be handed it first.+ const nativePicker = window.electronApi?.restore;++ async function pickNatively() {+ const picked = await nativePicker?.pickBackup();+ if (!picked || picked.status === "cancelled") {+ return;+ }+ if (picked.status === "error" || !picked.fileName) {+ onFailure(t("setup.restore-error-could-not-start"), picked.message);+ return;+ }++ // Already waiting on the other side of the bridge, so this goes straight to restoring it.+ onPick({ source: "pending", fileName: picked.fileName, encrypted: picked.encrypted });+ }useEffect(() => {server.get<ExistingBackupsResponse>("database/backups")@@ -196,26 +262,28 @@ function PickBackup({ onPick, onUpload }: { onPick: (selection: Selection) => vo<Card heading={t("setup.restore-from-a-file")}><CardSection className="restore-file-section">- <p>{t("setup.restore-from-a-file-description")}</p>-- <input- ref={fileInput}- type="file"- accept=".db,.tnbackup"- class="restore-file-input"- onChange={(e) => {- const file = (e.target as HTMLInputElement).files?.[0];- if (file) {- onUpload(file);- }- }}- />+ <p>{nativePicker ? t("setup.restore-from-a-file-description-native") : t("setup.restore-from-a-file-description")}</p>++ {!nativePicker && (+ <input+ ref={fileInput}+ type="file"+ accept=".db,.tnbackup"+ class="restore-file-input"+ onChange={(e) => {+ const file = (e.target as HTMLInputElement).files?.[0];+ if (file) {+ onUpload(file);+ }+ }}+ />+ )}<Buttonkind="primary"icon="bx bx-folder-open"text={t("setup.restore-choose-file")}- onClick={() => fileInput.current?.click()}+ onClick={nativePicker ? pickNatively : () => fileInput.current?.click()}/></CardSection></Card>diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 89f1563e32..350eeeea7f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3690,11 +3690,19 @@"restore-no-backups": "No backups were found on this device.","restore-from-a-file": "From a file","restore-from-a-file-description": "Choose a .db or .tnbackup file. Large backups are sent in pieces, so an interrupted transfer carries on rather than starting again.",+ "restore-from-a-file-description-native": "Choose a .db or .tnbackup file from this computer.","restore-choose-file": "Choose a backup file","restore-uploading": "Sending the backup...","restore-uploaded-so-far": "{{sent}} of {{total}}",- "restore-upload-failed": "The backup could not be sent: {{- message}}",- "restore-failed-generic": "The backup could not be restored.",+ "restore-error-unusable": "Unsupported or corrupted Trilium backup.",+ "restore-error-too-new": "This backup is from a newer version of Trilium. Update Trilium and try again.",+ "restore-error-too-old": "This backup is from a version of Trilium that is too old to be restored.",+ "restore-error-unfinished": "This backup was taken from a setup that was never finished, so there is nothing in it to restore.",+ "restore-error-swap-failed": "The database could not be replaced. Your previous database is back in place.",+ "restore-error-would-not-open": "The restored database could not be opened. Your previous database is back in place.",+ "restore-error-refused": "Another setup step is already running on this device.",+ "restore-error-could-not-start": "The restore could not be started.",+ "restore-error-upload-failed": "The backup could not be sent.","restore-passphrase": "Backup password","restore-passphrase-description": "This backup is encrypted. Enter the password it was created with.","restore-wrong-passphrase": "That password does not open this backup. Please try again.",diff --git a/apps/client/src/widgets/react/SetupPage.tsx b/apps/client/src/widgets/react/SetupPage.tsxindex ca48465178..9c9541e125 100644--- a/apps/client/src/widgets/react/SetupPage.tsx+++ b/apps/client/src/widgets/react/SetupPage.tsx@@ -18,7 +18,11 @@ import Button from "./Button";export default function SetupPage({ title, description, className, illustration, children, footer, error, errorId, onBack }: {title: string;description?: string;- error?: string | null;+ /**+ * A plain sentence, or a fragment for a failure that has more to say than one: what went wrong,+ * with the technical detail underneath it rather than in place of it.+ */+ error?: ComponentChildren;errorId?: number;className?: string;illustration?: ComponentChildren;@@ -47,7 +51,9 @@ export default function SetupPage({ title, description, className, illustration,{error && showError && (<Admonition className="page-error" type="caution"><ActionButton icon="bx bx-x" text={t("setup.dismiss-error")} onClick={() => setShowError(false)} />- {replaceHtmlEscapedSlashes(error)}+ {/* A message built from components renders as it was built; a bare sentence still+ gets the slashes a server error may have had escaped along the way. */}+ {typeof error === "string" ? replaceHtmlEscapedSlashes(error) : error}</Admonition>)}diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex a4ec6258f3..bea3dcaa43 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -41,6 +41,7 @@ const h = vi.hoisted(() => ({streamErrorHandlers: [] as Handler[],// Captured commandLine.appendSwitch calls.appendSwitch: vi.fn(),+ recoverInterruptedRestore: vi.fn(),onBeforeSendHeaders: vi.fn(),setName: vi.fn(),quit: vi.fn(),@@ -238,6 +239,11 @@ vi.mock("./services/auto_launch", () => ({}));vi.mock("./services/shell", () => ({ setupShellHandlers: vi.fn() }));vi.mock("./services/onenote", () => ({ setupOneNoteHandlers: vi.fn() }));+// Reaches the server's restore session, and through it the data directory, which this spec does not have.+vi.mock("./services/restore", () => ({ setupRestoreHandlers: vi.fn() }));+vi.mock("@triliumnext/server/src/services/database_restore.js", () => ({+ recoverInterruptedRestore: (...a: unknown[]) => h.recoverInterruptedRestore(...a)+}));vi.mock("./services/security_settings", () => ({getSecuritySettings: () => h.securitySettings,registerSecurityIpcHandlers: vi.fn()@@ -340,6 +346,13 @@ describe("main() bootstrap", () => {expect(h.streamErrorHandlers.length).toBe(2);expect(exitSpy).not.toHaveBeenCalled();+ // A restore interrupted partway through exchanging the files is undone before anything opens+ // the database. The "lang" switch is the first thing read out of it, so it comes after.+ expect(h.recoverInterruptedRestore).toHaveBeenCalled();+ const langSwitch = h.appendSwitch.mock.calls.findIndex(([ name ]) => name === "lang");+ expect(h.recoverInterruptedRestore.mock.invocationCallOrder[0])+ .toBeLessThan(h.appendSwitch.mock.invocationCallOrder[langSwitch]);+// Smooth-scroll disabled + linux switches + lang switch were appended.const switches = h.appendSwitch.mock.calls.map((c) => c[0]);expect(switches).toContain("disable-smooth-scrolling");diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex b31d801048..a0bf60fdde 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -40,6 +40,7 @@ import {import { setupOneNoteHandlers } from "./services/onenote";import { setupPrintingHandlers } from "./services/printing";import ElectronRequestProvider from "./services/request";+import { setupRestoreHandlers } from "./services/restore";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";import { setupShellHandlers } from "./services/shell";import { markStartupMetric, setupStartupMetricsIpc } from "./services/startup_metrics";@@ -135,6 +136,7 @@ export async function main() {setupPrintingHandlers();setupExportHandlers();setupImportHandlers();+ setupRestoreHandlers();setupDialogHandlers();registerSecurityIpcHandlers();registerBackupPassphraseIpcHandlers();diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 4e076e6970..31c72ddb99 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -699,4 +699,13 @@ describe("preload script", () => {expect(ipcRendererInvoked).toContainEqual({ channel: "dialog-pick-directory", args: [undefined] });});});++ describe("restore", () => {+ const restore = () => getGroup("restore");++ it("pickBackup invokes the open-dialog IPC channel, passing nothing it could steer", async () => {+ await restore().pickBackup();+ expect(ipcRendererInvoked).toContainEqual({ channel: "restore-pick-backup", args: [] });+ });+ });});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 7d003fe6a5..c3222ce66e 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -241,6 +241,12 @@ contextBridge.exposeInMainWorld("electronApi", {}},+ restore: {+ pickBackup() {+ return ipcRenderer.invoke("restore-pick-backup");+ }+ },+ws: {// Renderer → main process. Mirror channel name with the server-side// IpcMessagingProvider constants.diff --git a/apps/desktop/src/services/restore.spec.ts b/apps/desktop/src/services/restore.spec.tsnew file mode 100644index 0000000000..8740e05962--- /dev/null+++ b/apps/desktop/src/services/restore.spec.ts@@ -0,0 +1,118 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// --- electron mock: capture the IPC handlers and drive the dialog/window from the test ---+const electronMock = vi.hoisted(() => ({+ handlers: new Map<string, (...args: unknown[]) => unknown>(),+ handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => electronMock.handlers.set(channel, handler)),+ showOpenDialog: vi.fn<(...args: unknown[]) => Promise<{ canceled: boolean; filePaths: string[] }>>(),+ getFocusedWindow: vi.fn<() => object | null>(() => ({}))+}));++vi.mock("electron", () => ({+ default: {+ ipcMain: { handle: electronMock.handle },+ dialog: { showOpenDialog: electronMock.showOpenDialog },+ BrowserWindow: { getFocusedWindow: electronMock.getFocusedWindow }+ }+}));++vi.mock("i18next", () => ({ t: (key: string) => key }));++vi.mock("@triliumnext/core", () => ({+ getLog: () => ({ info: vi.fn(), error: vi.fn() }),+ utils: { safeExtractMessageAndStackFromError: (e: unknown) => String(e) }+}));++const sessionMock = vi.hoisted(() => ({+ setPendingBackup: vi.fn<(path: string, fileName: string, options: { consumable: boolean }) => unknown>()+}));+vi.mock("@triliumnext/server/src/services/restore_session.js", () => sessionMock);++import { setupRestoreHandlers } from "./restore.js";++/** Resolves the open-dialog mock to a user selection, or to a cancel when given nothing. */+function dialogReturns(filePath?: string) {+ electronMock.showOpenDialog.mockResolvedValue(+ filePath ? { canceled: false, filePaths: [ filePath ] } : { canceled: true, filePaths: [] }+ );+}++function pickBackup() {+ const handler = electronMock.handlers.get("restore-pick-backup");+ if (!handler) {+ throw new Error("the restore-pick-backup handler was never registered");+ }++ return handler() as Promise<{ status: string; fileName?: string; encrypted?: boolean; message?: string }>;+}++beforeEach(() => {+ vi.clearAllMocks();+ electronMock.handlers.clear();+ electronMock.getFocusedWindow.mockReturnValue({});+ sessionMock.setPendingBackup.mockReturnValue({ fileName: "backup-daily.db", encrypted: false });+ setupRestoreHandlers();+});++describe("choosing a backup to restore", () => {+ it("puts the chosen file forward, and answers with what it is rather than where it is", async () => {+ dialogReturns("/home/adorian/backups/backup-daily.db");++ const picked = await pickBackup();++ expect(sessionMock.setPendingBackup).toHaveBeenCalledWith(+ "/home/adorian/backups/backup-daily.db",+ "backup-daily.db",+ // Never consumable: it is the user's own file, not something uploaded to be consumed.+ { consumable: false }+ );+ expect(picked).toEqual({ status: "selected", fileName: "backup-daily.db", encrypted: false });+ // The path is the thing the renderer must never see, whatever else it is told.+ expect(JSON.stringify(picked)).not.toContain("/home/adorian");+ });++ it("passes on that a passphrase will be needed, which the header states in the clear", async () => {+ dialogReturns("/home/adorian/backups/backup-weekly.tnbackup");+ sessionMock.setPendingBackup.mockReturnValue({ fileName: "backup-weekly.tnbackup", encrypted: true });++ await expect(pickBackup()).resolves.toEqual({+ status: "selected", fileName: "backup-weekly.tnbackup", encrypted: true+ });+ });++ it("puts nothing forward when the dialog is dismissed", async () => {+ dialogReturns();++ await expect(pickBackup()).resolves.toEqual({ status: "cancelled" });+ expect(sessionMock.setPendingBackup).not.toHaveBeenCalled();+ });++ it("cannot open a dialog with no window to open it over", async () => {+ electronMock.getFocusedWindow.mockReturnValue(null);++ await expect(pickBackup()).resolves.toEqual({ status: "cancelled" });+ expect(electronMock.showOpenDialog).not.toHaveBeenCalled();+ });++ it("reports a refusal rather than throwing across the bridge", async () => {+ dialogReturns("/home/adorian/backups/backup-daily.db");+ sessionMock.setPendingBackup.mockImplementation(() => {+ throw new Error("Cannot start 'restore-backup': setup is already busy with 'new-document'.");+ });++ await expect(pickBackup()).resolves.toEqual({+ status: "error",+ message: "Cannot start 'restore-backup': setup is already busy with 'new-document'."+ });+ });++ it("offers the backup extensions first, and everything else after them", async () => {+ dialogReturns("/home/adorian/backups/backup-daily.db");++ await pickBackup();++ const [ , options ] = electronMock.showOpenDialog.mock.calls[0] as [ unknown, { properties: string[]; filters: { extensions: string[] }[] } ];+ expect(options.properties).toEqual([ "openFile" ]);+ expect(options.filters.map((filter) => filter.extensions)).toEqual([ [ "db", "tnbackup" ], [ "*" ] ]);+ });+});diff --git a/apps/desktop/src/services/restore.ts b/apps/desktop/src/services/restore.tsnew file mode 100644index 0000000000..a25f0e04c2--- /dev/null+++ b/apps/desktop/src/services/restore.ts@@ -0,0 +1,59 @@+import type { NativeBackupPickResult } from "@triliumnext/commons";+import { getLog, utils as coreUtils } from "@triliumnext/core";+import { setPendingBackup } from "@triliumnext/server/src/services/restore_session.js";+import { default as electron } from "electron";+import { t } from "i18next";+import { basename } from "path";++/**+ * Registers the desktop's own way of choosing a backup to restore, reachable only from the setup+ * screen's "restore from backup" step.+ *+ * The point is that a backup is a database: on a browser it has to be sent to the server before+ * anything can be done with it, which for one measured in gigabytes is an hour of uploading a file+ * that is already on the same disk. Here the file is simply pointed at and read where it lies.+ *+ * Security model: the renderer never supplies a path and never receives one. The OS dialog runs here+ * in the main process and is the only thing that can put a backup forward; what comes back is the+ * file's name and whether it is encrypted, which is all the screen needs to know. Unlike the native+ * import, no capability token crosses either — importing has to ask the user where the file should go+ * *after* they pick it, whereas picking a backup is the whole decision, so the pick can be acted on+ * at once and the renderer is left holding nothing it could replay.+ */+export function setupRestoreHandlers() {+ electron.ipcMain.handle("restore-pick-backup", async (): Promise<NativeBackupPickResult> => {+ const focusedWindow = electron.BrowserWindow.getFocusedWindow();+ if (!focusedWindow) {+ return { status: "cancelled" };+ }++ // Async dialog: showOpenDialogSync blocks the main process event loop (freezing the UI,+ // WebSockets and background tasks) for as long as the picker is open.+ const { canceled, filePaths } = await electron.dialog.showOpenDialog(focusedWindow, {+ title: t("restore.pick_backup_title"),+ properties: [ "openFile" ],+ filters: [+ { name: t("restore.backup_filter"), extensions: [ "db", "tnbackup" ] },+ { name: t("restore.any_file_filter"), extensions: [ "*" ] }+ ]+ });++ const filePath = canceled ? undefined : filePaths[0];+ if (!filePath) {+ return { status: "cancelled" };+ }++ try {+ const backup = setPendingBackup(filePath, basename(filePath), { consumable: false });+ getLog().info(`A backup was chosen for restoring (${backup.fileName}).`);++ return { status: "selected", ...backup };+ } catch (e) {+ // Setup being busy with something else is the expected one, e.g. a second window part-way+ // through its own restore.+ getLog().error(`A backup could not be chosen for restoring: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);++ return { status: "error", message: e instanceof Error ? e.message : String(e) };+ }+ });+}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex fc738e9be4..326173b5fa 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -383,6 +383,11 @@"import": {"invalid_file_grant": "The file selection has expired or is invalid. Please choose the file again."},+ "restore": {+ "pick_backup_title": "Choose a backup to restore",+ "backup_filter": "Trilium backup (*.db, *.tnbackup)",+ "any_file_filter": "All files"+ },"pdf": {"export_filter": "PDF Document (*.pdf)","unable-to-export-message": "The current note could not be exported as a PDF.",diff --git a/apps/server/src/routes/api/setup_restore.ts b/apps/server/src/routes/api/setup_restore.tsindex aa2c587bae..5e37a95cb9 100644--- a/apps/server/src/routes/api/setup_restore.ts+++ b/apps/server/src/routes/api/setup_restore.ts@@ -1,21 +1,15 @@-import { getBackup, getLog, holdSetup, NotFoundError, ValidationError, withSetupLock } from "@triliumnext/core";+import { getBackup, NotFoundError, ValidationError } from "@triliumnext/core";import type { Request } from "express";-import fs from "fs";import path from "path";import type ServerBackupService from "../../backup_provider.js";-import { createChunkedUpload } from "../../services/chunked_upload.js";-import dataDir from "../../services/data_dir.js";+import { getRestoreProgress, type RestoreProgress, type RestoreRequest } from "../../services/database_restore.js";import {- getRestoreProgress,- readBackupFormat,- removeQuietly,- reportRestoreFailure,- restoreDatabase,- RestoreFailure,- type RestoreFailureReason,- type RestoreProgress-} from "../../services/database_restore.js";+ backupUpload,+ beginRestore,+ discardPendingBackup,+ pendingRestoreRequest+} from "../../services/restore_session.js";/*** The setup screen's way back from a backup: list what is already on disk, take a file that is not,@@ -30,124 +24,39 @@ import {* @module*/-/** No database is worth more than this, and an upload claiming to be is refused before it starts. */-const MAX_BACKUP_BYTES = 64 * 1024 * 1024 * 1024;--/** Failures another passphrase could still get past, which is the only reason to keep the file. */-const RETRYABLE_WITH_ANOTHER_PASSPHRASE = new Set<RestoreFailureReason>([- "passphrase-required",- "wrong-passphrase-or-damaged-header"-]);--/**- * Where a finished upload waits between arriving and being restored.- *- * Deliberately outside the restore's own working directory, which is emptied whenever a restore- * ends: a wrong passphrase would otherwise take the uploaded backup with it, and the user would have- * to send the whole file again to try another one.- */-const PENDING_UPLOAD_PATH = path.join(dataDir.TMP_DIR, "uploads", "pending-backup");--/** What an upload turned out to be, which decides whether the user is asked for a passphrase. */-interface PendingUpload {- fileName: string;- encrypted: boolean;-}--let pendingUpload: PendingUpload | null = null;-let releaseSetupHold: (() => void) | null = null;--const upload = createChunkedUpload<PendingUpload>({- name: "restore",- directory: path.join(dataDir.TMP_DIR, "uploads"),- maxTotalBytes: MAX_BACKUP_BYTES,- requireFreeSpace: true,- onComplete: async ({ path: uploadedPath, fileName }) => {- fs.mkdirSync(path.dirname(PENDING_UPLOAD_PATH), { recursive: true });- fs.rmSync(PENDING_UPLOAD_PATH, { force: true });- // A move rather than a copy: the file is the size of a database, and both ends are in the- // same temporary directory.- fs.renameSync(uploadedPath, PENDING_UPLOAD_PATH);-- pendingUpload = {- fileName,- // Stated in the clear in a container's header, so the setup screen knows to ask for a- // passphrase without having to try the restore and fail first.- encrypted: readBackupFormat(PENDING_UPLOAD_PATH)?.encrypted ?? false- };- getLog().info(`A backup was uploaded for restoring (${fileName}).`);-- return pendingUpload;- }-});--/**- * Starts an upload, and reserves setup for it: what arrives is going to replace the database, and an- * hour of uploading must not end with another tab having created a document in the meantime.- */async function beginUpload(req: Request) {- const status = await upload.begin(req);-- // Taken after the upload is accepted, so a refused one does not leave setup reserved. Released- // when the restore ends, when the upload is abandoned, or when its session expires.- releaseSetupHold ??= holdSetup("restore-backup");-- return status;+ return await backupUpload.begin(req);}async function uploadChunk(req: Request) {- return await upload.chunk(req);+ return await backupUpload.chunk(req);}async function uploadStatus(req: Request) {- return await upload.status(req);+ return await backupUpload.status(req);}async function finishUpload(req: Request) {- return await upload.finish(req);+ return await backupUpload.finish(req);}async function abortUpload(req: Request) {- await upload.abort(req);- discardPendingUpload();+ await backupUpload.abort(req);+ discardPendingBackup();}/**- * Restores the backup the user picked: the one just uploaded, or one from the backup directory.+ * Restores the backup the user picked: the one waiting to be restored, or one from this device's+ * backup directory.*- * Answers as soon as the restore is under way rather than when it is over, since unwrapping,- * checking and migrating a large database outlast any sensible request. The client follows the rest- * through {@link status}.+ * Answers as soon as the restore is under way rather than when it is over. The client follows the+ * rest through {@link status}.*/-async function start(req: Request) {+function start(req: Request) {const { source, filePath, passphrase } = (req.body ?? {}) as StartBody;- const request = source === "existing"- ? existingBackup(filePath)- : uploadedBackup();-- // Deliberately not awaited: the restore runs on past this response, holding the setup lock for- // as long as it takes, and reports itself through the status endpoint.- void withSetupLock("restore-backup", async () => {- try {- await restoreDatabase({ ...request, passphrase });- discardPendingUpload();- } catch (e) {- // A passphrase that was wrong or missing is the one failure the same file can still- // recover from, so the upload is kept for the next attempt. Anything else is a file that- // will fail the same way however often it is tried.- if (!(e instanceof RestoreFailure) || !RETRYABLE_WITH_ANOTHER_PASSPHRASE.has(e.reason)) {- discardPendingUpload();- }-- throw e;- }- }).catch((e) => {- // A restore that ran has already recorded why it stopped. One that was refused before it- // began has recorded nothing, and a client polling for progress would wait on it forever.- if (!(e instanceof RestoreFailure)) {- reportRestoreFailure(request.fileName, e);- }- });+ const request = source === "existing" ? existingBackup(filePath) : pendingBackup();++ beginRestore({ ...request, passphrase });return { started: true };}@@ -158,7 +67,7 @@ function status(): { restore: RestoreProgress | null } {/** Drops the sweeper's timer. Only the tests have any use for a shutdown this tidy. */function stop() {- upload.stop();+ backupUpload.stop();}export default {@@ -173,25 +82,27 @@ export default {};interface StartBody {- source?: "uploaded" | "existing";+ /** `existing` names a backup from this device; anything else restores the pending one. */+ source?: "pending" | "existing";/** Only for `existing`: which backup, from the listing. */filePath?: string;passphrase?: string;}-function uploadedBackup() {- if (!pendingUpload) {- throw new NotFoundError("No uploaded backup is waiting to be restored.");+function pendingBackup(): Omit<RestoreRequest, "passphrase"> {+ const request = pendingRestoreRequest();+ if (!request) {+ throw new NotFoundError("No backup is waiting to be restored.");}- return { path: PENDING_UPLOAD_PATH, fileName: pendingUpload.fileName, consumable: true };+ return request;}/*** A backup from the listing, resolved through the backup service rather than trusted: the path* arrives from a client, on an endpoint that needs no authentication.*/-function existingBackup(filePath: string | undefined) {+function existingBackup(filePath: string | undefined): Omit<RestoreRequest, "passphrase"> {if (!filePath) {throw new ValidationError("No backup was named.");}@@ -204,18 +115,3 @@ function existingBackup(filePath: string | undefined) {return { path: resolvedPath, fileName: path.basename(resolvedPath), consumable: false };}--/**- * Frees setup and the disk once an upload is restored, abandoned, or found to be unusable.- *- * Runs while a failure is on its way to the user, so the file not going quietly must not become the- * failure they are told about. Setup is freed either way: a file left behind costs disk, a lock left- * behind costs them every other way out of the setup screen.- */-function discardPendingUpload() {- pendingUpload = null;- removeQuietly(PENDING_UPLOAD_PATH);-- releaseSetupHold?.();- releaseSetupHold = null;-}diff --git a/apps/server/src/services/restore_session.ts b/apps/server/src/services/restore_session.tsnew file mode 100644index 0000000000..a64169b346--- /dev/null+++ b/apps/server/src/services/restore_session.ts@@ -0,0 +1,167 @@+import { getLog, holdSetup, withSetupLock } from "@triliumnext/core";+import fs from "fs";+import path from "path";++import { createChunkedUpload } from "./chunked_upload.js";+import dataDir from "./data_dir.js";+import {+ readBackupFormat,+ removeQuietly,+ reportRestoreFailure,+ restoreDatabase,+ RestoreFailure,+ type RestoreFailureReason,+ type RestoreRequest+} from "./database_restore.js";++/**+ * Holds the backup the setup screen is about to restore, however it arrived, and starts the restore+ * when the user says so.+ *+ * There are two ways in and they converge here: a browser sends the file in chunks, and the desktop+ * points at one already on disk. Both end as *the pending backup*, so the passphrase prompt, the+ * retry after a wrong one, and the restore itself are one path rather than two that have to be kept+ * in step. A backup picked from this device's own backup directory needs nothing pending: it names+ * itself each time, and must survive being restored.+ *+ * Setup is reserved from the moment a backup is pending. What is coming replaces the database, and an+ * hour of uploading must not end with another tab having created a document in the meantime.+ *+ * @module+ */++/** No database is worth more than this, and an upload claiming to be is refused before it starts. */+const MAX_BACKUP_BYTES = 64 * 1024 * 1024 * 1024;++/** Failures another passphrase could still get past, which is the only reason to keep the backup. */+const RETRYABLE_WITH_ANOTHER_PASSPHRASE = new Set<RestoreFailureReason>([+ "passphrase-required",+ "wrong-passphrase-or-damaged-header"+]);++/**+ * Where a finished upload waits between arriving and being restored.+ *+ * Deliberately outside the restore's own working directory, which is emptied whenever a restore+ * ends: a wrong passphrase would otherwise take the uploaded backup with it, and the user would have+ * to send the whole file again to try another one.+ */+const PENDING_UPLOAD_PATH = path.join(dataDir.TMP_DIR, "uploads", "pending-backup");++/** The backup waiting to be restored, and what the screen needs to know about it. */+export interface PendingBackup {+ fileName: string;+ /** Whether the user has to be asked for a passphrase before anything can be done with it. */+ encrypted: boolean;+}++interface Pending extends PendingBackup {+ path: string;+ /** An upload exists only to be restored and may be consumed; a file of the user's may not. */+ consumable: boolean;+}++let pending: Pending | null = null;+let releaseSetupHold: (() => void) | null = null;++/** Receives a backup a chunk at a time, and makes what arrives the pending one. */+export const backupUpload = createChunkedUpload<PendingBackup>({+ name: "restore",+ directory: path.join(dataDir.TMP_DIR, "uploads"),+ maxTotalBytes: MAX_BACKUP_BYTES,+ requireFreeSpace: true,+ onComplete: async ({ path: uploadedPath, fileName }) => {+ fs.mkdirSync(path.dirname(PENDING_UPLOAD_PATH), { recursive: true });+ fs.rmSync(PENDING_UPLOAD_PATH, { force: true });+ // A move rather than a copy: the file is the size of a database, and both ends are in the+ // same temporary directory.+ fs.renameSync(uploadedPath, PENDING_UPLOAD_PATH);++ getLog().info(`A backup was uploaded for restoring (${fileName}).`);++ return setPendingBackup(PENDING_UPLOAD_PATH, fileName, { consumable: true });+ }+});++/**+ * Makes the backup at `filePath` the one waiting to be restored, and reserves setup for it.+ *+ * @param options.consumable whether the restore may take the file rather than copy it. True only for+ * a file that exists to be restored, i.e. an upload; never for one of the user's own.+ * @throws ConflictError when setup is busy with something else.+ */+export function setPendingBackup(filePath: string, fileName: string, options: { consumable: boolean }): PendingBackup {+ // Taken before the backup is recorded, so a refusal leaves nothing pending behind it. Released+ // when the restore ends, or when the backup is discarded.+ releaseSetupHold ??= holdSetup("restore-backup");++ pending = {+ path: filePath,+ fileName,+ consumable: options.consumable,+ // Stated in the clear in a container's header, so the screen knows to ask for a passphrase+ // without having to try the restore and fail first.+ encrypted: readBackupFormat(filePath)?.encrypted ?? false+ };++ return { fileName: pending.fileName, encrypted: pending.encrypted };+}++/** The backup waiting to be restored, or `null` when none is. */+export function getPendingBackup(): PendingBackup | null {+ return pending && { fileName: pending.fileName, encrypted: pending.encrypted };+}++/** What a restore needs to know to run, for the backup that is pending. */+export function pendingRestoreRequest(): Omit<RestoreRequest, "passphrase"> | null {+ return pending && { path: pending.path, fileName: pending.fileName, consumable: pending.consumable };+}++/**+ * Starts a restore and returns at once, since unwrapping, checking and migrating a large database+ * outlast any sensible request or dialog. Progress is followed through+ * {@link getRestoreProgress}.+ *+ * The setup lock is held for the whole of it, not just for starting it.+ */+export function beginRestore(request: RestoreRequest): void {+ void withSetupLock("restore-backup", async () => {+ try {+ await restoreDatabase(request);+ discardPendingBackup();+ } catch (e) {+ // A passphrase that was wrong or missing is the one failure the same backup can still+ // recover from, so it is kept for the next attempt. Anything else will fail the same way+ // however often it is tried.+ if (!(e instanceof RestoreFailure) || !RETRYABLE_WITH_ANOTHER_PASSPHRASE.has(e.reason)) {+ discardPendingBackup();+ }++ throw e;+ }+ }).catch((e) => {+ // A restore that ran has already recorded why it stopped. One that was refused before it+ // began has recorded nothing, and a client polling for progress would wait on it forever.+ if (!(e instanceof RestoreFailure)) {+ reportRestoreFailure(request.fileName, e);+ }+ });+}++/**+ * Frees setup once the pending backup is restored, abandoned, or found to be unusable, and deletes it+ * if it was ours to delete.+ *+ * Runs while a failure is on its way to the user, so a file that will not go must not become the+ * failure they are told about. Setup is freed either way: a file left behind costs disk, a lock left+ * behind costs them every other way out of the setup screen.+ */+export function discardPendingBackup(): void {+ if (pending?.consumable) {+ removeQuietly(pending.path);+ }++ pending = null;+ releaseSetupHold?.();+ releaseSetupHold = null;+}diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex bfab04bf31..c4f46993fb 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -639,6 +639,37 @@ export interface ElectronNativeImportApi {importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean; format?: string }): Promise<NativeImportResult>;}+/**+ * Outcome of {@link ElectronRestoreApi.pickBackup}: what the chosen backup is, never where it is.+ *+ * The file itself stays with the main process, which holds it as the one waiting to be restored, so+ * the renderer is given only what the screen has to show and decide with.+ */+export interface NativeBackupPickResult {+ status: "selected" | "cancelled" | "error";+ /** Display name of the chosen backup (when `status === "selected"`). */+ fileName?: string;+ /** Whether a passphrase has to be asked for before it can be restored. */+ encrypted?: boolean;+ /** Failure detail (when `status === "error"`), e.g. setup already being busy. */+ message?: string;+}++/**+ * Choosing a backup to restore from the desktop, where the file is already on the same disk as the+ * database it is going to replace and has no business being uploaded to reach it.+ *+ * Only usable during setup: what it puts forward is restored by the ordinary+ * `POST /api/setup/restore/start`, which refuses once the application is initialized.+ */+export interface ElectronRestoreApi {+ /**+ * Prompts a native "open file" dialog for a `.db` or `.tnbackup` backup and, if one is chosen,+ * makes it the backup waiting to be restored.+ */+ pickBackup(): Promise<NativeBackupPickResult>;+}+/** Outcome of {@link ElectronDialogApi.pickDirectory}. */export interface NativeDirectoryPickResult {status: "selected" | "cancelled";@@ -698,4 +729,6 @@ export interface ElectronApi {nativeImport: ElectronNativeImportApi;/** Native OS pickers that hand the renderer a location the user chose themselves. */dialog: ElectronDialogApi;+ /** Choosing a backup to restore during setup, read where it lies rather than uploaded. */+ restore: ElectronRestoreApi;}