Skip to content

Build your personal knowledge base with Trilium Notes

client/setup/backup: add a backup parameters screen

Adorian Doran845cc0f0cc43
diff --git a/apps/client/src/services/backup_download.spec.ts b/apps/client/src/services/backup_download.spec.ts
new file mode 100644
index 0000000000..72f97d0978
--- /dev/null
+++ b/apps/client/src/services/backup_download.spec.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import { backupFileName } from "./backup_download";
+
+// What the suggested name itself looks like is settled in commons, which every platform shares;
+// this is about the file that name becomes.
+describe("naming a backup file", () => {
+ it("adds the container extension, and tidies what only fails at save time", () => {
+ // Parentheses are legal everywhere, so the suggested name survives its own round trip.
+ expect(backupFileName("Trilium data (2026-08-08 16-30-32)"))
+ .toBe("Trilium data (2026-08-08 16-30-32).tnbackup");
+ // What a name may contain at all is the field's business and has its own tests; this is
+ // the last pass, for a name that never went through that field.
+ expect(backupFileName('a<b>c:d"e/f\\g|h?i*j')).toBe("abcdefghij.tnbackup");
+ // Legal to type, impossible to save on Windows, so it goes on the way out rather than
+ // under the cursor.
+ expect(backupFileName("My backup...")).toBe("My backup.tnbackup");
+ expect(backupFileName(" spaced ")).toBe("spaced.tnbackup");
+ });
+
+ it("falls back to the default name where nothing usable is left", () => {
+ const dated = /^Trilium data \(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}\)\.tnbackup$/;
+
+ expect(backupFileName("")).toMatch(dated);
+ expect(backupFileName("///")).toMatch(dated);
+ // A Windows device name is not a file there, whatever it is called afterwards.
+ expect(backupFileName("NUL")).toMatch(dated);
+ expect(backupFileName("com1")).toMatch(dated);
+ });
+});
diff --git a/apps/client/src/services/backup_download.ts b/apps/client/src/services/backup_download.ts
index 2748e2b2d3..8675eccc29 100644
--- a/apps/client/src/services/backup_download.ts
+++ b/apps/client/src/services/backup_download.ts
@@ -1,46 +1,60 @@
-import type { StandaloneDownloadResult } from "@triliumnext/commons";
+import { defaultBackupName, type StandaloneDownloadResult } from "@triliumnext/commons";
+
+import { tidyFilesystemFriendlyName } from "../widgets/react/FilesystemFriendlyName";
/**
* Backing up by download, which is the standalone platform's one and only backup.
*
* Standalone keeps no backups anywhere: the browser's storage holds the live database and could
- * rarely hold a copy of it beside itself, so a backup is streamed straight off the live database
- * into a browser download instead. The options screen and the setup screen both back up through
- * here, so the naming and the passphrase live in exactly one place.
+ * rarely hold a copy of it beside itself, so a backup is streamed straight off the database into a
+ * browser download instead. The options screen and the setup screen both back up through here, so
+ * the naming and the format live in exactly one place.
*
* @module
*/
+/** 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;
}
/**
- * How a downloaded backup is named: the same dated, readable shape the other platforms write
- * their setup backups under, with the encrypted container's extension, which is what the download
- * currently always carries.
+ * 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.
*/
-export function backupDownloadFileName(now: Date): string {
- const stamp = (value: number) => String(value).padStart(2, "0");
- const date = [ now.getFullYear(), stamp(now.getMonth() + 1), stamp(now.getDate()) ].join("-");
- const time = [ stamp(now.getHours()), stamp(now.getMinutes()), stamp(now.getSeconds()) ].join("-");
+export function backupFileName(name: string): string {
+ const tidied = tidyFilesystemFriendlyName(name);
+ const usable = tidied && !RESERVED_FILE_NAMES.test(tidied) ? tidied : defaultBackupName(new Date());
- return `Backup ${date} ${time}.tnbackup`;
+ return `${usable}${BACKUP_EXTENSION}`;
}
/**
* Starts the download and resolves with how it ended, which is when the stream behind it has been
* fully produced — the closest thing to "finished" the application can see, with the browser's
* own download UI carrying the transfer itself.
+ *
+ * @param passphrase encrypts the container. Omitted or empty leaves it unencrypted, which is still
+ * a container: one format, one extension, whatever the user chose.
*/
-export async function startBackupDownload(fileName: string): Promise<StandaloneDownloadResult> {
+export async function startBackupDownload(
+ fileName: string,
+ passphrase?: string
+): Promise<StandaloneDownloadResult> {
const api = window.standaloneApi;
if (!api) {
return { status: "failed", message: "This platform does not back up by download." };
}
- // TODO: ask the user for a passphrase instead; this fixed one exists only to test the
- // encrypted download path end to end.
- return await api.backup.downloadDatabase(fileName, "123456");
+ return await api.backup.downloadDatabase(fileName, passphrase || undefined);
}
diff --git a/apps/client/src/setup_backup.spec.tsx b/apps/client/src/setup_backup.spec.tsx
index 73952c0ec1..485cb359f6 100644
--- a/apps/client/src/setup_backup.spec.tsx
+++ b/apps/client/src/setup_backup.spec.tsx
@@ -8,8 +8,9 @@ const mocks = vi.hoisted(() => ({
startBackupDownload: vi.fn(async () => ({ status: "done" }) as { status: string; message?: string })
}));
-vi.mock("./services/backup_download", () => ({
- backupDownloadFileName: () => "Backup 2026-08-08 10-00-00.tnbackup",
+vi.mock("./services/backup_download", async (importOriginal) => ({
+ // The naming rules are real (they have their own tests); only the download is stubbed.
+ ...(await importOriginal<typeof import("./services/backup_download")>()),
isBackupDownloadSupported: () => true,
startBackupDownload: mocks.startBackupDownload
}));
@@ -35,6 +36,55 @@ function button(label: string): HTMLButtonElement | undefined {
.find((element) => element.textContent?.includes(label));
}
+function nameField(): HTMLInputElement | null {
+ return container.querySelector<HTMLInputElement>("input:not([type=password])");
+}
+
+/** The password pair, in the order they are filled in: the password, then its confirmation. */
+function passwordFields(): HTMLInputElement[] {
+ return [ ...container.querySelectorAll<HTMLInputElement>("input[type=password]") ];
+}
+
+/** 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) {
+ throw new Error("the field is not on screen");
+ }
+
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
+/** The shape of the name proposed by commons, which every platform now suggests. */
+const SUGGESTED_NAME = /^Trilium data \(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}\)$/;
+
+/**
+ * Answers the parameters screen and arrives at the download, which is where most of this is.
+ *
+ * @returns the name the backup was left under, since the field is gone by the time it matters.
+ */
+async function reachDownload({ name, password }: { name?: string; password?: string } = {}) {
+ renderScreen();
+ await settle();
+
+ if (name !== undefined) {
+ type(nameField(), name);
+ await settle();
+ }
+ if (password !== undefined) {
+ const [ first, second ] = passwordFields();
+ type(first, password);
+ type(second, password);
+ await settle();
+ }
+
+ const chosen = nameField()?.value ?? "";
+ button("setup.continue")?.click();
+ await settle();
+
+ return chosen;
+}
+
beforeEach(() => {
vi.useFakeTimers();
onDone.mockReset();
@@ -47,18 +97,81 @@ afterEach(() => {
vi.useRealTimers();
});
-describe("backing up from the setup screen", () => {
- it("names the file up front and downloads nothing until asked", async () => {
+describe("choosing what the backup is called and whether it is locked", () => {
+ it("opens on the parameters, with the name filled in and nothing downloading", async () => {
+ renderScreen();
+ await settle();
+
+ expect(container.textContent).toContain("setup.backup-name");
+ expect(nameField()?.value).toMatch(SUGGESTED_NAME);
+ // Optional, so both fields start empty and Continue is available anyway.
+ expect(passwordFields().map((field) => field.value)).toEqual([ "", "" ]);
+ expect(button("setup.continue")?.disabled).toBe(false);
+ expect(mocks.startBackupDownload).not.toHaveBeenCalled();
+ // Nothing here is destructive, so leaving is available from the start.
+ expect(button("setup.backup-finish")?.disabled).toBe(false);
+ });
+
+ it("will not continue on a password typed only once, which would back up unlocked", async () => {
+ renderScreen();
+ await settle();
+
+ const [ first, second ] = passwordFields();
+ type(first, "hunter2");
+ await settle();
+ expect(button("setup.continue")?.disabled).toBe(true);
+
+ type(second, "hunter3");
+ await settle();
+ expect(button("setup.continue")?.disabled).toBe(true);
+
+ type(second, "hunter2");
+ await settle();
+ expect(button("setup.continue")?.disabled).toBe(false);
+ });
+
+ it("refuses characters a filename cannot hold, as they are typed", async () => {
renderScreen();
await settle();
+ type(nameField(), 'Q3 notes: "final" <v2>');
+ await settle();
+
+ expect(nameField()?.value).toBe("Q3 notes final v2");
+ });
+
+ it("carries the name and password through to the download", async () => {
+ await reachDownload({ name: "Before the big import", password: "hunter2" });
+
+ button("setup.backup-download")?.click();
+ await settle();
+
+ expect(mocks.startBackupDownload)
+ .toHaveBeenCalledWith("Before the big import.tnbackup", "hunter2");
+ });
+
+ it("downloads under the suggested name, without a password, when neither was touched", async () => {
+ const chosen = await reachDownload();
+ expect(chosen).toMatch(SUGGESTED_NAME);
+
+ button("setup.backup-download")?.click();
+ await settle();
+
+ // Empty, not absent: the service turns that into an unencrypted container.
+ expect(mocks.startBackupDownload).toHaveBeenCalledWith(`${chosen}.tnbackup`, "");
+ });
+});
+
+describe("backing up from the setup screen", () => {
+ it("names the file up front and downloads nothing until asked", async () => {
+ const chosen = await reachDownload();
+
expect(container.textContent).toContain("setup.backup-data");
// The name is on the screen before the download, since it is what the user goes looking
// for afterwards, and it is the one part of the line that is not boilerplate.
expect(container.querySelector(".backup-download-file strong")?.textContent)
- .toBe("Backup 2026-08-08 10-00-00.tnbackup");
+ .toBe(`${chosen}.tnbackup`);
expect(mocks.startBackupDownload).not.toHaveBeenCalled();
- // Nothing here is destructive, so leaving is available from the start.
expect(button("setup.backup-finish")?.disabled).toBe(false);
});
@@ -67,13 +180,11 @@ describe("backing up from the setup screen", () => {
mocks.startBackupDownload.mockImplementation(() => new Promise((resolve) => {
finish = resolve;
}));
- renderScreen();
- await settle();
+ await reachDownload();
button("setup.backup-download")?.click();
await settle();
- expect(mocks.startBackupDownload).toHaveBeenCalledWith("Backup 2026-08-08 10-00-00.tnbackup");
expect(container.textContent).toContain("setup.backup-downloading");
// Said while it runs, because leaving the screen is exactly what would break it.
expect(container.textContent).toContain("setup.backup-do-not-close");
@@ -96,8 +207,7 @@ describe("backing up from the setup screen", () => {
it("shows what stopped a failed download, and offers another go", async () => {
mocks.startBackupDownload.mockResolvedValue({ status: "failed", message: "the stream broke" });
- renderScreen();
- await settle();
+ await reachDownload();
button("setup.backup-download")?.click();
await settle();
@@ -112,8 +222,7 @@ describe("backing up from the setup screen", () => {
});
it("hands back to the application when it is done with", async () => {
- renderScreen();
- await settle();
+ await reachDownload();
button("setup.backup-finish")?.click();
await settle();
diff --git a/apps/client/src/setup_backup.tsx b/apps/client/src/setup_backup.tsx
index 57a151a475..33900c200d 100644
--- a/apps/client/src/setup_backup.tsx
+++ b/apps/client/src/setup_backup.tsx
@@ -1,11 +1,17 @@
import "./setup_backup.css";
+import { defaultBackupName } from "@triliumnext/commons";
+import type { ComponentChildren } from "preact";
import { useMemo, useState } from "preact/hooks";
-import { backupDownloadFileName, startBackupDownload } from "./services/backup_download";
+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 FilesystemFriendlyName from "./widgets/react/FilesystemFriendlyName";
+import FormGroup from "./widgets/react/FormGroup";
+import FormPasswordWithConfirmation from "./widgets/react/FormPasswordWithConfirmation";
import Icon from "./widgets/react/Icon";
import SetupPage from "./widgets/react/SetupPage";
@@ -22,6 +28,14 @@ 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;
@@ -31,12 +45,9 @@ export interface BackupDownload {
start: () => void;
}
-/**
- * Owns a download and the file it is named after, which is fixed when the screen appears rather
- * than when the button is pressed: the name is shown before the download starts.
- */
-export function useBackupDownload(): BackupDownload {
- const fileName = useMemo(() => backupDownloadFileName(new Date()), []);
+/** Owns a download of the file `settings` describes. */
+export function useBackupDownload(settings: BackupSettings): BackupDownload {
+ const fileName = useMemo(() => backupFileName(settings.name), [ settings.name ]);
const [ state, setState ] = useState<BackupDownload["state"]>("idle");
const [ error, setError ] = useState<string>();
@@ -47,7 +58,7 @@ export function useBackupDownload(): BackupDownload {
start: () => {
setState("running");
setError(undefined);
- void startBackupDownload(fileName).then((result) => {
+ void startBackupDownload(fileName, settings.passphrase).then((result) => {
setState(result.status === "done" ? "done" : "failed");
setError(result.status === "done" ? undefined : result.message);
});
@@ -55,6 +66,71 @@ export function useBackupDownload(): BackupDownload {
};
}
+/**
+ * What the backup is called and whether it is locked, 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.
+ *
+ * @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;
+ /** What sits beside Continue, which differs by the flow this screen was reached through. */
+ footer?: ComponentChildren;
+}) {
+ const [ name, setName ] = useState(() => defaultBackupName(new Date()));
+ // 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>("");
+
+ return (
+ <SetupPage
+ className="setup-backup-parameters top-aligned"
+ title={t("setup.backup-data")}
+ illustration={<Icon icon="bx bx-archive-out" className="illustration-icon" />}
+ footer={
+ <>
+ {footer}
+ <Button
+ text={t("setup.continue")}
+ kind="primary"
+ disabled={passphrase === null}
+ onClick={() => onContinue({ name, passphrase: passphrase ?? "" })}
+ />
+ </>
+ }
+ >
+ <form>
+ <Card>
+ <CardSection>
+ <FormGroup
+ name="backupName"
+ label={t("setup.backup-name")}
+ description={t("setup.backup-name-description")}
+ >
+ {/* Filtered as it is typed rather than refused afterwards: what it
+ drops are characters no filesystem would have taken anyway. */}
+ <FilesystemFriendlyName currentValue={name} onChange={setName} />
+ </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>
+ </Card>
+ </form>
+ </SetupPage>
+ );
+}
+
/**
* The download itself: the button that starts it and what became of it.
*
@@ -107,17 +183,19 @@ export function BackupDownloadPanel({ download }: { download: BackupDownload })
}
/**
- * The whole of the wizard, when the wizard was opened to take a backup and nothing else.
+ * Taking the backup, once its settings are known.
*
- * Unlike every other screen here, this one leads nowhere: there is no next step, because the
- * database it was opened over is the one the application is going back to. Continue is available
- * from the start, so a user who changes their mind is not trapped on a screen that only exists to
- * offer them something.
+ * Split from the parameters screen so that the download owns a settled name and password: a hook
+ * cannot be told to forget what it started, and this component only exists once there is nothing
+ * left to change.
*
- * @param onDone leave setup and open the database that was there all along.
+ * @param onDone the backup is over, one way or another; leave the wizard.
*/
-export default function SetupBackupDatabase({ onDone }: { onDone: () => void }) {
- const download = useBackupDownload();
+export function BackupDownloadStep({ settings, onDone }: {
+ settings: BackupSettings;
+ onDone: () => void;
+}) {
+ const download = useBackupDownload(settings);
return (
<SetupPage
@@ -137,3 +215,28 @@ export default function SetupBackupDatabase({ onDone }: { onDone: () => void })
</SetupPage>
);
}
+
+/**
+ * The whole of the wizard, when the wizard was opened to take a backup and nothing else.
+ *
+ * Unlike every other screen here, this one leads nowhere: there is no next step, because the
+ * database it was opened over is the one the application is going back to. Leaving is available
+ * throughout, so a user who changes their mind is not trapped on a screen that only exists to
+ * offer them something.
+ *
+ * @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);
+
+ if (!settings) {
+ return (
+ <BackupParameters
+ onContinue={setSettings}
+ footer={<Button text={t("setup.backup-finish")} onClick={onDone} />}
+ />
+ );
+ }
+
+ return <BackupDownloadStep settings={settings} onDone={onDone} />;
+}
diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsx
index 11b12f66cd..050c65ef85 100644
--- a/apps/client/src/setup_existing.spec.tsx
+++ b/apps/client/src/setup_existing.spec.tsx
@@ -321,7 +321,10 @@ describe("backing up straight to a download on standalone", () => {
.at(-1);
}
- /** Chooses the backup and arrives at the download screen, with nothing started yet. */
+ /**
+ * Chooses the backup, accepts the suggested name and no password, and arrives at the download
+ * screen with nothing started yet.
+ */
async function reachDownloadScreen() {
renderScreens();
await settle();
@@ -330,6 +333,10 @@ describe("backing up straight to a download on standalone", () => {
await settle();
button("setup.continue")?.click();
await settle();
+
+ // The parameters screen, which the same Continue leaves as it was prefilled.
+ arrivingButton("setup.continue")?.click();
+ await settle();
}
it("shows the download step without starting anything, and gates Continue on it", async () => {
@@ -347,9 +354,10 @@ describe("backing up straight to a download on standalone", () => {
arrivingButton("setup.backup-download")?.click();
await settle();
+ // The suggested name, and no password, which is what the parameters screen was left at.
expect(downloadDatabase).toHaveBeenCalledWith(
- expect.stringMatching(/^Backup \d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}\.tnbackup$/),
- "123456");
+ expect.stringMatching(/^Trilium data \(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}\)\.tnbackup$/),
+ undefined);
expect(container.textContent).toContain("setup.backup-downloading");
expect(arrivingButton("setup.continue")?.disabled).toBe(true);
diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsx
index 69929a7dc1..dcb1c8c62b 100644
--- a/apps/client/src/setup_existing.tsx
+++ b/apps/client/src/setup_existing.tsx
@@ -15,7 +15,12 @@ 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 { type BackupDownload, BackupDownloadPanel, useBackupDownload } from "./setup_backup";
+import {
+ BackupDownloadPanel,
+ BackupParameters,
+ type BackupSettings,
+ useBackupDownload
+} from "./setup_backup";
/**
* What happens to the knowledge base that was already here.
@@ -40,8 +45,8 @@ const CHOICES: { value: Choice; label: string }[] = [
];
/** The screens, in the order they can be reached, which is also the order they slide in. */
-type Step = "choice" | "backing-up" | "downloading" | "backed-up";
-const STEP_ORDER: Step[] = [ "choice", "backing-up", "downloading", "backed-up" ];
+type Step = "choice" | "backup-parameters" | "backing-up" | "downloading" | "backed-up";
+const STEP_ORDER: Step[] = [ "choice", "backup-parameters", "backing-up", "downloading", "backed-up" ];
/**
* The whole question, as one step of the wizard.
@@ -56,7 +61,7 @@ const STEP_ORDER: Step[] = [ "choice", "backing-up", "downloading", "backed-up"
export default function ExistingData({ onProceed, onKept }: { onProceed: () => void; onKept: () => void }) {
const [ step, setStep ] = useState<Step>("choice");
const [ backup, setBackup ] = useState<SetupExistingBackup | null>(null);
- const download = useBackupDownload();
+ const [ settings, setSettings ] = useState<BackupSettings | null>(null);
const [ error, setError ] = useState<string>();
const [ errorId, setErrorId ] = useState(0);
@@ -78,11 +83,11 @@ 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. The
- // screen comes first and the download starts from its own button, so nothing lands in
- // the downloads bar unannounced.
+ // 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("downloading");
+ setStep("backup-parameters");
return;
}
@@ -122,10 +127,19 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
onCancel={() => void keep()}
/>
)}
+ {shown === "backup-parameters" && (
+ <BackupParameters
+ onContinue={(chosen) => {
+ setSettings(chosen);
+ setStep("downloading");
+ }}
+ footer={<Button text={t("setup.existing-data-cancel")} onClick={() => void keep()} />}
+ />
+ )}
{shown === "backing-up" && <ExistingDataBackingUp />}
- {shown === "downloading" && (
+ {shown === "downloading" && settings && (
<ExistingDataDownloading
- download={download}
+ settings={settings}
onContinue={() => void erase()}
onCancel={() => void keep()}
/>
@@ -296,11 +310,13 @@ const PROGRESS_INTERVAL_MS = 1000;
* been fully produced — the closest thing to "finished" the application can see, with the
* browser's own download UI carrying the transfer itself.
*/
-export function ExistingDataDownloading({ download, onContinue, onCancel }: {
- download: BackupDownload;
+export function ExistingDataDownloading({ settings, onContinue, onCancel }: {
+ settings: BackupSettings;
onContinue: () => void;
onCancel: () => void;
}) {
+ const download = useBackupDownload(settings);
+
return (
<SetupPage
className="existing-data-downloading top-aligned"
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 39baefa317..eb87105dfd 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3705,6 +3705,11 @@
"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-file": "Backup file:",
"backup-download": "Download",
"backup-downloading": "Downloading...",
diff --git a/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsx b/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsx
new file mode 100644
index 0000000000..0b7ddb48da
--- /dev/null
+++ b/apps/client/src/widgets/react/FilesystemFriendlyName.spec.tsx
@@ -0,0 +1,155 @@
+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");
+ });
+});
+
+describe("FilesystemFriendlyName", () => {
+ let container: HTMLDivElement | undefined;
+ const onChange = vi.fn();
+
+ /** Renders the field with its value held in state, which is what puts the caret back. */
+ function renderField(initial: string): HTMLInputElement {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+
+ function Harness() {
+ const [ value, setValue ] = useState(initial);
+
+ return (
+ <FilesystemFriendlyName
+ currentValue={value}
+ onChange={(cleaned) => {
+ onChange(cleaned);
+ setValue(cleaned);
+ }}
+ />
+ );
+ }
+
+ render(<Harness />, container);
+
+ const input = container.querySelector("input");
+ if (!input) {
+ throw new Error("the field did not render");
+ }
+ return input;
+ }
+
+ /** Preact applies state through a microtask, so a rendered result is awaited rather than read. */
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+ /** Types into the box the way a browser does: value, caret, then the input event. */
+ function type(input: HTMLInputElement, value: string, caret = value.length) {
+ input.value = value;
+ input.setSelectionRange(caret, caret);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+
+ /** Leaves the field. Preact's compat layer listens for the bubbling counterpart of blur. */
+ function leave(input: HTMLInputElement) {
+ input.dispatchEvent(new Event("focusout", { bubbles: true }));
+ input.dispatchEvent(new Event("blur", { bubbles: true }));
+ }
+
+ beforeEach(() => {
+ onChange.mockReset();
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ it("takes a refused character straight back out as it is typed", async () => {
+ const input = renderField("Backup");
+
+ type(input, "Backup:");
+ await settle();
+
+ expect(onChange).toHaveBeenCalledWith("Backup");
+ expect(input.value).toBe("Backup");
+ });
+
+ it("cleans a pasted name in one go", async () => {
+ const input = renderField("");
+
+ type(input, 'C:\\Users\\me\\notes "final"');
+ await settle();
+
+ expect(onChange).toHaveBeenCalledWith("CUsersmenotes final");
+ });
+
+ it("tidies the edges when the field is left, which is where a paste lands", async () => {
+ const input = renderField(" Before the import. ");
+
+ leave(input);
+ await settle();
+
+ expect(onChange).toHaveBeenCalledWith("Before the import");
+ });
+
+ it("leaves the caret where the typing was, rather than at the end", async () => {
+ const input = renderField("Backup 2026");
+
+ // A colon typed after "Backup", which is refused: the caret belongs right after "Backup",
+ // not thrown to the end of the box by the value being replaced.
+ type(input, "Backup: 2026", 7);
+ await settle();
+
+ expect(onChange).toHaveBeenCalledWith("Backup 2026");
+ expect(input.selectionStart).toBe(6);
+ });
+
+ it("keeps the caret ahead of the character typed after a refused one", async () => {
+ const input = renderField("Backup");
+
+ // Refused, and the host's value does not change, so this causes no render of its own.
+ type(input, "Backup:", 7);
+ await settle();
+ expect(input.value).toBe("Backup");
+
+ // Accepted, and this one does render. The position remembered for the refusal must not
+ // survive to it, or the caret lands before the character that was just typed.
+ type(input, "BackupX", 7);
+ await settle();
+
+ expect(input.value).toBe("BackupX");
+ expect(input.selectionStart).toBe(7);
+ });
+});
diff --git a/apps/client/src/widgets/react/FilesystemFriendlyName.tsx b/apps/client/src/widgets/react/FilesystemFriendlyName.tsx
new file mode 100644
index 0000000000..24075befa0
--- /dev/null
+++ b/apps/client/src/widgets/react/FilesystemFriendlyName.tsx
@@ -0,0 +1,116 @@
+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 FilesystemFriendlyNameProps
+ extends Omit<FormTextBoxProps, "currentValue" | "onBlur" | "onChange" | "type"> {
+ currentValue: string;
+ /** Receives the value with everything a file name cannot hold already removed. */
+ onChange(value: string): void;
+}
+
+/**
+ * Keeps a name usable as a file name, as it is typed rather than once it is submitted.
+ *
+ * Two passes, because one cannot do both jobs. Every input event, typing and pasting alike, has the
+ * forbidden characters taken straight back out, so the box never shows a character that will not
+ * survive being saved. Losing focus then tidies what would have been rude to touch mid-edit: the
+ * spaces and trailing dots a pasted name arrives with.
+ *
+ * The caret is put back where the typing was, since a rejected keystroke that also sent the cursor
+ * to the end would be worse than the character it refused.
+ */
+export default function FilesystemFriendlyName({ currentValue, onChange, inputRef, ...rest }: FilesystemFriendlyNameProps) {
+ const ownRef = useRef<HTMLInputElement | null>(null);
+ const element = (inputRef ?? ownRef) as RefObject<HTMLInputElement>;
+ /** Where to put the caret once the refused character is gone, or null when nothing was. */
+ const caret = useRef<number | null>(null);
+
+ useLayoutEffect(() => {
+ if (caret.current !== null) {
+ element.current?.setSelectionRange(caret.current, caret.current);
+ caret.current = null;
+ }
+ });
+
+ return (
+ <FormTextBox
+ {...rest}
+ inputRef={element}
+ currentValue={currentValue}
+ onChange={(typed) => {
+ // Forgotten first, and remembered again only if this keystroke is refused. A
+ // refusal that changes nothing the host holds causes no render, so a position left
+ // over from it would otherwise be applied to the render some later keystroke
+ // causes, putting the caret behind the character just typed.
+ caret.current = null;
+
+ const cleaned = toFilesystemFriendlyName(typed);
+ if (cleaned !== typed) {
+ // Where the caret sits once what preceded it has been filtered too, which is
+ // where the user was typing rather than the end of the box.
+ const upToCaret = typed.slice(0, element.current?.selectionStart ?? typed.length);
+ const position = toFilesystemFriendlyName(upToCaret).length;
+
+ // Put right here rather than left to the re-render: a refused character makes
+ // the value the host already holds, so there may be no re-render at all, and
+ // the box would go on showing what it just refused.
+ if (element.current) {
+ element.current.value = cleaned;
+ element.current.setSelectionRange(position, position);
+ }
+ // Kept for the render that does follow, which would otherwise put the caret
+ // back at the end while replacing the value.
+ caret.current = position;
+ }
+
+ onChange(cleaned);
+ }}
+ // Pasted names arrive whole, so the tidying that would interrupt typing waits for the
+ // moment the name is finished with. The caret is nobody's business once the field has
+ // been left, so nothing is held over for the render this causes.
+ onBlur={(value) => {
+ caret.current = null;
+ onChange(tidyFilesystemFriendlyName(value));
+ }}
+ />
+ );
+}
diff --git a/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsx b/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsx
index cac86dd40a..daaec9c7ee 100644
--- a/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsx
+++ b/apps/client/src/widgets/react/FormPasswordWithConfirmation.tsx
@@ -12,9 +12,16 @@ export interface FormPasswordWithConfirmationProps {
confirmationLabel?: string;
/** Focus target, for a host that wants the first field focused when it opens. */
inputRef?: RefObject<HTMLInputElement>;
+ /**
+ * Whether leaving both fields empty is an answer in itself, for a password that is offered
+ * rather than required. It is reported as an empty string, which is a settled "no password" as
+ * against the `null` of one that is half-typed.
+ */
+ optional?: boolean;
/**
* Receives the password once both fields agree and neither is empty, and `null` at every other
- * moment. A host enables its confirm action on a non-null value and needs no validation of its own.
+ * moment. A host enables its confirm action on a non-null value and needs no validation of its
+ * own. See {@link optional} for the one case where empty is a value rather than a `null`.
*/
onChange(password: string | null): void;
}
@@ -26,7 +33,7 @@ export interface FormPasswordWithConfirmationProps {
* password yet", not which of the two fields is behind. The mismatch is stated on the second field,
* where it is caused.
*/
-export default function FormPasswordWithConfirmation({ label, confirmationLabel, inputRef, onChange }: FormPasswordWithConfirmationProps) {
+export default function FormPasswordWithConfirmation({ label, confirmationLabel, inputRef, optional, onChange }: FormPasswordWithConfirmationProps) {
const [password, setPassword] = useState("");
const [confirmation, setConfirmation] = useState("");
@@ -35,8 +42,14 @@ export default function FormPasswordWithConfirmation({ label, confirmationLabel,
onChangeRef.current = onChange;
useEffect(() => {
+ // Untouched and allowed to stay that way: an answer, rather than an unfinished one.
+ if (optional && !password && !confirmation) {
+ onChangeRef.current("");
+ return;
+ }
+
onChangeRef.current(password.length > 0 && password === confirmation ? password : null);
- }, [password, confirmation]);
+ }, [password, confirmation, optional]);
return (
<>
diff --git a/apps/standalone/src/lightweight/backup-download.spec.ts b/apps/standalone/src/lightweight/backup-download.spec.ts
index 92567dd3c0..b78e64b379 100644
--- a/apps/standalone/src/lightweight/backup-download.spec.ts
+++ b/apps/standalone/src/lightweight/backup-download.spec.ts
@@ -65,28 +65,55 @@ function fakePort() {
return port;
}
+/**
+ * Everything the port carried, read back through the Node entry point: a container the browser
+ * wrote and the other runtime can open is the whole point of sharing the format.
+ */
+async function unwrap(port: ReturnType<typeof fakePort>, passphrase?: string): Promise<Uint8Array> {
+ const container = Buffer.concat(port.chunks().map((chunk) => Buffer.from(chunk)));
+ const unwrapped: Buffer[] = [];
+ const sink = new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ unwrapped.push(chunk);
+ callback();
+ }
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- a Node stream over the bytes.
+ await readBackupContainer(Readable.from([ container ]) as any, sink, {
+ passphrase,
+ requireSqliteHeader: false
+ });
+
+ return new Uint8Array(Buffer.concat(unwrapped));
+}
+
describe("streamDatabaseDownload", () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
- it("announces the size, sends one chunk per pull, and ends done", async () => {
+ it("wraps an unpassworded download in a container too, and reads back as the database", async () => {
const port = fakePort();
const running = streamDatabaseDownload(fakeReader(), port);
- for (let i = 0; i < 4; i++) {
+ for (let i = 0; i < 10; i++) {
port.deliver({ type: "pull" });
}
const outcome = await running;
expect(outcome).toEqual({ status: "done" });
- expect(port.sent[0]).toEqual({ type: "begin", byteSize: PAGE_SIZE * PAGE_COUNT });
- expect(port.chunks().map((chunk) => chunk.byteLength))
- .toEqual([ 128 * PAGE_SIZE, 128 * PAGE_SIZE, 44 * PAGE_SIZE ]);
+ // One format whether or not a password was given, so one extension and one restore path.
+ expect(port.sent[0])
+ .toEqual({ type: "begin", byteSize: streamedContainerSize(PAGE_SIZE * PAGE_COUNT, false) });
+ expect(port.chunks().reduce((total, chunk) => total + chunk.byteLength, 0))
+ .toBe(port.sent[0].byteSize);
expect(port.sent.at(-1)).toEqual({ type: "end" });
expect(port.closed).toBe(true);
expect(port.onmessage).toBeNull();
+
+ expect(await unwrap(port)).toEqual(fakeDatabaseBytes());
});
it("wraps the stream in an encrypted container, sized exactly as its begin announces", async () => {
@@ -104,25 +131,12 @@ describe("streamDatabaseDownload", () => {
expect(outcome).toEqual({ status: "done" });
// The announced size is what the download's Content-Length becomes, so it must be exact.
const announced = port.sent[0].byteSize;
- expect(announced).toBe(streamedContainerSize(PAGE_SIZE * PAGE_COUNT));
+ expect(announced).toBe(streamedContainerSize(PAGE_SIZE * PAGE_COUNT, true));
const streamed = port.chunks().reduce((total, chunk) => total + chunk.byteLength, 0);
expect(streamed).toBe(announced);
// What went down the wire reads back as the database, through the other runtime's reader.
- const container = Buffer.concat(port.chunks().map((chunk) => Buffer.from(chunk)));
- const unwrapped: Buffer[] = [];
- const sink = new Writable({
- write(chunk: Buffer, _encoding, callback) {
- unwrapped.push(chunk);
- callback();
- }
- });
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- a Node stream over the bytes.
- await readBackupContainer(Readable.from([ container ]) as any, sink, {
- passphrase: "123456",
- requireSqliteHeader: false
- });
- expect(new Uint8Array(Buffer.concat(unwrapped))).toEqual(fakeDatabaseBytes());
+ expect(await unwrap(port, "123456")).toEqual(fakeDatabaseBytes());
});
it("stops quietly when the download is cancelled", async () => {
diff --git a/apps/standalone/src/lightweight/backup-download.ts b/apps/standalone/src/lightweight/backup-download.ts
index 55ef549cc1..5ab98b04b9 100644
--- a/apps/standalone/src/lightweight/backup-download.ts
+++ b/apps/standalone/src/lightweight/backup-download.ts
@@ -124,31 +124,24 @@ export async function streamDatabaseDownload(
port.postMessage({ type: "chunk", data }, [ data ]);
};
- let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
+ let source: ReadableStream<Uint8Array> | undefined;
try {
const { byteSize, stream } = streamLiveDatabasePages(db);
+ source = stream;
- if (options.passphrase === undefined) {
- reader = stream.getReader();
- port.postMessage({ type: "begin", byteSize });
-
- for (;;) {
- const { done, value } = await reader.read();
- if (done) {
- port.postMessage({ type: "end" });
- return { status: "done" };
- }
- await sendChunk(value);
- }
- }
-
- port.postMessage({ type: "begin", byteSize: streamedContainerSize(byteSize) });
+ // A container either way, so every backup this application writes has one shape and one
+ // extension. Without a passphrase it is the database with a header in front of it, held to
+ // the size that header records; with one, every frame is authenticated as well.
+ const encrypted = !!options.passphrase;
+ port.postMessage({ type: "begin", byteSize: streamedContainerSize(byteSize, encrypted) });
await writeBackupContainer(
stream,
new WritableStream<Uint8Array>({ write: sendChunk }),
{
passphrase: options.passphrase,
streamed: true,
+ // Never compressed: at these sizes it costs more than a low-end device can spare,
+ // and the browser is downloading to a disk rather than over a wire.
plaintextSize: byteSize,
scrypt: options.scrypt
}
@@ -168,7 +161,9 @@ export async function streamDatabaseDownload(
post(port, { type: "error", message });
return { status: "failed", message };
} finally {
- await reader?.cancel().catch(() => undefined);
+ // Releases the pages still queued behind a stream that ended early; one already consumed
+ // or errored refuses, which is the same as being released.
+ await source?.cancel().catch(() => undefined);
port.onmessage = null;
port.close?.();
}
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index 585285668a..8be85cc33f 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -27,6 +27,7 @@ export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";
// The spreadsheet modules are deliberately not re-exported here: they pull in numfmt, and the
// 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/electron_api_interface.js";
export * from "./lib/setup_marker.js";
export * from "./lib/standalone_api_interface.js";
diff --git a/packages/commons/src/lib/backup_name.spec.ts b/packages/commons/src/lib/backup_name.spec.ts
new file mode 100644
index 0000000000..77d50e6f3b
--- /dev/null
+++ b/packages/commons/src/lib/backup_name.spec.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { defaultBackupName } from "./backup_name.js";
+
+describe("naming a backup", () => {
+ it("says what it is and when it was taken", () => {
+ expect(defaultBackupName(new Date(2026, 7, 8, 16, 30, 32)))
+ .toBe("Trilium data (2026-08-08 16-30-32)");
+ });
+
+ it("pads every part, so a directory listing sorts chronologically", () => {
+ expect(defaultBackupName(new Date(2026, 0, 2, 3, 4, 5)))
+ .toBe("Trilium data (2026-01-02 03-04-05)");
+ });
+
+ it("holds nothing a filename cannot, on any platform", () => {
+ // A colon is the obvious one: legal on Unix, refused by Windows, and the reason the time
+ // is dashed rather than written the way a clock is.
+ expect(defaultBackupName(new Date())).not.toMatch(/[<>:"/\\|?*]/);
+ });
+});
diff --git a/packages/commons/src/lib/backup_name.ts b/packages/commons/src/lib/backup_name.ts
new file mode 100644
index 0000000000..43540bbe99
--- /dev/null
+++ b/packages/commons/src/lib/backup_name.ts
@@ -0,0 +1,18 @@
+/**
+ * What a backup is called when the user has not said.
+ *
+ * Shared because every platform writes the same kind of file for the same reason, and a user who
+ * takes one from the desktop and one from a browser should not have to work out that the two are
+ * the same thing. The name has to survive being a filename on every one of them, so it holds no
+ * colons and nothing else Windows refuses.
+ *
+ * @param now the moment the backup was asked for, passed in so the caller decides what "now" is.
+ */
+export function defaultBackupName(now: Date): string {
+ const stamp = (value: number) => String(value).padStart(2, "0");
+ const date = [ now.getFullYear(), stamp(now.getMonth() + 1), stamp(now.getDate()) ].join("-");
+ const time = [ stamp(now.getHours()), stamp(now.getMinutes()), stamp(now.getSeconds()) ].join("-");
+
+ // Padded throughout, so a directory sorted by name is also sorted by date.
+ return `Trilium data (${date} ${time})`;
+}
diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.ts
index da3f33b5dd..e8678b6291 100644
--- a/packages/trilium-backup-container/src/container.spec.ts
+++ b/packages/trilium-backup-container/src/container.spec.ts
@@ -339,7 +339,7 @@ describe("peeking at a container", () => {
[ "fewer bytes than a header", Buffer.alloc(20) ],
[ "something that is not a container", Buffer.alloc(64, 9) ],
[ "a version it does not know", tamper((bytes) => bytes.writeUInt8(2, 20)) ],
- [ "a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b100, 21)) ]
+ [ "a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b1000, 21)) ]
])("answers null for %s, so one bad file cannot derail a listing", (_label, bytes) => {
expect(peekBackupContainer(bytes)).toBeNull();
});
@@ -503,7 +503,7 @@ describe("streamed containers", () => {
// No patch was asked of the destination, and none was needed.
expect(written.patchedAt).toEqual([]);
- expect(written.bytes.length).toBe(streamedContainerSize(database.length));
+ expect(written.bytes.length).toBe(streamedContainerSize(database.length, true));
// The digest field stays zeros, which is what "no digest" looks like in the header.
expect(written.bytes.subarray(HEADER_BYTES_ENCRYPTED - 32, HEADER_BYTES_ENCRYPTED)
.every((byte) => byte === 0)).toBe(true);
@@ -521,7 +521,7 @@ describe("streamed containers", () => {
const database = fakeDatabase(FRAME_SIZE);
const written = await writeToBuffer(database, STREAMED);
- expect(written.bytes.length).toBe(streamedContainerSize(FRAME_SIZE));
+ expect(written.bytes.length).toBe(streamedContainerSize(FRAME_SIZE, true));
const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });
expect(read.bytes.equals(database)).toBe(true);
});
@@ -534,16 +534,31 @@ describe("streamed containers", () => {
expect(await failureOf(tampered, { passphrase: PASSPHRASE })).toBe("damaged-payload");
});
- it("refuses to write a streamed container without encryption", async () => {
- expect(await reasonOf(writeToBuffer(fakeDatabase(), { streamed: true })))
- .toBe("invalid-options");
+ it("writes and reads one without a passphrase, held together by its recorded size", async () => {
+ const database = fakeDatabase(64 * 1024);
+ const written = await writeToBuffer(database, { streamed: true, plaintextSize: database.length });
+
+ expect(written.patchedAt).toEqual([]);
+ expect(written.bytes.length).toBe(streamedContainerSize(database.length, false));
+ expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES)))
+ .toMatchObject({ encrypted: false, streamed: true, compressed: false });
+
+ expect((await readFromBuffer(written.bytes)).bytes.equals(database)).toBe(true);
+ expect((await readFromBufferWeb(written.bytes)).bytes.equals(database)).toBe(true);
});
- it("refuses to read a streamed flag on an unencrypted container", async () => {
- const written = await writeToBuffer(fakeDatabase());
- const forged = Buffer.from(written.bytes);
- forged[21] |= 0b100;
+ it("catches a truncated unencrypted one, which is what a broken download leaves", async () => {
+ const database = fakeDatabase(64 * 1024);
+ const written = await writeToBuffer(database, { streamed: true, plaintextSize: database.length });
+
+ // The digest is gone, so the recorded size is what stands between a half-written
+ // download and a restore that trusts it.
+ expect(await failureOf(written.bytes.subarray(0, written.bytes.length - 1024)))
+ .toBe("size-mismatch");
+ });
- expect(await failureOf(forged)).toBe("unsupported-flags");
+ it("refuses to write an unencrypted streamed container that states no size", async () => {
+ expect(await reasonOf(writeToBuffer(fakeDatabase(), { streamed: true })))
+ .toBe("invalid-options");
});
});
diff --git a/packages/trilium-backup-container/src/format.spec.ts b/packages/trilium-backup-container/src/format.spec.ts
index 2beccc9065..cc6266b3af 100644
--- a/packages/trilium-backup-container/src/format.spec.ts
+++ b/packages/trilium-backup-container/src/format.spec.ts
@@ -25,6 +25,7 @@ function plainHeader(overrides: Partial<ContainerHeader> = {}): ContainerHeader
version: 1,
compressed: true,
encrypted: false,
+ streamed: false,
plaintextSize: 4096,
headerLength: HEADER_BYTES_PLAIN,
encryption: null,
@@ -132,7 +133,7 @@ describe("fixed header validation", () => {
[ "a newer version", (bytes: Buffer) => bytes.writeUInt8(2, 20), "unsupported-version" ],
[
"a reserved flag bit",
- (bytes: Buffer) => bytes.writeUInt8(0b100, 21),
+ (bytes: Buffer) => bytes.writeUInt8(0b1000, 21),
"unsupported-flags"
],
[
diff --git a/packages/trilium-backup-container/src/format.ts b/packages/trilium-backup-container/src/format.ts
index 61d83a4b65..fcb0ada018 100644
--- a/packages/trilium-backup-container/src/format.ts
+++ b/packages/trilium-backup-container/src/format.ts
@@ -20,9 +20,12 @@ export const FLAG_COMPRESSED = 0b0000_0001;
export const FLAG_ENCRYPTED = 0b0000_0010;
/**
* Written front to back, with no payload digest: the destination could not be revisited to patch
- * one in — a download already on its way to the user, for instance. Only ever valid together with
- * {@link FLAG_ENCRYPTED}: the frame tags then authenticate every payload byte, which is what the
- * digest was for, while on an unencrypted payload the digest is the only integrity there is.
+ * one in — a download already on its way to the user, for instance.
+ *
+ * What stands in for the digest depends on the other flags. Encrypted, every frame carries its own
+ * authentication tag, which covers each payload byte. Unencrypted, the recorded plaintext size is
+ * the check: the reader refuses output that does not measure exactly that, which is what a
+ * truncated download looks like. A streamed container therefore always records its size.
*/
export const FLAG_STREAMED = 0b0000_0100;
export const FLAG_RESERVED = 0b1111_1000;
@@ -213,14 +216,6 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F
}
const encrypted = (flags & FLAG_ENCRYPTED) !== 0;
const streamed = (flags & FLAG_STREAMED) !== 0;
- if (streamed && !encrypted) {
- // Without a digest and without frame tags there would be no integrity at all, so no
- // writer produces this and no reader trusts it.
- throw new BackupContainerError(
- "unsupported-flags",
- "A streamed container without encryption is never valid."
- );
- }
const headerLength = readU16LE(buffer, 22);
if (headerLength > maxHeaderBytes) {
@@ -252,12 +247,20 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F
}
/**
- * Exact byte length of a streamed, encrypted, uncompressed container wrapping `plaintextSize`
- * bytes: the header, the payload, and the length field and tag around every frame — including the
- * final frame, which is empty when the payload is an exact multiple of the frame size. Exactness
- * is the point: a download that states its size correctly is one the browser gives a progress bar.
+ * Exact byte length of a streamed, uncompressed container wrapping `plaintextSize` bytes.
+ *
+ * Encrypted, that is the header, the payload, and the length field and tag around every frame —
+ * including the final frame, which is empty when the payload is an exact multiple of the frame
+ * size. Unencrypted, the payload is written as it stands and only the header precedes it.
+ *
+ * Exactness is the point: a download that states its size correctly is one the browser can draw a
+ * progress bar for.
*/
-export function streamedContainerSize(plaintextSize: number): number {
+export function streamedContainerSize(plaintextSize: number, encrypted: boolean): number {
+ if (!encrypted) {
+ return HEADER_BYTES_PLAIN + plaintextSize;
+ }
+
const frames = Math.floor(plaintextSize / FRAME_SIZE) + 1;
return HEADER_BYTES_ENCRYPTED + plaintextSize + frames * (4 + TAG_BYTES);
diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.ts
index e6db63bdb9..e032ff414d 100644
--- a/packages/trilium-backup-container/src/read.ts
+++ b/packages/trilium-backup-container/src/read.ts
@@ -394,18 +394,22 @@ async function* readPlainPayload(
header: ContainerHeader,
backend: ContainerBackend
): AsyncGenerator<Uint8Array> {
- const hash = backend.createSha256();
+ // A streamed container records no digest, so hashing towards one would only slow the restore.
+ // What it records instead is its size, which `readContainer` holds the output to.
+ const hash = header.streamed ? null : backend.createSha256();
for (;;) {
const chunk = await reader.readUpTo(FRAME_SIZE);
if (chunk.length === 0) {
break;
}
- hash.update(chunk);
+ hash?.update(chunk);
yield chunk;
}
- verifyDigest(hash.digest(), header.digest);
+ if (hash) {
+ verifyDigest(hash.digest(), header.digest);
+ }
}
function verifyDigest(actual: Uint8Array, expected: Uint8Array): void {
diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.ts
index 48df1cb861..c6065e52e5 100644
--- a/packages/trilium-backup-container/src/write.ts
+++ b/packages/trilium-backup-container/src/write.ts
@@ -49,9 +49,11 @@ export interface WriteBackupContainerOptions extends ProgressOptions {
patchHeader?: PatchHeader;
/**
* Write front to back, recording no payload digest — for a destination that cannot be
- * revisited, such as a download already on its way to the user. Requires `passphrase`: the
- * GCM frame tags then authenticate every payload byte, which is what the digest was for,
- * while on an unencrypted payload the digest is the only integrity there is.
+ * revisited, such as a download already on its way to the user.
+ *
+ * Encrypted, the GCM frame tags stand in for the digest. Unencrypted, {@link
+ * WriteBackupContainerOptions.plaintextSize} does, so it is required: without either, nothing
+ * about the payload could be checked.
*/
streamed?: boolean;
/** Compress the payload with gzip. */
@@ -105,11 +107,11 @@ export async function writeContainer(
options: WriteBackupContainerOptions
): Promise<WriteBackupContainerResult> {
const streamed = options.streamed === true;
- if (streamed && options.passphrase === undefined) {
+ if (streamed && options.passphrase === undefined && !(options.plaintextSize ?? 0)) {
throw new BackupContainerError(
"invalid-options",
- "A streamed container must be encrypted: without a digest, the frame tags are the "
- + "only integrity it has."
+ "A streamed container that is not encrypted must record its plaintext size: with "
+ + "neither that nor frame tags, nothing about the payload could be checked."
);
}
if (!streamed && typeof options.patchHeader !== "function") {
diff --git a/packages/trilium-core/src/services/setup_existing.spec.ts b/packages/trilium-core/src/services/setup_existing.spec.ts
index acd9634c83..0d23d6a048 100644
--- a/packages/trilium-core/src/services/setup_existing.spec.ts
+++ b/packages/trilium-core/src/services/setup_existing.spec.ts
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { getBackup } from "./backup.js";
import {
backUpExistingData,
- backupNameFor,
deleteExistingData,
getExistingBackupProgress,
getExistingBackupStatus,
@@ -30,16 +29,6 @@ afterEach(() => {
vi.restoreAllMocks();
});
-describe("naming the backup", () => {
- it("is dated and readable, and is a filename on every platform", () => {
- expect(backupNameFor(new Date(2026, 7, 7, 10, 32, 21))).toBe("Backup 2026-08-07 10-32-21");
- // Padded, so a directory listing sorts by name and gets chronological order for free.
- expect(backupNameFor(new Date(2026, 0, 2, 3, 4, 5))).toBe("Backup 2026-01-02 03-04-05");
- // A colon is not a filename on Windows, and this one is written to a directory the user opens.
- expect(backupNameFor(new Date())).not.toContain(":");
- });
-});
-
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 };
@@ -51,7 +40,9 @@ describe("what becomes of the existing database", () => {
backup.backupAs = backupAs;
await expect(backUpExistingData(new Date(2026, 7, 7, 10, 32, 21))).resolves.toEqual(written);
- expect(backupAs).toHaveBeenCalledWith("Backup 2026-08-07 10-32-21", expect.any(Function));
+ // 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));
// Nothing is erased by taking a copy of it.
expect(platform.removeDatabase).not.toHaveBeenCalled();
diff --git a/packages/trilium-core/src/services/setup_existing.ts b/packages/trilium-core/src/services/setup_existing.ts
index 7c161e6b20..e879f37c6f 100644
--- a/packages/trilium-core/src/services/setup_existing.ts
+++ b/packages/trilium-core/src/services/setup_existing.ts
@@ -1,4 +1,4 @@
-import type { SetupExistingBackup, SetupExistingBackupStatus } from "@triliumnext/commons";
+import { defaultBackupName, type SetupExistingBackup, type SetupExistingBackupStatus } from "@triliumnext/commons";
import { getBackup } from "./backup.js";
import eventService from "./events.js";
@@ -22,9 +22,6 @@ import sqlInit from "./sql_init.js";
* @module
*/
-/** How the backup is named, since a user reading a directory listing is who has to recognise it. */
-const BACKUP_NAME_PREFIX = "Backup";
-
/**
* Backs the existing database up, and says where it went.
*
@@ -47,7 +44,7 @@ export async function backUpExistingData(now: Date): Promise<SetupExistingBackup
progress = 0;
try {
- const written = await backup.backupAs(backupNameFor(now), reportProgress);
+ const written = await backup.backupAs(defaultBackupName(now), reportProgress);
getLog().info(`Setup: the existing database was backed up (${written.fileSize} bytes).`);
return written;
@@ -157,21 +154,6 @@ export async function keepExistingData(): Promise<void> {
eventService.emit(eventService.DB_INITIALIZED);
}
-/**
- * The name a backup taken here is written under.
- *
- * Spaced and dated rather than slugged, because it is read in a file manager next to backups named
- * after the schedule that took them, and this one wants to be recognisable as the one from the day
- * everything was replaced. The time is dashed: a colon is not a filename on Windows.
- */
-export function backupNameFor(now: Date): string {
- const stamp = (value: number) => String(value).padStart(2, "0");
- const date = [ now.getFullYear(), stamp(now.getMonth() + 1), stamp(now.getDate()) ].join("-");
- const time = [ stamp(now.getHours()), stamp(now.getMinutes()), stamp(now.getSeconds()) ].join("-");
-
- return `${BACKUP_NAME_PREFIX} ${date} ${time}`;
-}
-
/**
* Refuses everything here on an instance that has nothing to lose.
*