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: refactor, mark invalid or unsupported containers in the existing backup list
Adorian Doranf002c60840cd
diff --git a/apps/client/src/services/database_files.spec.ts b/apps/client/src/services/database_files.spec.tsnew file mode 100644index 0000000000..1acd2d0048--- /dev/null+++ b/apps/client/src/services/database_files.spec.ts@@ -0,0 +1,46 @@+import { describe, expect, it, vi } from "vitest";++// i18next is never initialised in these tests, so t() would return nothing at all. Echoing the key+// keeps the assertions about which sentence is chosen rather than about its English.+vi.mock("./i18n.js", () => ({+ t: (key: string, values?: Record<string, unknown>) =>+ [ key, ...Object.values(values ?? {}) ].join(" ")+}));++import { describeDatabaseFile } from "./database_files.js";++const FILE = {+ fileName: "backup-daily.tnbackup",+ filePath: "/data/backup/backup-daily.tnbackup",+ mtime: new Date("2026-02-03T04:05:06Z"),+ fileSize: 2 * 1024 * 1024+};++describe("the line under a backup's name", () => {+ it("states when it was taken and how big it is", () => {+ expect(describeDatabaseFile(FILE)).toContain("2 MiB");+ expect(describeDatabaseFile(FILE)).not.toContain("database_file_list");+ });++ it("states both sizes for a backup smaller than the database it was made from", () => {+ const described = describeDatabaseFile({ ...FILE, plaintextSize: 8 * 1024 * 1024 });++ expect(described).toContain("8 MiB");+ expect(described).toContain("database_file_list.size_on_disk 2 MiB");+ });++ it.each([+ [ "invalid" as const, "database_file_list.invalid_backup" ],+ [ "unsupported-version" as const, "database_file_list.unsupported_version" ]+ ])("says a %s backup cannot be restored from, without dropping what it is", (+ unreadable,+ expected+ ) => {+ const described = describeDatabaseFile({ ...FILE, unreadable });++ expect(described.endsWith(expected)).toBe(true);+ // The date and the size stay: a backup that stopped halfway is the size of how far it got,+ // which is what tells the user why this one is no good.+ expect(described).toContain("2 MiB");+ });+});diff --git a/apps/client/src/services/database_files.ts b/apps/client/src/services/database_files.tsindex f296342c81..c1a19c7b1f 100644--- a/apps/client/src/services/database_files.ts+++ b/apps/client/src/services/database_files.ts@@ -14,6 +14,11 @@ export interface DatabaseFile {* size — a compressed backup, say. Both are then shown, so the saving is visible.*/plaintextSize?: number;+ /**+ * Why the file cannot be restored from, where its own header says as much. Absent for a plain+ * copy and for a container this build can open.+ */+ unreadable?: "invalid" | "unsupported-version";}/**@@ -54,5 +59,14 @@ export function describeDatabaseFile(file: DatabaseFile): string {parts.push(formatSize(file.fileSize));}+ // Last, after the two facts that identify which file this is. The date and the size are kept+ // rather than replaced because they are what tells the user why it is no good: a backup that+ // stopped halfway is the size of how far it got.+ if (file.unreadable) {+ parts.push(file.unreadable === "invalid"+ ? t("database_file_list.invalid_backup")+ : t("database_file_list.unsupported_version"));+ }+return parts.join(" • ");}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex f11e9e5e26..e9fd7b7c47 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2106,7 +2106,9 @@"encrypted": "Encrypted"},"database_file_list": {- "size_on_disk": "{{size}} on disk"+ "size_on_disk": "{{size}} on disk",+ "invalid_backup": "Invalid backup file",+ "unsupported_version": "Unsupported backup file format version"},"password_with_confirmation": {"password": "Password",diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.tsindex 60d625767d..e08eca5128 100644--- a/apps/server/src/backup_provider.spec.ts+++ b/apps/server/src/backup_provider.spec.ts@@ -257,7 +257,7 @@ describe("ServerBackupService: backup format", () => {expect(byName.get("backup-plain.db")).not.toHaveProperty("plaintextSize");});- it("lists a container it cannot make sense of, rather than dropping it", async () => {+ it("lists a container it cannot make sense of, saying so rather than dropping it", async () => {fs.mkdirSync(DEFAULT_DIR, { recursive: true });fs.writeFileSync(path.join(DEFAULT_DIR, "backup-damaged.tnbackup"),@@ -266,10 +266,33 @@ describe("ServerBackupService: backup format", () => {const backups = await desktopService("").getExistingBackups();+ // Listed, because a file sitting in the backup directory is one the user is relying on,+ // and saying it is no good is the whole point of listing it.expect(backups.map((b) => b.fileName)).toEqual([ "backup-damaged.tnbackup" ]);+ expect(backups[0]).toMatchObject({ unreadable: "invalid" });expect(backups[0]).not.toHaveProperty("compressed");expect(backups[0]).not.toHaveProperty("encrypted");});++ it("tells a backup from a newer Trilium apart from one that is not a backup", async () => {+ fs.mkdirSync(DEFAULT_DIR, { recursive: true });++ const compressing = desktopService("", { backupEnableCompression: "true" });+ const newer = fs.readFileSync(await compressing.backupNow("daily"));+ // The version byte, straight after the magic. Everything else about the file is intact,+ // which is exactly the case that must not read as damaged.+ newer.writeUInt8(2, 20);+ fs.writeFileSync(path.join(DEFAULT_DIR, "backup-newer.tnbackup"), newer);++ const byName = new Map(+ (await desktopService("").getExistingBackups()).map((b) => [ b.fileName, b ])+ );++ expect(byName.get("backup-newer.tnbackup")).toMatchObject({+ unreadable: "unsupported-version"+ });+ expect(byName.get("backup-daily.tnbackup")).not.toHaveProperty("unreadable");+ });});describe("ServerBackupService.backupAs: the backup the setup screen asked for", () => {diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.tsindex f2259d71e0..d733b32831 100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@ -305,7 +305,8 @@ function listBackupsIn(directory: string): DatabaseBackup[] {* 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.+ * passphrase. A file that is not a container this build can open is still listed, saying why: it is+ * sitting in the backup directory being counted as a backup, and the user is relying on it.*/function describeContainer(filePath: string, fileName: string): Partial<DatabaseBackup> {if (!fileName.endsWith(CONTAINER_EXTENSION)) {@@ -313,11 +314,13 @@ function describeContainer(filePath: string, fileName: string): Partial<Database}const head = Buffer.alloc(FIXED_HEADER_BYTES);+ let read: number;let descriptor: number | undefined;try {descriptor = fs.openSync(filePath, "r");- fs.readSync(descriptor, head, 0, head.length, 0);+ read = fs.readSync(descriptor, head, 0, head.length, 0);} catch {+ // Nothing was learned, which is not the same as having learned the file is no good.return {};} finally {if (descriptor !== undefined) {@@ -325,9 +328,14 @@ function describeContainer(filePath: string, fileName: string): Partial<Database}}- const info = getInfo(head);- if (!info.isValid || !info.isSupported) {- return {};+ // Only what the file actually held, so a file too short to have a header is judged on that+ // rather than on the zeroes the buffer came with.+ const info = getInfo(head.subarray(0, read));+ if (!info.isValid) {+ return { unreadable: "invalid" };+ }+ if (!info.isSupported) {+ return { unreadable: "unsupported-version" };}return {diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 17ada60b6f..347239feff 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -186,6 +186,14 @@ export interface DatabaseBackup {* for a plain copy, where the file size already says it.*/plaintextSize?: number;+ /**+ * Why the file cannot be restored from, where its own header says as much. Absent for a plain+ * copy and for a container this build can open.+ *+ * Worth a listing telling the user about: a file that has been sitting in the backup directory+ * for months, being counted as a backup, is one they are relying on.+ */+ unreadable?: "invalid" | "unsupported-version";}export interface ExistingBackupsResponse {