Skip to content

Build your personal knowledge base with Trilium Notes

client/options/backup: show extra info about existing backups

Adorian Doran609f3023f9ed
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 49b442b6ec..5b6b8b3bf3 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2052,7 +2052,12 @@
"password_modal_description": "Keep a copy of this password somewhere safe. Trilium cannot show it again, and without it a backup cannot be restored.",
"save_password": "Save password",
"password_stored": "The backup password has been saved.",
- "password_not_stored": "The backup password could not be saved."
+ "password_not_stored": "The backup password could not be saved.",
+ "compressed": "Compressed",
+ "encrypted": "Encrypted"
+ },
+ "database_file_list": {
+ "size_on_disk": "{{size}} on disk"
},
"password_with_confirmation": {
"password": "Password",
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index ce375f2c8f..9245f54054 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -17,7 +17,7 @@ import FormToggle from "../../react/FormToggle";
import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import Icon from "../../react/Icon";
import Modal from "../../react/Modal";
-import DatabaseFileList, { type DatabaseFile } from "./components/DatabaseFileList";
+import DatabaseFileList from "./components/DatabaseFileList";
import OptionsPageHeader from "./components/OptionsPageHeader";
import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";
import OptionsSection from "./components/OptionsSection";
@@ -270,20 +270,31 @@ export function BackupList({ backups, backupFolderPath, refreshCallback }: { bac
const [backupInProgress, setBackupInProgress] = useState(false);
const [customDir] = useTriliumOption("customDbBackupDir");
- // With a custom location in use the list also carries whatever stayed in — or was redirected to —
- // the default one, and a row shows only a file name, so those need telling apart.
- const fileBadge = useCallback((file: DatabaseFile) => (
- customDir && backupFolderPath && !isInsideDirectory(backupFolderPath, file.filePath)
- ? t("backup.default_location")
- : undefined
- ), [customDir, backupFolderPath]);
+ // What a row cannot say for itself: the format it was written in, and — with a custom location in
+ // use, where the list also carries whatever stayed in or was redirected to the default one — which
+ // directory it is in.
+ const fileBadges = useCallback((file: DatabaseBackup) => {
+ const badges: string[] = [];
+
+ if (customDir && backupFolderPath && !isInsideDirectory(backupFolderPath, file.filePath)) {
+ badges.push(t("backup.default_location"));
+ }
+ if (file.compressed) {
+ badges.push(t("backup.compressed"));
+ }
+ if (file.encrypted) {
+ badges.push(t("backup.encrypted"));
+ }
+
+ return badges;
+ }, [customDir, backupFolderPath]);
return (
// Where the backups live is stated by the "Backup location" card above, not repeated here.
<DatabaseFileList
title={t("backup.existing_backups")}
files={backups}
- fileBadge={fileBadge}
+ fileBadges={fileBadges}
downloadEndpoint="api/database/backup/download"
rowName="existing-backup"
downloadText={t("backup.download")}
diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
index c34acbb146..e4e5e04488 100644
--- a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
@@ -3,6 +3,7 @@ import "./DatabaseFileList.css";
import { ComponentChildren } from "preact";
import { useMemo } from "preact/hooks";
+import { t } from "../../../../services/i18n";
import open from "../../../../services/open";
import { formatSize } from "../../../../services/utils";
import { formatDateTime } from "../../../../utils/formatters";
@@ -18,14 +19,19 @@ export interface DatabaseFile {
mtime: Date;
/** Size of the file, in bytes. */
fileSize: number;
+ /**
+ * Size of the database the file was made from, in bytes, where that differs from the file's own
+ * size — a compressed backup, say. Both are then shown, so the saving is visible.
+ */
+ plaintextSize?: number;
}
-interface DatabaseFileListProps {
+interface DatabaseFileListProps<T extends DatabaseFile> {
title: string;
/** Sentence describing where the files are stored; omitted when there is no user-accessible location. */
locationDescription?: string | null;
/** Displayed sorted by modification date & time in a descending order. */
- files: DatabaseFile[];
+ files: T[];
/** Endpoint the per-file download links point to; the file path is appended as a query parameter. */
downloadEndpoint: string;
rowName: string;
@@ -33,12 +39,12 @@ interface DatabaseFileListProps {
emptyIcon: string;
emptyText: string;
/** Labels individual files, for the ones that need telling apart — e.g. one kept somewhere else. */
- fileBadge?: (file: DatabaseFile) => string | undefined;
+ fileBadges?: (file: T) => string[];
/** Extra content rendered below the list (e.g. an action button). */
children?: ComponentChildren;
}
-export default function DatabaseFileList({ title, locationDescription, files, downloadEndpoint, rowName, downloadText, emptyIcon, emptyText, fileBadge, children }: DatabaseFileListProps) {
+export default function DatabaseFileList<T extends DatabaseFile>({ title, locationDescription, files, downloadEndpoint, rowName, downloadText, emptyIcon, emptyText, fileBadges, children }: DatabaseFileListProps<T>) {
const sortedFiles = useMemo(() => [...files].sort((a, b) => {
if (a.mtime < b.mtime) return 1;
if (a.mtime > b.mtime) return -1;
@@ -60,10 +66,12 @@ export default function DatabaseFileList({ title, locationDescription, files, do
label={
<span className="database-file-label">
<span className="selectable-text">{file.fileName}</span>
- {fileBadge?.(file) && <Badge className="database-file-badge" text={fileBadge(file)} outline />}
+ {fileBadges?.(file).map((badge) => (
+ <Badge key={badge} className="database-file-badge" text={badge} outline />
+ ))}
</span>
}
- description={`${file.mtime ? formatDateTime(file.mtime) : "-"} • ${formatSize(file.fileSize)}`}
+ description={describeFile(file)}
>
<ActionButton
icon="bx bx-download"
@@ -80,3 +88,19 @@ export default function DatabaseFileList({ title, locationDescription, files, do
</OptionsSection>
);
}
+
+/**
+ * When the file was written, and how big it is. A file made from a database larger than itself states
+ * both, so what compressing it saved is visible rather than having to be worked out.
+ */
+function describeFile(file: DatabaseFile): string {
+ const parts = [file.mtime ? formatDateTime(file.mtime) : "-"];
+
+ if (file.plaintextSize && file.plaintextSize !== file.fileSize) {
+ parts.push(formatSize(file.plaintextSize), t("database_file_list.size_on_disk", { size: formatSize(file.fileSize) }));
+ } else {
+ parts.push(formatSize(file.fileSize));
+ }
+
+ return parts.join(" • ");
+}
diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.ts
index 98b0563e3b..338b96a610 100644
--- a/apps/server/src/backup_provider.spec.ts
+++ b/apps/server/src/backup_provider.spec.ts
@@ -200,6 +200,32 @@ describe("ServerBackupService: backup format", () => {
expect(backups.map((b) => b.fileName).sort()).toEqual(["backup-daily.tnbackup", "backup-weekly.db"]);
});
+
+ it("reads what each container is from its own header, not from today's options", async () => {
+ await desktopService("", { backupEnableCompression: "true" }).backupNow("compressed");
+ await desktopService("", { backupEnableEncryption: "true" }, withPassphrase).backupNow("encrypted");
+ await desktopService("").backupNow("plain");
+
+ // Listed by a service with both switched off: a backup keeps the shape it was written in.
+ const byName = new Map((await desktopService("").getExistingBackups()).map((b) => [b.fileName, b]));
+
+ expect(byName.get("backup-compressed.tnbackup")).toMatchObject({ compressed: true, encrypted: false, plaintextSize: "db-bytes".length });
+ expect(byName.get("backup-encrypted.tnbackup")).toMatchObject({ compressed: false, encrypted: true });
+ // A plain copy states nothing of the sort: its own size is the whole story.
+ expect(byName.get("backup-plain.db")).not.toHaveProperty("compressed");
+ expect(byName.get("backup-plain.db")).not.toHaveProperty("plaintextSize");
+ });
+
+ it("lists a container it cannot make sense of, rather than dropping it", async () => {
+ fs.mkdirSync(DEFAULT_DIR, { recursive: true });
+ fs.writeFileSync(path.join(DEFAULT_DIR, "backup-damaged.tnbackup"), "not a container at all");
+
+ const backups = await desktopService("").getExistingBackups();
+
+ expect(backups.map((b) => b.fileName)).toEqual(["backup-damaged.tnbackup"]);
+ expect(backups[0]).not.toHaveProperty("compressed");
+ expect(backups[0]).not.toHaveProperty("encrypted");
+ });
});
describe("ServerBackupService: when the backup passphrase cannot be read", () => {
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.ts
index f6af28db92..a9d7d24353 100644
--- a/apps/server/src/backup_provider.ts
+++ b/apps/server/src/backup_provider.ts
@@ -1,4 +1,4 @@
-import { writeBackupContainer } from "@triliumnext/backup-container";
+import { FIXED_HEADER_BYTES, peekBackupContainer, writeBackupContainer } from "@triliumnext/backup-container";
import type { DatabaseBackup } from "@triliumnext/commons";
import { BackupOptionsService, BackupService, utils as coreUtils, getLog, sync_mutex as syncMutexService, ws } from "@triliumnext/core";
import fs from "fs";
@@ -199,10 +199,48 @@ function listBackupsIn(directory: string): DatabaseBackup[] {
return [];
}
- return [{ fileName, filePath, mtime: stat.mtime, fileSize: stat.size }];
+ return [{ fileName, filePath, mtime: stat.mtime, fileSize: stat.size, ...describeContainer(filePath, fileName) }];
});
}
+/**
+ * What a container is, read from its own header rather than from today's options: a backup keeps the
+ * shape it was written in, whatever the settings have since become.
+ *
+ * Only the fixed header is read, so this costs a few dozen bytes per file and never needs the
+ * passphrase. A file whose header does not parse is listed as a plain one rather than not at all.
+ */
+function describeContainer(filePath: string, fileName: string): Partial<DatabaseBackup> {
+ if (!fileName.endsWith(CONTAINER_EXTENSION)) {
+ return {};
+ }
+
+ const head = Buffer.alloc(FIXED_HEADER_BYTES);
+ let descriptor: number | undefined;
+ try {
+ descriptor = fs.openSync(filePath, "r");
+ fs.readSync(descriptor, head, 0, head.length, 0);
+ } catch {
+ return {};
+ } finally {
+ if (descriptor !== undefined) {
+ fs.closeSync(descriptor);
+ }
+ }
+
+ const info = peekBackupContainer(head);
+ if (!info) {
+ return {};
+ }
+
+ return {
+ compressed: info.compressed,
+ encrypted: info.encrypted,
+ // Recorded as 0 when the writer did not know it, which reads the same as "not stated".
+ plaintextSize: info.plaintextSize > 0 ? info.plaintextSize : undefined
+ };
+}
+
async function writeBackup(directory: string, baseName: string, format: BackupFormat, location: "default" | "custom"): Promise<string> {
const isContainer = format.compress || format.passphrase !== null;
const fileName = `${baseName}${isContainer ? CONTAINER_EXTENSION : DATABASE_EXTENSION}`;
diff --git a/apps/server/tsconfig.app.json b/apps/server/tsconfig.app.json
index b416e1af91..f0105d73f3 100644
--- a/apps/server/tsconfig.app.json
+++ b/apps/server/tsconfig.app.json
@@ -44,6 +44,9 @@
{
"path": "../../packages/express-partial-content/tsconfig.lib.json"
},
+ {
+ "path": "../../packages/trilium-backup-container/tsconfig.lib.json"
+ },
{
"path": "../../packages/commons/tsconfig.lib.json"
},
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index dbcf8661a2..bdb8938c45 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -173,6 +173,18 @@ export interface DatabaseBackup {
mtime: Date;
/** Size of the backup file, in bytes. */
fileSize: number;
+ /**
+ * Whether the backup is gzip-compressed. Absent for a plain database copy, and for a container
+ * whose header could not be read.
+ */
+ compressed?: boolean;
+ /** Whether the backup is encrypted. Absent under the same conditions as {@link compressed}. */
+ encrypted?: boolean;
+ /**
+ * Size of the wrapped database before compression, in bytes, as recorded by the writer. Absent
+ * for a plain copy, where the file size already says it.
+ */
+ plaintextSize?: number;
}
export interface ExistingBackupsResponse {
diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.ts
index 43853a4674..a06e33c7b2 100644
--- a/packages/trilium-backup-container/src/container.spec.ts
+++ b/packages/trilium-backup-container/src/container.spec.ts
@@ -4,12 +4,13 @@ import { gunzipSync } from "node:zlib";
import { describe, expect, it } from "vitest";
import {
+ FIXED_HEADER_BYTES,
FRAME_SIZE,
HEADER_BYTES_ENCRYPTED,
HEADER_BYTES_PLAIN,
TAG_BYTES
} from "./format.js";
-import { readBackupContainer } from "./read.js";
+import { peekBackupContainer, readBackupContainer } from "./read.js";
import {
chunked,
fakeDatabase,
@@ -240,6 +241,50 @@ describe("damage and tampering", () => {
});
});
+describe("peeking at a container", () => {
+ it.each([
+ ["plain", {}, { compressed: false, encrypted: false }],
+ ["compressed", { compress: true }, { compressed: true, encrypted: false }],
+ ["encrypted", { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }, { compressed: false, encrypted: true }],
+ ["both", { compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }, { compressed: true, encrypted: true }]
+ ] as [string, WriteOptions, { compressed: boolean; encrypted: boolean }][])("reports a %s container from its first bytes alone", async (_label, options, expected) => {
+ const database = fakeDatabase(9_000);
+ const written = await writeToBuffer(database, { ...options, plaintextSize: database.length });
+
+ // Only the fixed header, and no passphrase, which is the whole point of the peek.
+ expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES))).toEqual({
+ version: 1,
+ plaintextSize: 9_000,
+ ...expected
+ });
+ });
+
+ it("reports an unrecorded plaintext size as zero rather than guessing", async () => {
+ const written = await writeToBuffer(fakeDatabase(4096), { compress: true });
+
+ expect(peekBackupContainer(written.bytes)?.plaintextSize).toBe(0);
+ });
+
+ it.each([
+ ["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))]
+ ])("answers null for %s, so one bad file cannot derail a listing", (_label, bytes) => {
+ expect(peekBackupContainer(bytes)).toBeNull();
+ });
+});
+
+function tamper(mutate: (bytes: Buffer) => void): Buffer {
+ const header = Buffer.alloc(FIXED_HEADER_BYTES);
+ Buffer.from("Trilium Notes Backup", "ascii").copy(header, 0);
+ header.writeUInt8(1, 20);
+ header.writeUInt16LE(64, 22);
+ mutate(header);
+
+ return header;
+}
+
describe("input that is not a container", () => {
it.each([
["random bytes", Buffer.alloc(300, 9), "not-a-container"],
diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.ts
index a7380e940a..e1586ea028 100644
--- a/packages/trilium-backup-container/src/index.ts
+++ b/packages/trilium-backup-container/src/index.ts
@@ -42,6 +42,7 @@
export { BackupContainerError, type BackupContainerErrorReason, isBackupContainerError } from "./errors.js";
export {
+ FIXED_HEADER_BYTES,
FORMAT_VERSION,
FRAME_SIZE,
SCRYPT_BOUNDS,
@@ -49,7 +50,9 @@ export {
type ScryptParams
} from "./format.js";
export {
+ type BackupContainerInfo,
DEFAULT_MAX_OUTPUT_BYTES,
+ peekBackupContainer,
readBackupContainer,
type ReadBackupContainerOptions,
type ReadBackupContainerResult
diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.ts
index 24f23a6231..a8c674008c 100644
--- a/packages/trilium-backup-container/src/read.ts
+++ b/packages/trilium-backup-container/src/read.ts
@@ -48,6 +48,36 @@ export interface ReadBackupContainerOptions {
requireSqliteHeader?: boolean;
}
+/** What a container says about itself, before any of its payload is read. */
+export interface BackupContainerInfo {
+ version: number;
+ compressed: boolean;
+ encrypted: boolean;
+ /** Size of the wrapped database before compression, or 0 when the writer did not record it. */
+ plaintextSize: number;
+}
+
+/**
+ * Identifies a container from its first {@link FIXED_HEADER_BYTES} bytes, without touching the payload
+ * and without the passphrase: what a container is, is stated in the clear.
+ *
+ * Returns `null` for anything this reader does not recognise, so that listing a directory of backups is
+ * never derailed by one damaged or foreign file.
+ */
+export function peekBackupContainer(head: Buffer, maxHeaderBytes: number = DEFAULT_MAX_HEADER_BYTES): BackupContainerInfo | null {
+ if (head.length < FIXED_HEADER_BYTES) {
+ return null;
+ }
+
+ try {
+ const { version, compressed, encrypted, plaintextSize } = decodeFixedHeader(head.subarray(0, FIXED_HEADER_BYTES), maxHeaderBytes);
+
+ return { version, compressed, encrypted, plaintextSize };
+ } catch {
+ return null;
+ }
+}
+
export interface ReadBackupContainerResult {
version: number;
compressed: boolean;