Skip to content

Build your personal knowledge base with Trilium Notes

fix some issues

Adorian Doranf2ab2a49ca9e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 5b6b8b3bf3..ac269d7daa 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2053,6 +2053,7 @@
"save_password": "Save password",
"password_stored": "The backup password has been saved.",
"password_not_stored": "The backup password could not be saved.",
+ "encryption_not_disabled": "The backup password was removed, but encryption could not be switched off. Backups will not be encrypted until you turn encryption on again.",
"compressed": "Compressed",
"encrypted": "Encrypted"
},
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index 00ae653036..9558defb2a 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import dialogService from "../../../services/dialog";
import { t } from "../../../services/i18n";
+import options from "../../../services/options";
import server from "../../../services/server";
import toast from "../../../services/toast";
import { isElectron } from "../../../services/utils";
@@ -192,8 +193,17 @@ export function BackupOptions() {
// Re-read either way: a declined confirmation has to put the switch back where it was.
await refreshPassphrase();
- if (result === "applied") {
- await setEncryptionEnabled(false);
+ if (result !== "applied") {
+ return;
+ }
+
+ await setEncryptionEnabled(false);
+
+ // Saving an option swallows its own failure, and the passphrase is already gone by now. Left
+ // unsaid, every later backup would quietly fall back to an unencrypted one in the default
+ // directory, with nothing on this page to explain why.
+ if (options.is("backupEnableEncryption")) {
+ toast.showError(t("backup.encryption_not_disabled"));
}
}
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 50bae5ad1c..6703fe648b 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -32,7 +32,10 @@ import { setupReferer } from "./services/referer";
import { setupDialogHandlers } from "./services/dialog";
import { setupExportHandlers } from "./services/export";
import { setupImportHandlers } from "./services/import";
-import { getBackupPassphrase, registerBackupPassphraseIpcHandlers } from "./services/backup_passphrase";
+import {
+ getBackupPassphrase,
+ registerBackupPassphraseIpcHandlers
+} from "./services/backup_passphrase";
import { setupOneNoteHandlers } from "./services/onenote";
import { setupPrintingHandlers } from "./services/printing";
import ElectronRequestProvider from "./services/request";
@@ -262,7 +265,10 @@ export async function main() {
inAppHelp: new NodejsInAppHelpProvider(),
log: new ServerLogService(),
// Only the desktop lets the user pick where backups go; the server uses TRILIUM_BACKUP_DIR.
- backup: new ServerBackupService(options, { allowCustomDirectory: true, getPassphrase: getBackupPassphrase }),
+ backup: new ServerBackupService(
+ options,
+ { allowCustomDirectory: true, getPassphrase: getBackupPassphrase }
+ ),
image: (await import("@triliumnext/server/src/services/image_provider.js")).serverImageProvider,
config,
extraAppInfo: {
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index a46e80726f..76ccc7507d 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -616,17 +616,26 @@ describe("preload script", () => {
it("getStatus invokes the corresponding IPC channel", async () => {
await backupPassphrase().getStatus();
- expect(ipcRendererInvoked).toContainEqual({ channel: "backup-passphrase-status", args: [] });
+ expect(ipcRendererInvoked).toContainEqual(
+ { channel: "backup-passphrase-status",
+ args: [] }
+ );
});
it("set invokes the corresponding IPC channel", async () => {
await backupPassphrase().set("hunter2");
- expect(ipcRendererInvoked).toContainEqual({ channel: "backup-passphrase-set", args: ["hunter2"] });
+ expect(ipcRendererInvoked).toContainEqual(
+ { channel: "backup-passphrase-set",
+ args: ["hunter2"] }
+ );
});
it("clear invokes the corresponding IPC channel", async () => {
await backupPassphrase().clear();
- expect(ipcRendererInvoked).toContainEqual({ channel: "backup-passphrase-clear", args: [] });
+ expect(ipcRendererInvoked).toContainEqual(
+ { channel: "backup-passphrase-clear",
+ args: [] }
+ );
});
it("exposes no way to read the passphrase back", () => {
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index b70c972211..7d003fe6a5 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -1,4 +1,12 @@
-import type { BackupPassphraseChange, BackupPassphraseStatus, ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";
+import type {
+ BackupPassphraseChange,
+ BackupPassphraseStatus,
+ ElectronApi,
+ ElectronContextMenuParams,
+ NativeImportOptions,
+ OneNoteLoginResult,
+ RendererStartupMetric
+} from "@triliumnext/commons";
import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";
contextBridge.exposeInMainWorld("electronApi", {
diff --git a/apps/desktop/src/services/backup_passphrase.spec.ts b/apps/desktop/src/services/backup_passphrase.spec.ts
index c34c3c32cd..ee2350d7a3 100644
--- a/apps/desktop/src/services/backup_passphrase.spec.ts
+++ b/apps/desktop/src/services/backup_passphrase.spec.ts
@@ -10,7 +10,8 @@ const h = vi.hoisted(() => ({
storageBackend: "gnome_libsecret",
platform: "linux",
// Base64 rather than a readable prefix, so "never stored in the clear" is a real assertion.
- encrypt: vi.fn(async (plainText: string) => Buffer.from(Buffer.from(plainText, "utf8").toString("base64"), "utf8")),
+ encrypt: vi.fn(async (plainText: string) =>
+ Buffer.from(Buffer.from(plainText, "utf8").toString("base64"), "utf8")),
decrypt: vi.fn(async (buffer: Buffer) => ({
result: Buffer.from(buffer.toString("utf8"), "base64").toString("utf8"),
shouldReEncrypt: false
@@ -23,9 +24,12 @@ const isPassphrasePath = (p: unknown) => String(p).includes("backup-passphrase.b
vi.mock("fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("fs") & { default?: typeof import("fs") }>();
const real = actual.default ?? actual;
- const existsSync = (p: fs.PathLike) => (isPassphrasePath(p) ? h.fileStore.has(String(p)) : real.existsSync(p));
+ const existsSync = (p: fs.PathLike) =>
+ (isPassphrasePath(p) ? h.fileStore.has(String(p)) : real.existsSync(p));
const readFileSync = ((p: fs.PathLike, enc?: unknown) =>
- isPassphrasePath(p) ? h.fileStore.get(String(p)) : real.readFileSync(p, enc as never)) as typeof real.readFileSync;
+ isPassphrasePath(p)
+ ? h.fileStore.get(String(p))
+ : real.readFileSync(p, enc as never)) as typeof real.readFileSync;
const writeFileSync = ((p: fs.PathLike, data: Buffer) => {
h.fileStore.set(String(p), Buffer.from(data));
}) as typeof real.writeFileSync;
@@ -40,7 +44,15 @@ vi.mock("fs", async (importOriginal) => {
h.fileStore.delete(String(p));
}) as typeof real.rmSync;
const patched = { ...real, existsSync, readFileSync, writeFileSync, renameSync, rmSync };
- return { ...actual, default: patched, existsSync, readFileSync, writeFileSync, renameSync, rmSync };
+ return {
+ ...actual,
+ default: patched,
+ existsSync,
+ readFileSync,
+ writeFileSync,
+ renameSync,
+ rmSync
+ };
});
vi.mock("i18next", () => ({ t: (key: string) => key }));
@@ -67,6 +79,8 @@ vi.mock("@triliumnext/core", () => ({
getLog: () => ({ error: (message: string) => h.errors.push(message) })
}));
+type ConfirmCase = [string, [string, ...unknown[]]];
+
const passphrase = await import("./backup_passphrase.js");
describe("backup passphrase storage", () => {
@@ -120,7 +134,7 @@ describe("backup passphrase storage", () => {
expect(h.encrypt).toHaveBeenCalledWith("hunter2");
});
- it("returns null and logs, without the passphrase, when the blob cannot be decrypted", async () => {
+ it("returns null and logs, without the passphrase, when the blob will not open", async () => {
await passphrase.storeBackupPassphrase("hunter2");
h.decrypt.mockRejectedValueOnce(new Error("keyring is locked"));
@@ -142,7 +156,10 @@ describe("keyring availability", () => {
it.each([
["the app is not ready yet", () => { h.isReady = false; }],
["the platform offers no encryption", () => { h.encryptionAvailable = false; }],
- ["Linux falls back to the hardcoded-password backend", () => { h.storageBackend = "basic_text"; }]
+ [
+ "Linux falls back to the hardcoded-password backend",
+ () => { h.storageBackend = "basic_text"; }
+ ]
])("treats the keyring as unavailable when %s", async (_label, arrange) => {
arrange();
@@ -205,13 +222,17 @@ describe("IPC handlers", () => {
it.each([
["set", ["backup-passphrase-set", "hunter2"]],
["clear", ["backup-passphrase-clear"]]
- ] as [string, [string, ...unknown[]]][])("asks the OS before it %ss, and offers no way to stop being asked", async (_label, call) => {
+ ] as ConfirmCase[])("asks the OS before it %ss, with no escape from asking", async (
+ _label,
+ call
+ ) => {
await invoke(...call);
expect(h.showMessageBox).toHaveBeenCalledOnce();
const options = h.showMessageBox.mock.calls[0][0];
expect(options).toMatchObject({ type: "warning", cancelId: 0 });
- // The security settings offer "don't ask again"; skipping the question is the vulnerability here.
+ // The security settings offer "don't ask again"; skipping the question is the vulnerability
+ // here.
expect(options).not.toHaveProperty("checkboxLabel");
});
diff --git a/apps/desktop/src/services/backup_passphrase.ts b/apps/desktop/src/services/backup_passphrase.ts
index 178e8b267e..5fa7e2b223 100644
--- a/apps/desktop/src/services/backup_passphrase.ts
+++ b/apps/desktop/src/services/backup_passphrase.ts
@@ -18,15 +18,16 @@ const TEMP_PATH = `${PASSPHRASE_PATH}.tmp`;
* Whether the OS has somewhere safe to keep the passphrase.
*
* `isEncryptionAvailable()` alone is not enough. On Linux without a keyring the selected backend is
- * `basic_text`, which "encrypts" with a hardcoded password, so the file would be plaintext in all but
- * name. Both that and the backend name are only meaningful once the app is ready.
+ * `basic_text`, which "encrypts" with a hardcoded password, so the file would be plaintext in all
+ * but name. Both that and the backend name are only meaningful once the app is ready.
*/
export function isKeyringAvailable(): boolean {
if (!electron.app.isReady() || !electron.safeStorage.isEncryptionAvailable()) {
return false;
}
- return process.platform !== "linux" || electron.safeStorage.getSelectedStorageBackend() !== "basic_text";
+ return process.platform !== "linux"
+ || electron.safeStorage.getSelectedStorageBackend() !== "basic_text";
}
export function isPassphraseSet(): boolean {
@@ -37,7 +38,9 @@ export function getBackupPassphraseStatus(): BackupPassphraseStatus {
return { available: isKeyringAvailable(), set: isPassphraseSet() };
}
-/** Stores a passphrase, replacing any existing one. Returns `false` when there is no keyring to use. */
+/**
+ * Stores a passphrase, replacing any existing one. Returns `false` when there is no keyring to use.
+ */
export async function storeBackupPassphrase(passphrase: string): Promise<boolean> {
if (!isKeyringAvailable() || !passphrase) {
return false;
@@ -70,9 +73,11 @@ export async function getBackupPassphrase(): Promise<string | null> {
}
try {
- const { result, shouldReEncrypt } = await electron.safeStorage.decryptStringAsync(fs.readFileSync(PASSPHRASE_PATH));
+ const stored = fs.readFileSync(PASSPHRASE_PATH);
+ const { result, shouldReEncrypt } = await electron.safeStorage.decryptStringAsync(stored);
- // The OS rotated its key underneath us; rewrite now or the blob eventually stops decrypting.
+ // The OS rotated its key underneath us; rewrite now or the blob eventually stops
+ // decrypting.
if (shouldReEncrypt) {
await storeBackupPassphrase(result);
}
@@ -80,7 +85,8 @@ export async function getBackupPassphrase(): Promise<string | null> {
return result;
} catch (e) {
// The reason reaches the log, the passphrase never does.
- getLog().error(`Could not read the stored backup passphrase: ${e instanceof Error ? e.message : String(e)}`);
+ const reason = e instanceof Error ? e.message : String(e);
+ getLog().error(`Could not read the stored backup passphrase: ${reason}`);
return null;
}
}
@@ -92,14 +98,17 @@ export async function getBackupPassphrase(): Promise<string | null> {
* the OS drew, which is the whole point: without the question, a script could quietly replace the
* passphrase with one it knows and every later backup would be encrypted to it.
*
- * Deliberately without the "don't ask again" escape the security settings offer. That exists there to
- * stop a script from fatiguing the user through repetition; here the question is rare enough that
- * being asked every time costs nothing, and skipping it is the whole vulnerability.
+ * Deliberately without the "don't ask again" escape the security settings offer. That exists there
+ * to stop a script from fatiguing the user through repetition; here the question is rare enough
+ * that being asked every time costs nothing, and skipping it is the whole vulnerability.
*/
async function confirmChange(action: "set" | "clear"): Promise<boolean> {
const { response } = await electron.dialog.showMessageBox({
type: "warning",
- buttons: [t("backup-password-dialog.cancel"), t(`backup-password-dialog.${action}-confirm`)],
+ buttons: [
+ t("backup-password-dialog.cancel"),
+ t(`backup-password-dialog.${action}-confirm`)
+ ],
defaultId: 1,
cancelId: 0,
title: t(`backup-password-dialog.${action}-title`),
@@ -111,26 +120,32 @@ async function confirmChange(action: "set" | "clear"): Promise<boolean> {
}
export function registerBackupPassphraseIpcHandlers(): void {
- electron.ipcMain.handle("backup-passphrase-status", (): BackupPassphraseStatus => getBackupPassphraseStatus());
+ electron.ipcMain.handle("backup-passphrase-status", handleStatus);
+ electron.ipcMain.handle("backup-passphrase-set", handleSet);
+ electron.ipcMain.handle("backup-passphrase-clear", handleClear);
+}
- electron.ipcMain.handle("backup-passphrase-set", async (_event, passphrase: string): Promise<BackupPassphraseChange> => {
- // Nothing to confirm when it could not be honoured anyway.
- if (!isKeyringAvailable() || !passphrase) {
- return "unavailable";
- }
- if (!await confirmChange("set")) {
- return "cancelled";
- }
+function handleStatus(): BackupPassphraseStatus {
+ return getBackupPassphraseStatus();
+}
- return await storeBackupPassphrase(passphrase) ? "applied" : "unavailable";
- });
+async function handleSet(_event: unknown, passphrase: string): Promise<BackupPassphraseChange> {
+ // Nothing to confirm when it could not be honoured anyway.
+ if (!isKeyringAvailable() || !passphrase) {
+ return "unavailable";
+ }
+ if (!await confirmChange("set")) {
+ return "cancelled";
+ }
- electron.ipcMain.handle("backup-passphrase-clear", async (): Promise<BackupPassphraseChange> => {
- if (!await confirmChange("clear")) {
- return "cancelled";
- }
- clearBackupPassphrase();
+ return await storeBackupPassphrase(passphrase) ? "applied" : "unavailable";
+}
- return "applied";
- });
+async function handleClear(): Promise<BackupPassphraseChange> {
+ if (!await confirmChange("clear")) {
+ return "cancelled";
+ }
+ clearBackupPassphrase();
+
+ return "applied";
}
diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.ts
index 338b96a610..fbe0d14c3e 100644
--- a/apps/server/src/backup_provider.spec.ts
+++ b/apps/server/src/backup_provider.spec.ts
@@ -23,8 +23,15 @@ async function writeStubDatabase(target: string) {
}
/** A desktop service (custom directory honoured) reading the given option value. */
-function desktopService(customDbBackupDir: string | null, extraOptions: OptionOverrides = {}, config: Partial<ServerBackupConfig> = {}) {
- return new ServerBackupService(optionsWith(customDbBackupDir, extraOptions), { allowCustomDirectory: true, ...config });
+function desktopService(
+ customDbBackupDir: string | null,
+ extraOptions: OptionOverrides = {},
+ config: Partial<ServerBackupConfig> = {}
+) {
+ return new ServerBackupService(
+ optionsWith(customDbBackupDir, extraOptions),
+ { allowCustomDirectory: true, ...config }
+ );
}
/** A server service, which ignores the option entirely. */
@@ -35,7 +42,10 @@ function serverService(customDbBackupDir: string | null) {
type OptionOverrides = Partial<Record<OptionNames, string>>;
function optionsWith(customDbBackupDir: string | null, extraOptions: OptionOverrides = {}) {
- const values: Partial<Record<OptionNames, string | null>> = { customDbBackupDir, ...extraOptions };
+ const values: Partial<Record<OptionNames, string | null>> = {
+ customDbBackupDir,
+ ...extraOptions
+ };
return {
getOption: (name: OptionNames) => values[name] ?? "",
@@ -135,7 +145,9 @@ describe("ServerBackupService: backup format", () => {
}
it("writes a plain database when neither compression nor encryption is on", async () => {
- expect(await desktopService(CUSTOM_DIR).backupNow("now")).toBe(path.join(CUSTOM_DIR, "backup-now.db"));
+ const backupFile = await desktopService(CUSTOM_DIR).backupNow("now");
+
+ expect(backupFile).toBe(path.join(CUSTOM_DIR, "backup-now.db"));
expect(backupNamesIn(CUSTOM_DIR)).toEqual(["backup-now.db"]);
});
@@ -149,17 +161,26 @@ describe("ServerBackupService: backup format", () => {
});
it("writes an encrypted container, which only the passphrase opens", async () => {
- const service = desktopService(CUSTOM_DIR, { backupEnableEncryption: "true" }, withPassphrase);
+ const service = desktopService(
+ CUSTOM_DIR,
+ { backupEnableEncryption: "true" },
+ withPassphrase
+ );
const backupFile = await service.backupNow("now");
expect(backupFile).toBe(path.join(CUSTOM_DIR, "backup-now.tnbackup"));
expect(await unwrap(backupFile, PASSPHRASE)).toBe("db-bytes");
- await expect(unwrap(backupFile, "wrong")).rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });
+ await expect(unwrap(backupFile, "wrong"))
+ .rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });
});
it("compresses and encrypts together when both are on", async () => {
- const service = desktopService(CUSTOM_DIR, { backupEnableCompression: "true", backupEnableEncryption: "true" }, withPassphrase);
+ const service = desktopService(
+ CUSTOM_DIR,
+ { backupEnableCompression: "true", backupEnableEncryption: "true" },
+ withPassphrase
+ );
const backupFile = await service.backupNow("now");
@@ -180,15 +201,23 @@ describe("ServerBackupService: backup format", () => {
it("leaves no snapshot behind in the data directory", async () => {
await desktopService(CUSTOM_DIR, { backupEnableCompression: "true" }).backupNow("now");
- expect(fs.readdirSync(dataDir.TMP_DIR).filter((name) => name.includes("snapshot"))).toEqual([]);
+ const left = fs.readdirSync(dataDir.TMP_DIR);
+ const snapshots = left.filter((name) => name.includes("snapshot"));
+
+ expect(snapshots).toEqual([]);
});
- it("cleans up after a failure, leaving neither a snapshot nor a partial container", async () => {
+ it("cleans up after a failure, leaving no snapshot and no partial container", async () => {
copyDatabase.mockRejectedValue(new Error("EIO: i/o error"));
- await expect(desktopService("", { backupEnableCompression: "true" }).backupNow("now")).rejects.toThrow("EIO");
+ const backup = desktopService("", { backupEnableCompression: "true" }).backupNow("now");
+
+ await expect(backup).rejects.toThrow("EIO");
+
+ const left = fs.readdirSync(dataDir.TMP_DIR);
+ const snapshots = left.filter((name) => name.includes("snapshot"));
- expect(fs.readdirSync(dataDir.TMP_DIR).filter((name) => name.includes("snapshot"))).toEqual([]);
+ expect(snapshots).toEqual([]);
expect(backupNamesIn(DEFAULT_DIR)).toEqual([]);
});
@@ -198,19 +227,31 @@ describe("ServerBackupService: backup format", () => {
const backups = await desktopService("").getExistingBackups();
- expect(backups.map((b) => b.fileName).sort()).toEqual(["backup-daily.tnbackup", "backup-weekly.db"]);
+ 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");
+ const encrypting = desktopService("", { backupEnableEncryption: "true" }, withPassphrase);
+ await encrypting.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]));
+ const listed = await desktopService("").getExistingBackups();
+ const byName = new Map(listed.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 });
+ 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");
@@ -218,7 +259,10 @@ describe("ServerBackupService: backup format", () => {
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");
+ fs.writeFileSync(
+ path.join(DEFAULT_DIR, "backup-damaged.tnbackup"),
+ "not a container at all"
+ );
const backups = await desktopService("").getExistingBackups();
@@ -232,21 +276,33 @@ describe("ServerBackupService: when the backup passphrase cannot be read", () =>
const noPassphrase: Partial<ServerBackupConfig> = { getPassphrase: async () => null };
it("keeps the unencrypted backup out of the chosen directory and says so", async () => {
- const service = desktopService(CUSTOM_DIR, { backupEnableEncryption: "true" }, noPassphrase);
+ const service = desktopService(
+ CUSTOM_DIR,
+ { backupEnableEncryption: "true" },
+ noPassphrase
+ );
const backupFile = await service.backupNow("daily");
// The chosen directory is typically a synced folder, which is what encryption was avoiding.
- // With nothing left to wrap, the backup is a plain database again rather than an empty container.
+ // With nothing left to wrap, the backup is a plain database again rather than an empty
+ // container.
expect(backupFile).toBe(path.join(DEFAULT_DIR, "backup-daily.db"));
expect(backupNamesIn(CUSTOM_DIR)).toEqual([]);
expect(ws.sendMessageToAllClients).toHaveBeenCalledWith(
- expect.objectContaining({ type: "toast", message: expect.stringContaining("not encrypted") })
+ expect.objectContaining(
+ { type: "toast",
+ message: expect.stringContaining("not encrypted") }
+ )
);
});
- it("still honours compression, so the backup is only missing what could not be done", async () => {
- const service = desktopService(CUSTOM_DIR, { backupEnableCompression: "true", backupEnableEncryption: "true" }, noPassphrase);
+ it("still honours compression, so only what could not be done is missing", async () => {
+ const service = desktopService(
+ CUSTOM_DIR,
+ { backupEnableCompression: "true", backupEnableEncryption: "true" },
+ noPassphrase
+ );
const backupFile = await service.backupNow("daily");
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.ts
index a9d7d24353..e1e2829584 100644
--- a/apps/server/src/backup_provider.ts
+++ b/apps/server/src/backup_provider.ts
@@ -1,4 +1,8 @@
-import { FIXED_HEADER_BYTES, peekBackupContainer, 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";
@@ -9,7 +13,9 @@ import path from "path";
import dataDir from "./services/data_dir.js";
import sql from "./services/sql.js";
-/** Backups that are compressed, encrypted or both are containers rather than plain database copies. */
+/**
+ * Backups that are compressed, encrypted or both are containers rather than plain database copies.
+ */
const CONTAINER_EXTENSION = ".tnbackup";
const DATABASE_EXTENSION = ".db";
@@ -21,8 +27,8 @@ export interface ServerBackupConfig {
*/
allowCustomDirectory?: boolean;
/**
- * Reads the stored backup passphrase, or `null` when there is none to be had. Set by the desktop
- * application, which is the only one with an OS keyring to keep a passphrase in.
+ * Reads the stored backup passphrase, or `null` when there is none to be had. Set by the
+ * desktop application, which is the only one with an OS keyring to keep a passphrase in.
*/
getPassphrase?: () => Promise<string | null>;
}
@@ -32,9 +38,10 @@ interface BackupFormat {
compress: boolean;
passphrase: string | null;
/**
- * Set when encryption was asked for and could not be delivered. The backup is still worth having,
- * but it must stay in the default directory: the chosen one is typically a synced folder, and
- * putting an unencrypted database there is the very thing encryption was turned on to avoid.
+ * Set when encryption was asked for and could not be delivered. The backup is still worth
+ * having, but it must stay in the default directory: the chosen one is typically a synced
+ * folder, and putting an unencrypted database there is the very thing encryption was turned on
+ * to avoid.
*/
keepLocal: boolean;
}
@@ -111,12 +118,13 @@ export default class ServerBackupService extends BackupService {
}
/**
- * Settles what the backup is written as. Compression alone needs nothing but the option; encryption
- * also needs a passphrase, and where that cannot be read the backup falls back to being unencrypted
- * and local rather than not being taken at all.
+ * Settles what the backup is written as. Compression alone needs nothing but the option;
+ * encryption also needs a passphrase, and where that cannot be read the backup falls back to
+ * being unencrypted and local rather than not being taken at all.
*/
private async resolveFormat(): Promise<BackupFormat> {
- // Read leniently: the pre-migration backup runs before the options added by newer versions exist.
+ // Read leniently: the pre-migration backup runs before the options added by newer versions
+ // exist.
const isEnabled = (name: "backupEnableCompression" | "backupEnableEncryption") =>
this.options.getOptionOrNull(name) === "true";
@@ -130,7 +138,8 @@ export default class ServerBackupService extends BackupService {
return { compress, passphrase, keepLocal: false };
}
- getLog().error("Could not read the backup passphrase; backing up unencrypted to the default location.");
+ getLog().error("Could not read the backup passphrase; backing up unencrypted to the "
+ + "default location.");
ws.sendMessageToAllClients({
type: "toast",
message: t("backup.passphrase_unavailable"),
@@ -189,9 +198,10 @@ function listBackupsIn(directory: string): DatabaseBackup[] {
}
return fileNames
- // The extension check excludes intermediate files (e.g. *.db-journal, *.part) created while a
- // backup is in progress.
- .filter((fileName) => fileName.includes("backup") && (fileName.endsWith(DATABASE_EXTENSION) || fileName.endsWith(CONTAINER_EXTENSION)))
+ // The extension check excludes intermediate files (e.g. *.db-journal, *.part) created while
+ // a backup is in progress.
+ .filter((fileName) => fileName.includes("backup")
+ && (fileName.endsWith(DATABASE_EXTENSION) || fileName.endsWith(CONTAINER_EXTENSION)))
.flatMap((fileName) => {
const filePath = path.resolve(directory, fileName);
const stat = fs.statSync(filePath, { throwIfNoEntry: false });
@@ -199,13 +209,19 @@ function listBackupsIn(directory: string): DatabaseBackup[] {
return [];
}
- return [{ fileName, filePath, mtime: stat.mtime, fileSize: stat.size, ...describeContainer(filePath, fileName) }];
+ 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.
+ * 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.
@@ -241,7 +257,12 @@ function describeContainer(filePath: string, fileName: string): Partial<Database
};
}
-async function writeBackup(directory: string, baseName: string, format: BackupFormat, location: "default" | "custom"): Promise<string> {
+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}`;
const backupFile = path.resolve(directory, fileName);
@@ -262,8 +283,10 @@ async function writeBackup(directory: string, baseName: string, format: BackupFo
throw new Error(withoutDirectory(e, directory));
}
- // One backup name, one file: a container retires the plain copy it replaces, and the other way round.
- fs.rmSync(path.resolve(directory, `${baseName}${isContainer ? DATABASE_EXTENSION : CONTAINER_EXTENSION}`), { force: true });
+ // One backup name, one file: a container retires the plain copy it replaces, and the other way
+ // round.
+ const counterpart = `${baseName}${isContainer ? DATABASE_EXTENSION : CONTAINER_EXTENSION}`;
+ fs.rmSync(path.resolve(directory, counterpart), { force: true });
getLog().info(`Created backup .${path.sep}${fileName}${location === "custom" ? " in the custom backup location." : ""}`);
@@ -277,7 +300,11 @@ async function writeBackup(directory: string, baseName: string, format: BackupFo
* before it can be fed to the writer. It lands in the data directory's temp folder and is deleted
* straight after, so the backup directory never holds a plain database even for a moment.
*/
-async function writeContainer(backupFile: string, baseName: string, format: BackupFormat): Promise<void> {
+async function writeContainer(
+ backupFile: string,
+ baseName: string,
+ format: BackupFormat
+): Promise<void> {
const snapshot = path.resolve(dataDir.TMP_DIR, `${baseName}.snapshot.db`);
const partial = `${backupFile}.part`;
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 20d90814b7..bfab04bf31 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -513,23 +513,25 @@ export type BackupPassphraseChange =
| "unavailable";
/**
- * The backup passphrase, kept encrypted by the OS keyring in a file outside the database (the database
- * is what ends up inside the backup, so a passphrase stored there would ride along inside the very
- * container it protects).
+ * The backup passphrase, kept encrypted by the OS keyring in a file outside the database (the
+ * database is what ends up inside the backup, so a passphrase stored there would ride along inside
+ * the very container it protects).
*
* Deliberately write-only: there is no way to read the passphrase back, so a frontend script cannot
* exfiltrate it. Only the main process ever sees the plaintext again, when it writes a backup.
*
* Both changes are also gated on a native OS confirmation, which a script can request but cannot
- * answer. Without that, a script could quietly swap in a passphrase of its own and every later backup
- * would be encrypted to it.
+ * answer. Without that, a script could quietly swap in a passphrase of its own and every later
+ * backup would be encrypted to it.
*/
export interface ElectronBackupPassphraseApi {
/** Whether a passphrase can be stored on this system, and whether one already is. */
getStatus(): Promise<BackupPassphraseStatus>;
/** Stores a passphrase, replacing any existing one, once the user has confirmed it. */
set(passphrase: string): Promise<BackupPassphraseChange>;
- /** Forgets the stored passphrase. Existing backups keep the passphrase they were written with. */
+ /**
+ * Forgets the stored passphrase. Existing backups keep the passphrase they were written with.
+ */
clear(): Promise<BackupPassphraseChange>;
}
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index 278e13e9a1..db1e8538d6 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -192,13 +192,14 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
weeklyBackupEnabled: boolean;
monthlyBackupEnabled: boolean;
/**
- * Whether backups are gzip-compressed. Compression or encryption switches the backup from a plain
- * database file to a backup container; with both off, backups stay plain `.db` copies.
+ * Whether backups are gzip-compressed. Compression or encryption switches the backup from a
+ * plain database file to a backup container; with both off, backups stay plain `.db` copies.
*/
backupEnableCompression: boolean;
/**
- * Whether backups are encrypted with the stored backup passphrase. Desktop only, and only where the
- * OS offers a keyring to keep that passphrase in, since unattended backups cannot ask for it.
+ * Whether backups are encrypted with the stored backup passphrase. Desktop only, and only where
+ * the OS offers a keyring to keep that passphrase in, since unattended backups cannot ask for
+ * it.
*/
backupEnableEncryption: boolean;
compressImages: boolean;
diff --git a/packages/trilium-backup-container/src/byte-reader.ts b/packages/trilium-backup-container/src/byte-reader.ts
index ddb3260796..1ebadab54f 100644
--- a/packages/trilium-backup-container/src/byte-reader.ts
+++ b/packages/trilium-backup-container/src/byte-reader.ts
@@ -24,7 +24,11 @@ export class ByteReader {
await this.#buffer(count);
if (this.#pendingBytes < count) {
- throw new BackupContainerError("truncated", `Expected ${count} bytes at offset ${this.#consumed}, found ${this.#pendingBytes}.`);
+ throw new BackupContainerError(
+ "truncated",
+ `Expected ${count} bytes at offset ${this.#consumed},
+ found ${this.#pendingBytes}.`
+ );
}
return this.#take(count);
@@ -60,7 +64,10 @@ export class ByteReader {
return Buffer.alloc(0);
}
- const merged = this.#pending.length === 1 ? this.#pending[0] : Buffer.concat(this.#pending, this.#pendingBytes);
+ const merged = this.#pending.length === 1 ? this.#pending[0] : Buffer.concat(
+ this.#pending,
+ this.#pendingBytes
+ );
const taken = merged.subarray(0, count);
const rest = merged.subarray(count);
diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.ts
index a06e33c7b2..1fa2720718 100644
--- a/packages/trilium-backup-container/src/container.spec.ts
+++ b/packages/trilium-backup-container/src/container.spec.ts
@@ -14,6 +14,7 @@ import { peekBackupContainer, readBackupContainer } from "./read.js";
import {
chunked,
fakeDatabase,
+ failureOf,
FAST_SCRYPT,
flipByte,
MemorySink,
@@ -24,6 +25,7 @@ import {
import { writeBackupContainer, type WriteBackupContainerOptions } from "./write.js";
type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;
+type PeekCase = [string, WriteOptions, { compressed: boolean; encrypted: boolean }];
const PASSPHRASE = "correct horse battery staple";
const FRAME_OVERHEAD = 4 + TAG_BYTES;
@@ -33,13 +35,20 @@ describe("round trip", () => {
["plain", {}, HEADER_BYTES_PLAIN],
["compressed", { compress: true }, HEADER_BYTES_PLAIN],
["encrypted", { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }, HEADER_BYTES_ENCRYPTED],
- ["compressed and encrypted", { compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }, HEADER_BYTES_ENCRYPTED]
+ [
+ "compressed and encrypted",
+ { compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },
+ HEADER_BYTES_ENCRYPTED
+ ]
];
it.each(cases)("wraps and unwraps a %s container", async (_label, options, headerLength) => {
const database = fakeDatabase(64 * 1024);
- const written = await writeToBuffer(database, { ...options, plaintextSize: database.length });
+ const written = await writeToBuffer(
+ database,
+ { ...options, plaintextSize: database.length }
+ );
expect(written.result.headerLength).toBe(headerLength);
expect(written.patchedAt).toEqual([headerLength - 32]);
@@ -67,10 +76,16 @@ describe("round trip", () => {
});
it("wraps an empty payload as a single empty final frame", async () => {
- const written = await writeToBuffer(Buffer.alloc(0), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ Buffer.alloc(0),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + FRAME_OVERHEAD);
- const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE, requireSqliteHeader: false });
+ const read = await readFromBuffer(
+ written.bytes,
+ { passphrase: PASSPHRASE, requireSqliteHeader: false }
+ );
expect(read.result.bytesWritten).toBe(0);
});
@@ -86,7 +101,10 @@ describe("round trip", () => {
describe("payload digest", () => {
it("is the SHA-256 of the payload as stored, patched in after the payload", async () => {
- const written = await writeToBuffer(fakeDatabase(20_000), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ fakeDatabase(20_000),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
const payload = written.bytes.subarray(HEADER_BYTES_ENCRYPTED);
const stored = written.bytes.subarray(HEADER_BYTES_ENCRYPTED - 32, HEADER_BYTES_ENCRYPTED);
@@ -100,7 +118,7 @@ describe("payload digest", () => {
const written = await writeToBuffer(fakeDatabase(4096));
const damaged = flipByte(written.bytes, written.bytes.length - 5);
- expect(await reasonOf(readFromBuffer(damaged))).toBe("digest-mismatch");
+ expect(await failureOf(damaged)).toBe("digest-mismatch");
});
});
@@ -119,9 +137,12 @@ describe("gzip payload", () => {
});
describe("canonical framing", () => {
- it("ends a payload that is an exact multiple of the frame size with an empty final frame", async () => {
+ it("ends a payload that is an exact multiple of the frame size emptily", async () => {
const database = fakeDatabase(2 * FRAME_SIZE);
- const written = await writeToBuffer(database, { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ database,
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
const fullFrames = 2 * (FRAME_SIZE + FRAME_OVERHEAD);
expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + fullFrames + FRAME_OVERHEAD);
@@ -132,7 +153,10 @@ describe("canonical framing", () => {
it("ends a partial payload with a short final frame", async () => {
const database = fakeDatabase(FRAME_SIZE + 1_000);
- const written = await writeToBuffer(database, { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ database,
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
expect(written.bytes).toHaveLength(
HEADER_BYTES_ENCRYPTED + (FRAME_SIZE + FRAME_OVERHEAD) + (1_000 + FRAME_OVERHEAD)
@@ -142,16 +166,22 @@ describe("canonical framing", () => {
describe("passphrase handling", () => {
it("rejects the wrong passphrase before reading any frame", async () => {
- const written = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
- expect(await reasonOf(readFromBuffer(written.bytes, { passphrase: "wrong" })))
+ expect(await failureOf(written.bytes, { passphrase: "wrong" }))
.toBe("wrong-passphrase-or-damaged-header");
});
it("reports a missing passphrase separately", async () => {
- const written = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
- expect(await reasonOf(readFromBuffer(written.bytes))).toBe("passphrase-required");
+ expect(await failureOf(written.bytes)).toBe("passphrase-required");
});
it("normalises to NFC, so a decomposed and a composed passphrase agree", async () => {
@@ -159,32 +189,47 @@ describe("passphrase handling", () => {
const composed = "café secret"; // precomposed e-acute
expect(decomposed).not.toBe(composed);
- const written = await writeToBuffer(fakeDatabase(), { passphrase: decomposed, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: decomposed, scrypt: FAST_SCRYPT }
+ );
const read = await readFromBuffer(written.bytes, { passphrase: composed });
expect(read.result.bytesWritten).toBe(4096);
});
it("uses a fresh salt and nonce prefix per file", async () => {
- const first = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
- const second = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const first = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
+ const second = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
expect(first.bytes.subarray(36, 60).equals(second.bytes.subarray(36, 60))).toBe(false);
});
});
describe("damage and tampering", () => {
- const encrypted = () => writeToBuffer(fakeDatabase(2 * FRAME_SIZE), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const encrypted = () => writeToBuffer(
+ fakeDatabase(2 * FRAME_SIZE),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
it("recovers when only the verifier tag is damaged", async () => {
const written = await encrypted();
const damaged = flipByte(written.bytes, 65); // inside the verifier tag, bytes 60 to 75
- expect(await reasonOf(readFromBuffer(damaged, { passphrase: PASSPHRASE })))
+ expect(await failureOf(damaged, { passphrase: PASSPHRASE }))
.toBe("wrong-passphrase-or-damaged-header");
// The tag sits outside the authenticated header, so the frames are still intact.
- const recovered = await readFromBuffer(damaged, { passphrase: PASSPHRASE, skipVerifier: true });
+ const recovered = await readFromBuffer(
+ damaged,
+ { passphrase: PASSPHRASE, skipVerifier: true }
+ );
expect(recovered.bytes.equals(fakeDatabase(2 * FRAME_SIZE))).toBe(true);
});
@@ -192,29 +237,33 @@ describe("damage and tampering", () => {
const written = await encrypted();
const damaged = flipByte(written.bytes, 40);
- expect(await reasonOf(readFromBuffer(damaged, { passphrase: PASSPHRASE, skipVerifier: true })))
- .toBe("damaged-payload");
+ const reason = await failureOf(damaged, { passphrase: PASSPHRASE, skipVerifier: true });
+
+ expect(reason).toBe("damaged-payload");
});
it("rejects a flipped bit inside a frame", async () => {
const written = await encrypted();
const damaged = flipByte(written.bytes, HEADER_BYTES_ENCRYPTED + 500);
- expect(await reasonOf(readFromBuffer(damaged, { passphrase: PASSPHRASE }))).toBe("damaged-payload");
+ const reason = await failureOf(damaged, { passphrase: PASSPHRASE });
+
+ expect(reason).toBe("damaged-payload");
});
it("rejects bytes appended after the final frame", async () => {
const written = await encrypted();
const extended = Buffer.concat([written.bytes, Buffer.from("extra")]);
- expect(await reasonOf(readFromBuffer(extended, { passphrase: PASSPHRASE }))).toBe("trailing-data");
+ expect(await failureOf(extended, { passphrase: PASSPHRASE })).toBe("trailing-data");
});
it("rejects a truncated container", async () => {
const written = await encrypted();
- expect(await reasonOf(readFromBuffer(written.bytes.subarray(0, written.bytes.length - 10), { passphrase: PASSPHRASE })))
- .toBe("truncated");
+ const cut = written.bytes.subarray(0, written.bytes.length - 10);
+
+ expect(await failureOf(cut, { passphrase: PASSPHRASE })).toBe("truncated");
});
it("rejects a non-final frame that is not exactly one frame long", async () => {
@@ -222,22 +271,26 @@ describe("damage and tampering", () => {
const tampered = Buffer.from(written.bytes);
tampered.writeUInt32LE(5, HEADER_BYTES_ENCRYPTED);
- expect(await reasonOf(readFromBuffer(tampered, { passphrase: PASSPHRASE }))).toBe("invalid-frame-length");
+ expect(await failureOf(tampered, { passphrase: PASSPHRASE })).toBe("invalid-frame-length");
});
it("rejects an oversized frame length before reading that many bytes", async () => {
- const written = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
const tampered = Buffer.from(written.bytes);
- tampered.writeUInt32LE(0xffffffff, HEADER_BYTES_ENCRYPTED); // final flag plus a 2 GiB claim
+ // The final flag plus a 2 GiB claim.
+ tampered.writeUInt32LE(0xffffffff, HEADER_BYTES_ENCRYPTED);
- expect(await reasonOf(readFromBuffer(tampered, { passphrase: PASSPHRASE }))).toBe("invalid-frame-length");
+ expect(await failureOf(tampered, { passphrase: PASSPHRASE })).toBe("invalid-frame-length");
});
it("rejects a damaged compressed payload", async () => {
const written = await writeToBuffer(fakeDatabase(50_000), { compress: true });
const damaged = flipByte(written.bytes, HEADER_BYTES_PLAIN + 40);
- expect(["damaged-payload", "digest-mismatch"]).toContain(await reasonOf(readFromBuffer(damaged)));
+ expect(["damaged-payload", "digest-mismatch"]).toContain(await failureOf(damaged));
});
});
@@ -245,11 +298,26 @@ 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) => {
+ [
+ "encrypted",
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },
+ { compressed: false, encrypted: true }
+ ],
+ [
+ "both",
+ { compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },
+ { compressed: true, encrypted: true }
+ ]
+ ] as PeekCase[])("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 });
+ 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({
@@ -289,18 +357,22 @@ describe("input that is not a container", () => {
it.each([
["random bytes", Buffer.alloc(300, 9), "not-a-container"],
["an empty file, which identifies itself as nothing", Buffer.alloc(0), "not-a-container"],
- ["a short file whose bytes are not the start of the magic", Buffer.from("Trillium"), "not-a-container"]
+ [
+ "a short file whose bytes are not the start of the magic",
+ Buffer.from("Trillium"),
+ "not-a-container"
+ ]
])("rejects %s", async (_label, bytes, reason) => {
- expect(await reasonOf(readFromBuffer(bytes))).toBe(reason);
+ expect(await failureOf(bytes)).toBe(reason);
});
it("reports a container cut off inside its header as truncated", async () => {
const written = await writeToBuffer(fakeDatabase());
// A valid prefix of the magic is ambiguous, and a cut-off container is the useful reading.
- expect(await reasonOf(readFromBuffer(Buffer.from("Tril")))).toBe("truncated");
- expect(await reasonOf(readFromBuffer(written.bytes.subarray(0, 24)))).toBe("truncated");
- expect(await reasonOf(readFromBuffer(written.bytes.subarray(0, 40)))).toBe("truncated");
+ expect(await failureOf(Buffer.from("Tril"))).toBe("truncated");
+ expect(await failureOf(written.bytes.subarray(0, 24))).toBe("truncated");
+ expect(await failureOf(written.bytes.subarray(0, 40))).toBe("truncated");
});
});
@@ -308,16 +380,19 @@ describe("output bounds", () => {
it("stops output that would exceed the ceiling", async () => {
const written = await writeToBuffer(fakeDatabase(64 * 1024), { compress: true });
- expect(await reasonOf(readFromBuffer(written.bytes, { maxOutputBytes: 1_000 }))).toBe("output-too-large");
+ expect(await failureOf(written.bytes, { maxOutputBytes: 1_000 })).toBe("output-too-large");
});
it("lets a recorded plaintext size tighten the ceiling", async () => {
const database = fakeDatabase(64 * 1024);
- const written = await writeToBuffer(database, { compress: true, plaintextSize: database.length });
+ const written = await writeToBuffer(
+ database,
+ { compress: true, plaintextSize: database.length }
+ );
const tightened = Buffer.from(written.bytes);
tightened.writeBigUInt64LE(1_000n, 24);
- expect(await reasonOf(readFromBuffer(tightened))).toBe("output-too-large");
+ expect(await failureOf(tightened)).toBe("output-too-large");
});
it("never lets a crafted plaintext size widen the ceiling", async () => {
@@ -325,7 +400,7 @@ describe("output bounds", () => {
const crafted = Buffer.from(written.bytes);
crafted.writeBigUInt64LE(2n ** 63n, 24);
- expect(await reasonOf(readFromBuffer(crafted, { maxOutputBytes: 1_000 }))).toBe("output-too-large");
+ expect(await failureOf(crafted, { maxOutputBytes: 1_000 })).toBe("output-too-large");
});
it("rejects output whose length disagrees with the recorded size", async () => {
@@ -334,7 +409,7 @@ describe("output bounds", () => {
const lying = Buffer.from(written.bytes);
lying.writeBigUInt64LE(5_000n, 24);
- expect(await reasonOf(readFromBuffer(lying))).toBe("size-mismatch");
+ expect(await failureOf(lying)).toBe("size-mismatch");
});
});
@@ -342,14 +417,15 @@ describe("SQLite check", () => {
it("rejects a payload that is not a database, and can be told not to", async () => {
const written = await writeToBuffer(Buffer.from("this is not a database, it is a note"));
- expect(await reasonOf(readFromBuffer(written.bytes))).toBe("not-a-database");
- expect((await readFromBuffer(written.bytes, { requireSqliteHeader: false })).result.bytesWritten).toBe(36);
+ expect(await failureOf(written.bytes)).toBe("not-a-database");
+ const read = await readFromBuffer(written.bytes, { requireSqliteHeader: false });
+ expect(read.result.bytesWritten).toBe(36);
});
it("rejects output too short to hold a SQLite header", async () => {
const written = await writeToBuffer(Buffer.from("short"));
- expect(await reasonOf(readFromBuffer(written.bytes))).toBe("not-a-database");
+ expect(await failureOf(written.bytes)).toBe("not-a-database");
});
});
@@ -365,16 +441,27 @@ describe("option validation", () => {
it.each([
["a negative plaintext size", { plaintextSize: -1 }, "invalid-options"],
["a fractional plaintext size", { plaintextSize: 1.5 }, "invalid-options"],
- ["scrypt parameters out of bounds", { passphrase: PASSPHRASE, scrypt: { log2N: 30, r: 8, p: 1 } }, "invalid-kdf-params"],
- ["a scrypt cost above the writer ceiling", { passphrase: PASSPHRASE, maxKdfMemoryBytes: 1024 }, "invalid-kdf-params"]
+ [
+ "scrypt parameters out of bounds",
+ { passphrase: PASSPHRASE, scrypt: { log2N: 30, r: 8, p: 1 } },
+ "invalid-kdf-params"
+ ],
+ [
+ "a scrypt cost above the writer ceiling",
+ { passphrase: PASSPHRASE, maxKdfMemoryBytes: 1024 },
+ "invalid-kdf-params"
+ ]
])("rejects %s", async (_label, options, reason) => {
expect(await reasonOf(writeToBuffer(fakeDatabase(), options))).toBe(reason);
});
it("refuses a key derivation the reader considers too expensive", async () => {
- const written = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });
+ const written = await writeToBuffer(
+ fakeDatabase(),
+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }
+ );
- expect(await reasonOf(readFromBuffer(written.bytes, { passphrase: PASSPHRASE, maxKdfMemoryBytes: 1024 })))
+ expect(await failureOf(written.bytes, { passphrase: PASSPHRASE, maxKdfMemoryBytes: 1024 }))
.toBe("invalid-kdf-params");
});
});
@@ -385,7 +472,10 @@ describe("errors", () => {
await readFromBuffer(Buffer.alloc(300, 9));
expect.unreachable("should have thrown");
} catch (error) {
- expect(error).toMatchObject({ name: "BackupContainerError", reason: "not-a-container" });
+ expect(error).toMatchObject({
+ name: "BackupContainerError",
+ reason: "not-a-container"
+ });
expect((error as Error).message).toMatch(/container magic/);
}
});
@@ -393,8 +483,11 @@ describe("errors", () => {
it("lets a destination error through untranslated", async () => {
const written = await writeToBuffer(fakeDatabase());
const failing = new MemorySink();
- failing._write = (_chunk, _encoding, callback) => callback(new Error("ENOSPC: no space left on device"));
+ failing._write = (_chunk, _encoding, callback) =>
+ callback(new Error("ENOSPC: no space left on device"));
+
+ const read = readBackupContainer(Readable.from([written.bytes]), failing);
- await expect(readBackupContainer(Readable.from([written.bytes]), failing)).rejects.toThrow(/ENOSPC/);
+ await expect(read).rejects.toThrow(/ENOSPC/);
});
});
diff --git a/packages/trilium-backup-container/src/crypto.ts b/packages/trilium-backup-container/src/crypto.ts
index 98535afc8a..acc8bb3ff2 100644
--- a/packages/trilium-backup-container/src/crypto.ts
+++ b/packages/trilium-backup-container/src/crypto.ts
@@ -11,8 +11,8 @@ import {
} from "./format.js";
/**
- * OpenSSL needs a little more than the `128 * N * r` working set, so the ceiling handed to Node sits
- * above what {@link scryptMemoryBytes} reports. It is a limit, not an allocation.
+ * OpenSSL needs a little more than the `128 * N * r` working set, so the ceiling handed to Node
+ * sits above what {@link scryptMemoryBytes} reports. It is a limit, not an allocation.
*/
const MAXMEM_SLACK_BYTES = 1024 * 1024;
@@ -34,11 +34,21 @@ export function deriveKey(passphrase: string, salt: Buffer, params: ScryptParams
return new Promise((resolve, reject) => {
const fail = (error: Error) =>
- reject(new BackupContainerError("invalid-kdf-params", `Key derivation failed: ${error.message}`));
+ reject(new BackupContainerError(
+ "invalid-kdf-params",
+ `Key derivation failed: ${error.message}`
+ ));
- // scrypt rejects impossible parameters synchronously and everything else through the callback.
+ // scrypt rejects impossible parameters synchronously and everything else through the
+ // callback.
try {
- scrypt(secret, salt, KEY_BYTES, options, (error, key) => (error ? fail(error) : resolve(key)));
+ scrypt(
+ secret,
+ salt,
+ KEY_BYTES,
+ options,
+ (error, key) => (error ? fail(error) : resolve(key))
+ );
} catch (error) {
fail(error as Error);
}
@@ -46,7 +56,14 @@ export function deriveKey(passphrase: string, salt: Buffer, params: ScryptParams
}
/** Seals one frame, returning `length || ciphertext || tag` ready to be written. */
-export function sealFrame(key: Buffer, noncePrefix: Buffer, aad: Buffer, counter: number, lengthField: Buffer, plaintext: Buffer): Buffer {
+export function sealFrame(
+ key: Buffer,
+ noncePrefix: Buffer,
+ aad: Buffer,
+ counter: number,
+ lengthField: Buffer,
+ plaintext: Buffer
+): Buffer {
const cipher = createCipheriv("aes-256-gcm", key, nonceFor(noncePrefix, counter));
cipher.setAAD(Buffer.concat([aad, lengthField]));
@@ -56,7 +73,16 @@ export function sealFrame(key: Buffer, noncePrefix: Buffer, aad: Buffer, counter
}
/** Opens one frame, throwing `damaged-payload` when the tag does not match. */
-export function openFrame(key: Buffer, noncePrefix: Buffer, aad: Buffer, counter: number, lengthField: Buffer, ciphertext: Buffer, tag: Buffer, offset: number): Buffer {
+export function openFrame(
+ key: Buffer,
+ noncePrefix: Buffer,
+ aad: Buffer,
+ counter: number,
+ lengthField: Buffer,
+ ciphertext: Buffer,
+ tag: Buffer,
+ offset: number
+): Buffer {
const decipher = createDecipheriv("aes-256-gcm", key, nonceFor(noncePrefix, counter));
decipher.setAAD(Buffer.concat([aad, lengthField]));
decipher.setAuthTag(tag);
@@ -64,7 +90,10 @@ export function openFrame(key: Buffer, noncePrefix: Buffer, aad: Buffer, counter
try {
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
} catch {
- throw new BackupContainerError("damaged-payload", `Frame ${counter} failed authentication at byte offset ${offset}.`);
+ throw new BackupContainerError(
+ "damaged-payload",
+ `Frame ${counter} failed authentication at byte offset ${offset}.`
+ );
}
}
@@ -78,12 +107,18 @@ export function computeVerifierTag(key: Buffer, noncePrefix: Buffer, aad: Buffer
}
/**
- * Checks the verifier tag, which tells a wrong passphrase from a usable one before any frame is read.
+ * Checks the verifier tag, which tells a wrong passphrase from a usable one before any frame is
+ * read.
*
- * A mismatch cannot distinguish a wrong passphrase from a bit flip in the salt, nonce prefix or tag,
- * which is why the reason covers both.
+ * A mismatch cannot distinguish a wrong passphrase from a bit flip in the salt, nonce prefix or
+ * tag, which is why the reason covers both.
*/
-export function verifyPassphrase(key: Buffer, noncePrefix: Buffer, aad: Buffer, expectedTag: Buffer): void {
+export function verifyPassphrase(
+ key: Buffer,
+ noncePrefix: Buffer,
+ aad: Buffer,
+ expectedTag: Buffer
+): void {
const decipher = createDecipheriv("aes-256-gcm", key, nonceFor(noncePrefix, VERIFIER_COUNTER));
decipher.setAAD(aad);
decipher.setAuthTag(expectedTag.subarray(0, TAG_BYTES));
@@ -91,6 +126,9 @@ export function verifyPassphrase(key: Buffer, noncePrefix: Buffer, aad: Buffer,
try {
decipher.final();
} catch {
- throw new BackupContainerError("wrong-passphrase-or-damaged-header", "Verifier tag did not match.");
+ throw new BackupContainerError(
+ "wrong-passphrase-or-damaged-header",
+ "Verifier tag did not match."
+ );
}
}
diff --git a/packages/trilium-backup-container/src/errors.ts b/packages/trilium-backup-container/src/errors.ts
index 4d987c9ecf..ff5d055d78 100644
--- a/packages/trilium-backup-container/src/errors.ts
+++ b/packages/trilium-backup-container/src/errors.ts
@@ -1,8 +1,8 @@
/**
* Machine-readable cause of a container failure.
*
- * The human-readable message on the error is fixed English meant for logs. Anything user-facing must
- * be selected from this reason instead, so that the module carries no translations.
+ * The human-readable message on the error is fixed English meant for logs. Anything user-facing
+ * must be selected from this reason instead, so that the module carries no translations.
*/
export type BackupContainerErrorReason =
/** The first bytes are not the container magic, i.e. this is not a backup container at all. */
@@ -11,7 +11,10 @@ export type BackupContainerErrorReason =
| "unsupported-version"
/** A reserved flag bit is set, or the flags are otherwise not understood. */
| "unsupported-flags"
- /** The header length is not the value this version and these flags require, or it is out of range. */
+ /**
+ * The header length is not the value this version and these flags require, or it is out of
+ * range.
+ */
| "invalid-header-length"
/** The key derivation function id is not one this reader implements. */
| "unsupported-kdf"
diff --git a/packages/trilium-backup-container/src/file-destination.spec.ts b/packages/trilium-backup-container/src/file-destination.spec.ts
index d4322d03a3..8b28fab12c 100644
--- a/packages/trilium-backup-container/src/file-destination.spec.ts
+++ b/packages/trilium-backup-container/src/file-destination.spec.ts
@@ -28,7 +28,8 @@ describe("file destination", () => {
const restored = join(directory, "restored.db");
await writeFile(source, database);
- const result = await writeBackupContainer(createReadStream(source), createWriteStream(partial), {
+ const output = createWriteStream(partial);
+ const result = await writeBackupContainer(createReadStream(source), output, {
compress: true,
passphrase: "file test",
scrypt: FAST_SCRYPT,
@@ -49,11 +50,16 @@ describe("file destination", () => {
await rename(partial, container);
expect((await stat(container)).size).toBeLessThan(database.length);
- const info = await readBackupContainer(createReadStream(container), createWriteStream(restored), {
+ const restoredOutput = createWriteStream(restored);
+ const info = await readBackupContainer(createReadStream(container), restoredOutput, {
passphrase: "file test"
});
- expect(info).toMatchObject({ compressed: true, encrypted: true, bytesWritten: database.length });
+ expect(info).toMatchObject({
+ compressed: true,
+ encrypted: true,
+ bytesWritten: database.length
+ });
expect((await readFile(restored)).equals(database)).toBe(true);
});
});
diff --git a/packages/trilium-backup-container/src/format.spec.ts b/packages/trilium-backup-container/src/format.spec.ts
index 25ef1ff510..5bac177f11 100644
--- a/packages/trilium-backup-container/src/format.spec.ts
+++ b/packages/trilium-backup-container/src/format.spec.ts
@@ -66,7 +66,12 @@ describe("header layout", () => {
expect(digestOffset(64)).toBe(32);
const decoded = decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES);
- expect(decoded).toMatchObject({ version: 1, compressed: true, encrypted: false, plaintextSize: 4096 });
+ expect(decoded).toMatchObject({
+ version: 1,
+ compressed: true,
+ encrypted: false,
+ plaintextSize: 4096
+ });
expect(decoded.encryption).toBeNull();
expect(decoded.digest.equals(Buffer.alloc(32, 7))).toBe(true);
});
@@ -114,11 +119,23 @@ describe("fixed header validation", () => {
};
it.each([
- ["magic mismatch", (bytes: Buffer) => bytes.write("Trillium Notes Bckp!", 0, "ascii"), "not-a-container"],
+ [
+ "magic mismatch",
+ (bytes: Buffer) => bytes.write("Trillium Notes Bckp!", 0, "ascii"),
+ "not-a-container"
+ ],
["version 0", (bytes: Buffer) => bytes.writeUInt8(0, 20), "unsupported-version"],
["a newer version", (bytes: Buffer) => bytes.writeUInt8(2, 20), "unsupported-version"],
- ["a reserved flag bit", (bytes: Buffer) => bytes.writeUInt8(0b100, 21), "unsupported-flags"],
- ["a header length that does not match the flags", (bytes: Buffer) => bytes.writeUInt16LE(65, 22), "invalid-header-length"]
+ [
+ "a reserved flag bit",
+ (bytes: Buffer) => bytes.writeUInt8(0b100, 21),
+ "unsupported-flags"
+ ],
+ [
+ "a header length that does not match the flags",
+ (bytes: Buffer) => bytes.writeUInt16LE(65, 22),
+ "invalid-header-length"
+ ]
])("rejects %s", (_label, mutate, reason) => {
expect(decode(mutate)).toThrow(expect.objectContaining({ reason }) as Error);
});
@@ -130,8 +147,14 @@ describe("fixed header validation", () => {
});
it("accepts the exact length each flag combination requires", () => {
- expect(decodeFixedHeader(encodeHeader(plainHeader()).subarray(0, 32), DEFAULT_MAX_HEADER_BYTES).headerLength).toBe(64);
- expect(decodeFixedHeader(encodeHeader(encryptedHeader()).subarray(0, 32), DEFAULT_MAX_HEADER_BYTES).headerLength).toBe(108);
+ const lengthOf = (header: ContainerHeader) =>
+ decodeFixedHeader(
+ encodeHeader(header).subarray(0, 32),
+ DEFAULT_MAX_HEADER_BYTES
+ ).headerLength;
+
+ expect(lengthOf(plainHeader())).toBe(64);
+ expect(lengthOf(encryptedHeader())).toBe(108);
});
it("rejects a KDF id it does not implement", () => {
@@ -162,7 +185,10 @@ describe("scrypt parameter bounds", () => {
});
it("rejects a cost above the memory ceiling even when every field is in range", () => {
- expect(() => validateScryptParams({ log2N: 20, r: 16, p: 1 }, 64 * 1024 * 1024)).toThrow(BackupContainerError);
+ const ceiling = 64 * 1024 * 1024;
+ const tooExpensive = () => validateScryptParams({ log2N: 20, r: 16, p: 1 }, ceiling);
+
+ expect(tooExpensive).toThrow(BackupContainerError);
expect(() => validateScryptParams({ log2N: 17, r: 8, p: 1 }, 134217728)).not.toThrow();
});
});
@@ -181,7 +207,8 @@ describe("SQLite header check", () => {
["output that is too short", sqliteHead(4096).subarray(0, 17)],
["a foreign magic", Buffer.concat([Buffer.from("Not a database!!"), Buffer.alloc(2)])]
])("rejects %s", (_label, head) => {
- expect(() => validateSqliteHeader(head)).toThrow(expect.objectContaining({ reason: "not-a-database" }) as Error);
+ expect(() => validateSqliteHeader(head))
+ .toThrow(expect.objectContaining({ reason: "not-a-database" }) as Error);
});
});
diff --git a/packages/trilium-backup-container/src/format.ts b/packages/trilium-backup-container/src/format.ts
index b0e1efab80..3cc9219534 100644
--- a/packages/trilium-backup-container/src/format.ts
+++ b/packages/trilium-backup-container/src/format.ts
@@ -74,7 +74,10 @@ export interface ContainerHeader {
version: number;
compressed: boolean;
encrypted: boolean;
- /** Size of the wrapped database before compression, or 0 when unknown. A hint, never an instruction. */
+ /**
+ * Size of the wrapped database before compression, or 0 when unknown. A hint, never an
+ * instruction.
+ */
plaintextSize: number;
headerLength: number;
encryption: EncryptionHeader | null;
@@ -89,9 +92,9 @@ export function headerLengthFor(encrypted: boolean): number {
/**
* End of the span that the verifier tag and every frame authenticate.
*
- * The verifier tag and the payload digest are the last two fields of the header and are both written
- * after the fact, so neither can be inside what the header authenticates. Stopping here also keeps a
- * bit flip in the verifier tag from invalidating every frame in the file.
+ * The verifier tag and the payload digest are the last two fields of the header and are both
+ * written after the fact, so neither can be inside what the header authenticates. Stopping here
+ * also keeps a bit flip in the verifier tag from invalidating every frame in the file.
*/
export function authenticatedHeaderEnd(headerLength: number): number {
return headerLength - TAG_BYTES - DIGEST_BYTES;
@@ -115,13 +118,18 @@ export function nonceFor(noncePrefix: Buffer, counter: number): Buffer {
return nonce;
}
-/** Serialises a header. The digest is written as supplied, so a writer passes zeros and patches later. */
+/**
+ * Serialises a header. The digest is written as supplied, so a writer passes zeros and patches
+ * later.
+ */
export function encodeHeader(header: ContainerHeader): Buffer {
const buffer = Buffer.alloc(header.headerLength);
MAGIC.copy(buffer, 0);
buffer.writeUInt8(header.version, MAGIC.length);
- buffer.writeUInt8((header.compressed ? FLAG_COMPRESSED : 0) | (header.encrypted ? FLAG_ENCRYPTED : 0), 21);
+ const compressed = header.compressed ? FLAG_COMPRESSED : 0;
+ const encrypted = header.encrypted ? FLAG_ENCRYPTED : 0;
+ buffer.writeUInt8(compressed | encrypted, 21);
buffer.writeUInt16LE(header.headerLength, 22);
buffer.writeBigUInt64LE(BigInt(header.plaintextSize), 24);
@@ -150,15 +158,18 @@ export interface FixedHeader {
}
/**
- * Parses and validates the 32 bytes every container starts with, which is as far as a reader can get
- * before it knows how long the header is.
+ * Parses and validates the 32 bytes every container starts with, which is as far as a reader can
+ * get before it knows how long the header is.
*
* @param buffer the first {@link FIXED_HEADER_BYTES} bytes of the file.
* @param maxHeaderBytes ceiling above which a header is refused outright.
*/
export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): FixedHeader {
if (!buffer.subarray(0, MAGIC.length).equals(MAGIC)) {
- throw new BackupContainerError("not-a-container", "File does not start with the container magic.");
+ throw new BackupContainerError(
+ "not-a-container",
+ "File does not start with the container magic."
+ );
}
const version = buffer.readUInt8(MAGIC.length);
@@ -166,24 +177,38 @@ export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): Fixed
throw new BackupContainerError("unsupported-version", "Version 0 is never valid.");
}
if (version > FORMAT_VERSION) {
- throw new BackupContainerError("unsupported-version", `Container version ${version} is newer than ${FORMAT_VERSION}.`);
+ throw new BackupContainerError(
+ "unsupported-version",
+ `Container version ${version} is newer than ${FORMAT_VERSION}.`
+ );
}
const flags = buffer.readUInt8(21);
if (flags & FLAG_RESERVED) {
- throw new BackupContainerError("unsupported-flags", `Reserved flag bits are set: 0x${flags.toString(16)}.`);
+ throw new BackupContainerError(
+ "unsupported-flags",
+ `Reserved flag bits are set: 0x${flags.toString(16)}.`
+ );
}
const encrypted = (flags & FLAG_ENCRYPTED) !== 0;
const headerLength = buffer.readUInt16LE(22);
if (headerLength > maxHeaderBytes) {
- throw new BackupContainerError("invalid-header-length", `Header of ${headerLength} bytes exceeds the ${maxHeaderBytes} byte ceiling.`);
+ throw new BackupContainerError(
+ "invalid-header-length",
+ `Header of ${headerLength} bytes exceeds the ${maxHeaderBytes} byte ceiling.`
+ );
}
if (headerLength !== headerLengthFor(encrypted)) {
- throw new BackupContainerError("invalid-header-length", `Header of ${headerLength} bytes does not match version ${version} with flags 0x${flags.toString(16)}.`);
+ throw new BackupContainerError(
+ "invalid-header-length",
+ `Header of ${headerLength} bytes does not match version ${version} `
+ + `with flags 0x${flags.toString(16)}.`
+ );
}
- // A hint that may only ever tighten a bound, so an unrepresentable value is the same as "unknown".
+ // A hint that may only ever tighten a bound, so an unrepresentable value is the same as
+ // "unknown".
const plaintextSize = buffer.readBigUInt64LE(24);
return {
@@ -195,7 +220,10 @@ export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): Fixed
};
}
-/** Parses the fields after the fixed header. `buffer` is the whole header, `headerLength` bytes long. */
+/**
+ * Parses the fields after the fixed header. `buffer` is the whole header, `headerLength` bytes
+ * long.
+ */
export function decodeHeader(buffer: Buffer, maxHeaderBytes: number): ContainerHeader {
const fixed = decodeFixedHeader(buffer.subarray(0, FIXED_HEADER_BYTES), maxHeaderBytes);
@@ -203,7 +231,10 @@ export function decodeHeader(buffer: Buffer, maxHeaderBytes: number): ContainerH
if (fixed.encrypted) {
const kdfId = buffer.readUInt8(32);
if (kdfId !== KDF_SCRYPT) {
- throw new BackupContainerError("unsupported-kdf", `Key derivation function ${kdfId} is not supported.`);
+ throw new BackupContainerError(
+ "unsupported-kdf",
+ `Key derivation function ${kdfId} is not supported.`
+ );
}
encryption = {
@@ -234,7 +265,11 @@ export function validateScryptParams(params: ScryptParams, maxMemoryBytes: numbe
const inRange = (value: number, bounds: { min: number; max: number }) =>
Number.isInteger(value) && value >= bounds.min && value <= bounds.max;
- if (!inRange(params.log2N, SCRYPT_BOUNDS.log2N) || !inRange(params.r, SCRYPT_BOUNDS.r) || !inRange(params.p, SCRYPT_BOUNDS.p)) {
+ const withinBounds = inRange(params.log2N, SCRYPT_BOUNDS.log2N)
+ && inRange(params.r, SCRYPT_BOUNDS.r)
+ && inRange(params.p, SCRYPT_BOUNDS.p);
+
+ if (!withinBounds) {
throw new BackupContainerError(
"invalid-kdf-params",
`scrypt parameters out of bounds: log2N=${params.log2N}, r=${params.r}, p=${params.p}.`
@@ -256,14 +291,23 @@ export function validateScryptParams(params: ScryptParams, maxMemoryBytes: numbe
* @param head at least {@link SQLITE_HEADER_BYTES} bytes from offset 0 of the output.
*/
export function validateSqliteHeader(head: Buffer): void {
- if (head.length < SQLITE_HEADER_BYTES || !head.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC)) {
- throw new BackupContainerError("not-a-database", "Output does not start with the SQLite file magic.");
+ const magicMatches = head.length >= SQLITE_HEADER_BYTES
+ && head.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC);
+
+ if (!magicMatches) {
+ throw new BackupContainerError(
+ "not-a-database",
+ "Output does not start with the SQLite file magic."
+ );
}
// Big-endian, and the value 1 encodes 65536 because that does not fit the field.
const pageSize = head.readUInt16BE(16);
const isPowerOfTwo = pageSize >= 512 && pageSize <= 32768 && (pageSize & (pageSize - 1)) === 0;
if (pageSize !== 1 && !isPowerOfTwo) {
- throw new BackupContainerError("not-a-database", `SQLite page size ${pageSize} is not valid.`);
+ throw new BackupContainerError(
+ "not-a-database",
+ `SQLite page size ${pageSize} is not valid.`
+ );
}
}
diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.ts
index e1586ea028..eaeaa5640f 100644
--- a/packages/trilium-backup-container/src/index.ts
+++ b/packages/trilium-backup-container/src/index.ts
@@ -2,9 +2,9 @@
* Reader and writer for the Trilium backup container: one SQLite database wrapped with
* optional gzip compression and optional AES-256-GCM encryption.
*
- * The module depends on nothing outside the Node standard library, carries no translated strings, and
- * reports every failure as a {@link BackupContainerError} whose `reason` is a stable machine-readable
- * code the caller maps to its own messages.
+ * The module depends on nothing outside the Node standard library, carries no translated strings,
+ * and reports every failure as a {@link BackupContainerError} whose `reason` is a stable
+ * machine-readable code the caller maps to its own messages.
*
* @example Writing an encrypted, compressed container
* ```ts
@@ -40,7 +40,11 @@
* @module
*/
-export { BackupContainerError, type BackupContainerErrorReason, isBackupContainerError } from "./errors.js";
+export {
+ BackupContainerError,
+ type BackupContainerErrorReason,
+ isBackupContainerError
+} from "./errors.js";
export {
FIXED_HEADER_BYTES,
FORMAT_VERSION,
diff --git a/packages/trilium-backup-container/src/internals.spec.ts b/packages/trilium-backup-container/src/internals.spec.ts
index 19157caf9f..53d233f454 100644
--- a/packages/trilium-backup-container/src/internals.spec.ts
+++ b/packages/trilium-backup-container/src/internals.spec.ts
@@ -8,11 +8,21 @@ import { deriveKey } from "./crypto.js";
import { BackupContainerError, isBackupContainerError } from "./errors.js";
import { FRAME_SIZE, HEADER_BYTES_PLAIN } from "./format.js";
import { FrameEncryptor } from "./streams.js";
-import { fakeDatabase, flipByte, MemorySink, reasonOf, readFromBuffer, writeToBuffer } from "./test-helpers.js";
+import {
+ fakeDatabase,
+ failureOf,
+ flipByte,
+ MemorySink,
+ reasonOf,
+ readFromBuffer,
+ writeToBuffer
+} from "./test-helpers.js";
describe("BackupContainerError", () => {
it("narrows only its own errors", () => {
- expect(isBackupContainerError(new BackupContainerError("truncated", "cut short"))).toBe(true);
+ const own = new BackupContainerError("truncated", "cut short");
+
+ expect(isBackupContainerError(own)).toBe(true);
expect(isBackupContainerError(new Error("something else"))).toBe(false);
expect(isBackupContainerError("not even an error")).toBe(false);
});
@@ -71,8 +81,11 @@ describe("compressed payload damage", () => {
// Corrupt the deflate data, then repair the digest so the failure can only come from zlib.
const damaged = flipByte(written.bytes, HEADER_BYTES_PLAIN + 30);
- createHash("sha256").update(damaged.subarray(HEADER_BYTES_PLAIN)).digest().copy(damaged, HEADER_BYTES_PLAIN - 32);
+ createHash("sha256").update(damaged.subarray(HEADER_BYTES_PLAIN)).digest().copy(
+ damaged,
+ HEADER_BYTES_PLAIN - 32
+ );
- expect(await reasonOf(readFromBuffer(damaged))).toBe("damaged-payload");
+ expect(await failureOf(damaged)).toBe("damaged-payload");
});
});
diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.ts
index a8c674008c..187fb41869 100644
--- a/packages/trilium-backup-container/src/read.ts
+++ b/packages/trilium-backup-container/src/read.ts
@@ -31,7 +31,9 @@ export const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024 * 1024;
export interface ReadBackupContainerOptions {
/** Required when the container is encrypted. */
passphrase?: string;
- /** Hard ceiling on unwrapped output. A recorded plaintext size may tighten it, never widen it. */
+ /**
+ * Hard ceiling on unwrapped output. A recorded plaintext size may tighten it, never widen it.
+ */
maxOutputBytes?: number;
/** Refuses a header above this size before anything is allocated. */
maxHeaderBytes?: number;
@@ -58,19 +60,25 @@ export interface BackupContainerInfo {
}
/**
- * 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.
+ * 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.
+ * 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 {
+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);
+ const { version, compressed, encrypted, plaintextSize } = decodeFixedHeader(
+ head.subarray(0, FIXED_HEADER_BYTES),
+ maxHeaderBytes
+ );
return { version, compressed, encrypted, plaintextSize };
} catch {
@@ -92,7 +100,8 @@ export interface ReadBackupContainerResult {
* Unwraps a container back into a database.
*
* Frames are authenticated before any of their plaintext is emitted, the output ceiling is applied
- * before bytes reach the destination, and the payload digest and recorded size are checked at the end.
+ * before bytes reach the destination, and the payload digest and recorded size are checked at the
+ * end.
*
* @param input the container bytes.
* @param output the destination for the database, which is ended by this call.
@@ -111,19 +120,30 @@ export async function readBackupContainer(
let key: Buffer | null = null;
if (header.encryption) {
if (options.passphrase === undefined) {
- throw new BackupContainerError("passphrase-required", "Container is encrypted but no passphrase was given.");
+ throw new BackupContainerError(
+ "passphrase-required",
+ "Container is encrypted but no passphrase was given."
+ );
}
- validateScryptParams(header.encryption, options.maxKdfMemoryBytes ?? DEFAULT_MAX_KDF_MEMORY_BYTES);
+ validateScryptParams(
+ header.encryption,
+ options.maxKdfMemoryBytes ?? DEFAULT_MAX_KDF_MEMORY_BYTES
+ );
key = await deriveKey(options.passphrase, header.encryption.salt, header.encryption);
if (options.skipVerifier !== true) {
- verifyPassphrase(key, header.encryption.noncePrefix, aadOf(header), header.encryption.verifierTag);
+ verifyPassphrase(
+ key,
+ header.encryption.noncePrefix,
+ aadOf(header),
+ header.encryption.verifierTag
+ );
}
}
- // A recorded size may only tighten the ceiling, never widen it: it is unauthenticated in a plain
- // container, so a crafted value would otherwise disable the guard entirely.
+ // A recorded size may only tighten the ceiling, never widen it: it is unauthenticated in a
+ // plain container, so a crafted value would otherwise disable the guard entirely.
const ceiling = Math.min(
options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
header.plaintextSize > 0 ? header.plaintextSize : Number.POSITIVE_INFINITY
@@ -134,10 +154,15 @@ export async function readBackupContainer(
? readFrames(reader, header, header.encryption, key)
: readPlainPayload(reader, header);
- const stages = header.compressed ? [payload, createGunzip(), guard, output] : [payload, guard, output];
+ const stages = header.compressed ? [payload, createGunzip(), guard, output] : [
+ payload,
+ guard,
+ output
+ ];
try {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- pipeline's overloads do not accept a built array.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- pipeline's overloads do
+ // not accept a built array.
await pipeline(stages as any);
} catch (error) {
throw translatePipelineError(error);
@@ -162,14 +187,21 @@ export async function readBackupContainer(
async function readHeader(reader: ByteReader, maxHeaderBytes: number): Promise<ContainerHeader> {
const fixedBytes = await reader.readUpTo(FIXED_HEADER_BYTES);
- // Too short to hold a header. An empty file identifies itself as nothing; anything else is judged
- // on whether what is there could be the start of the magic.
+ // Too short to hold a header. An empty file identifies itself as nothing; anything else is
+ // judged on whether what is there could be the start of the magic.
if (fixedBytes.length < FIXED_HEADER_BYTES) {
const prefix = MAGIC.subarray(0, Math.min(fixedBytes.length, MAGIC.length));
if (fixedBytes.length === 0 || !fixedBytes.subarray(0, prefix.length).equals(prefix)) {
- throw new BackupContainerError("not-a-container", "File does not start with the container magic.");
+ throw new BackupContainerError(
+ "not-a-container",
+ "File does not start with the container magic."
+ );
}
- throw new BackupContainerError("truncated", `File ends after ${fixedBytes.length} bytes, inside the header.`);
+ throw new BackupContainerError(
+ "truncated",
+ `File ends after ${fixedBytes.length} bytes,
+ inside the header.`
+ );
}
const fixed = decodeFixedHeader(fixedBytes, maxHeaderBytes);
@@ -184,7 +216,12 @@ function aadOf(header: ContainerHeader): Buffer {
}
/** Yields the plaintext of each frame, after that frame has been authenticated. */
-async function* readFrames(reader: ByteReader, header: ContainerHeader, encryption: EncryptionHeader, key: Buffer): AsyncGenerator<Buffer> {
+async function* readFrames(
+ reader: ByteReader,
+ header: ContainerHeader,
+ encryption: EncryptionHeader,
+ key: Buffer
+): AsyncGenerator<Buffer> {
const aad = aadOf(header);
const hash = createHash("sha256");
let counter = 0;
@@ -198,14 +235,26 @@ async function* readFrames(reader: ByteReader, header: ContainerHeader, encrypti
// Checked before the data is read: the field can claim up to 2 GiB.
if (length > FRAME_SIZE || (!final && length !== FRAME_SIZE)) {
- throw new BackupContainerError("invalid-frame-length", `Frame ${counter} at offset ${offset} declares ${length} bytes.`);
+ throw new BackupContainerError(
+ "invalid-frame-length",
+ `Frame ${counter} at offset ${offset} declares ${length} bytes.`
+ );
}
const ciphertext = await reader.readExactly(length);
const tag = await reader.readExactly(TAG_BYTES);
hash.update(lengthField).update(ciphertext).update(tag);
- yield openFrame(key, encryption.noncePrefix, aad, counter, lengthField, ciphertext, tag, offset);
+ yield openFrame(
+ key,
+ encryption.noncePrefix,
+ aad,
+ counter,
+ lengthField,
+ ciphertext,
+ tag,
+ offset
+ );
if (final) {
break;
@@ -214,14 +263,20 @@ async function* readFrames(reader: ByteReader, header: ContainerHeader, encrypti
}
if (!(await reader.atEof())) {
- throw new BackupContainerError("trailing-data", `Bytes follow the final frame at offset ${reader.consumed}.`);
+ throw new BackupContainerError(
+ "trailing-data",
+ `Bytes follow the final frame at offset ${reader.consumed}.`
+ );
}
verifyDigest(hash.digest(), header.digest);
}
/** Yields the payload of an unencrypted container, which runs to end of file. */
-async function* readPlainPayload(reader: ByteReader, header: ContainerHeader): AsyncGenerator<Buffer> {
+async function* readPlainPayload(
+ reader: ByteReader,
+ header: ContainerHeader
+): AsyncGenerator<Buffer> {
const hash = createHash("sha256");
for (;;) {
@@ -238,15 +293,23 @@ async function* readPlainPayload(reader: ByteReader, header: ContainerHeader): A
function verifyDigest(actual: Buffer, expected: Buffer): void {
if (!timingSafeEqual(actual, expected)) {
- throw new BackupContainerError("digest-mismatch", "Payload digest does not match the header.");
+ throw new BackupContainerError(
+ "digest-mismatch",
+ "Payload digest does not match the header."
+ );
}
}
-/** zlib failures mean a damaged payload; everything else, e.g. a full disk, belongs to the caller. */
+/**
+ * zlib failures mean a damaged payload; everything else, e.g. a full disk, belongs to the caller.
+ */
function translatePipelineError(error: unknown): unknown {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (typeof code === "string" && code.startsWith("Z_")) {
- return new BackupContainerError("damaged-payload", `Compressed payload could not be read: ${code}.`);
+ return new BackupContainerError(
+ "damaged-payload",
+ `Compressed payload could not be read: ${code}.`
+ );
}
return error;
diff --git a/packages/trilium-backup-container/src/streams.ts b/packages/trilium-backup-container/src/streams.ts
index 9cf17d5c3b..0d87991476 100644
--- a/packages/trilium-backup-container/src/streams.ts
+++ b/packages/trilium-backup-container/src/streams.ts
@@ -22,7 +22,11 @@ export class DigestTap extends Transform {
return this.#bytes;
}
- override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {
+ override _transform(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: TransformCallback
+ ): void {
this.#hash.update(chunk);
this.#bytes += chunk.length;
callback(null, chunk);
@@ -36,14 +40,18 @@ export class DigestTap extends Transform {
/**
* Forces the gzip OS byte to "unknown".
*
- * Node emits MTIME 0 and no FNAME or FEXTRA already, but the OS byte follows the build platform (3 on
- * Unix, 10 on Windows), which would leak where the backup was written. The byte is informational and
- * outside gzip's CRC, so rewriting it is safe.
+ * Node emits MTIME 0 and no FNAME or FEXTRA already, but the OS byte follows the build platform (3
+ * on Unix, 10 on Windows), which would leak where the backup was written. The byte is informational
+ * and outside gzip's CRC, so rewriting it is safe.
*/
export class GzipHeaderNormaliser extends Transform {
#seen = 0;
- override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {
+ override _transform(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: TransformCallback
+ ): void {
const osByteIndex = 9 - this.#seen;
if (osByteIndex >= 0 && osByteIndex < chunk.length) {
// Copy first: the buffer belongs to zlib.
@@ -59,8 +67,9 @@ export class GzipHeaderNormaliser extends Transform {
* Splits the stream into authenticated frames.
*
* Full frames are emitted as soon as they fill and the flush always emits exactly one final frame,
- * which is why a payload that is an exact multiple of the frame size ends with an empty one. That is
- * the canonical framing, and it lets the writer stream without ever needing to know what follows.
+ * which is why a payload that is an exact multiple of the frame size ends with an empty one. That
+ * is the canonical framing, and it lets the writer stream without ever needing to know what
+ * follows.
*/
export class FrameEncryptor extends Transform {
readonly #frame = Buffer.allocUnsafe(FRAME_SIZE);
@@ -77,7 +86,11 @@ export class FrameEncryptor extends Transform {
super();
}
- override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {
+ override _transform(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: TransformCallback
+ ): void {
let offset = 0;
try {
@@ -109,13 +122,23 @@ export class FrameEncryptor extends Transform {
#seal(final: boolean): Buffer {
if (this.#counter > this.maxCounter) {
- throw new BackupContainerError("payload-too-large", `Payload needs more than ${this.maxCounter + 1} frames.`);
+ throw new BackupContainerError(
+ "payload-too-large",
+ `Payload needs more than ${this.maxCounter + 1} frames.`
+ );
}
const lengthField = Buffer.allocUnsafe(4);
lengthField.writeUInt32LE(final ? (this.#filled | FRAME_FINAL_FLAG) >>> 0 : this.#filled);
- const frame = sealFrame(this.key, this.noncePrefix, this.aad, this.#counter, lengthField, this.#frame.subarray(0, this.#filled));
+ const frame = sealFrame(
+ this.key,
+ this.noncePrefix,
+ this.aad,
+ this.#counter,
+ lengthField,
+ this.#frame.subarray(0, this.#filled)
+ );
this.#counter++;
this.#filled = 0;
@@ -145,9 +168,16 @@ export class OutputGuard extends Transform {
return this.#written;
}
- override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {
+ override _transform(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: TransformCallback
+ ): void {
if (this.#written + chunk.length > this.ceiling) {
- callback(new BackupContainerError("output-too-large", `Output would exceed the ${this.ceiling} byte ceiling.`));
+ callback(new BackupContainerError(
+ "output-too-large",
+ `Output would exceed the ${this.ceiling} byte ceiling.`
+ ));
return;
}
this.#written += chunk.length;
@@ -173,7 +203,10 @@ export class OutputGuard extends Transform {
override _flush(callback: TransformCallback): void {
if (this.requireSqliteHeader && !this.#headChecked) {
- callback(new BackupContainerError("not-a-database", "Output is too short to be a SQLite database."));
+ callback(new BackupContainerError(
+ "not-a-database",
+ "Output is too short to be a SQLite database."
+ ));
return;
}
callback();
diff --git a/packages/trilium-backup-container/src/test-helpers.ts b/packages/trilium-backup-container/src/test-helpers.ts
index 7d8a6c10c9..345ac29a04 100644
--- a/packages/trilium-backup-container/src/test-helpers.ts
+++ b/packages/trilium-backup-container/src/test-helpers.ts
@@ -1,8 +1,16 @@
import { Readable, Writable } from "node:stream";
import { SQLITE_MAGIC, type ScryptParams } from "./format.js";
-import { readBackupContainer, type ReadBackupContainerOptions, type ReadBackupContainerResult } from "./read.js";
-import { writeBackupContainer, type WriteBackupContainerOptions, type WriteBackupContainerResult } from "./write.js";
+import {
+ readBackupContainer,
+ type ReadBackupContainerOptions,
+ type ReadBackupContainerResult
+} from "./read.js";
+import {
+ writeBackupContainer,
+ type WriteBackupContainerOptions,
+ type WriteBackupContainerResult
+} from "./write.js";
/** Cheap scrypt cost, so the suite is not dominated by key derivation. */
export const FAST_SCRYPT: ScryptParams = { log2N: 10, r: 8, p: 1 };
@@ -10,7 +18,11 @@ export const FAST_SCRYPT: ScryptParams = { log2N: 10, r: 8, p: 1 };
export class MemorySink extends Writable {
readonly chunks: Buffer[] = [];
- override _write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
+ override _write(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: (error?: Error | null) => void
+ ): void {
this.chunks.push(Buffer.from(chunk));
callback();
}
@@ -57,7 +69,10 @@ export async function writeToBuffer(
const result = await writeBackupContainer(
Buffer.isBuffer(input) ? Readable.from([input]) : input,
sink,
- { ...options, patchHeader: (offset, data) => { patches.push({ offset, data: Buffer.from(data) }); } }
+ {
+ ...options,
+ patchHeader: (offset, data) => { patches.push({ offset, data: Buffer.from(data) }); }
+ }
);
const bytes = sink.toBuffer();
@@ -73,7 +88,10 @@ export interface ReadContainer {
result: ReadBackupContainerResult;
}
-export async function readFromBuffer(container: Buffer, options: ReadBackupContainerOptions = {}): Promise<ReadContainer> {
+export async function readFromBuffer(
+ container: Buffer,
+ options: ReadBackupContainerOptions = {}
+): Promise<ReadContainer> {
const sink = new MemorySink();
const result = await readBackupContainer(Readable.from([container]), sink, options);
@@ -88,6 +106,14 @@ export function flipByte(data: Buffer, offset: number): Buffer {
return copy;
}
+/** The `reason` reading these bytes fails with, which most of the failure tests assert on. */
+export function failureOf(
+ container: Buffer,
+ options: ReadBackupContainerOptions = {}
+): Promise<string> {
+ return reasonOf(readFromBuffer(container, options));
+}
+
/** Runs `read` and returns the `reason` of the BackupContainerError it throws. */
export async function reasonOf(operation: Promise<unknown>): Promise<string> {
try {
diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.ts
index 9b868609c2..01b7f26e65 100644
--- a/packages/trilium-backup-container/src/write.ts
+++ b/packages/trilium-backup-container/src/write.ts
@@ -77,18 +77,26 @@ export async function writeBackupContainer(
options: WriteBackupContainerOptions
): Promise<WriteBackupContainerResult> {
if (typeof options.patchHeader !== "function") {
- throw new BackupContainerError("invalid-options", "patchHeader is required to write the payload digest.");
+ throw new BackupContainerError(
+ "invalid-options",
+ "patchHeader is required to write the payload digest."
+ );
}
const plaintextSize = options.plaintextSize ?? 0;
if (!Number.isSafeInteger(plaintextSize) || plaintextSize < 0) {
- throw new BackupContainerError("invalid-options", `plaintextSize must be a non-negative safe integer, got ${plaintextSize}.`);
+ throw new BackupContainerError(
+ "invalid-options",
+ `plaintextSize must be a non-negative safe integer,
+ got ${plaintextSize}.`
+ );
}
const compressed = options.compress === true;
const encrypted = options.passphrase !== undefined;
- // Build the header first: the verifier tag authenticates the bytes before it, so those must be final.
+ // Build the header first: the verifier tag authenticates the bytes before it, so those must be
+ // final.
const header: ContainerHeader = {
version: FORMAT_VERSION,
compressed,
@@ -118,7 +126,10 @@ export async function writeBackupContainer(
const aad = headerBytes.subarray(0, authenticatedHeaderEnd(header.headerLength));
if (header.encryption && key) {
- computeVerifierTag(key, header.encryption.noncePrefix, aad).copy(headerBytes, authenticatedHeaderEnd(header.headerLength));
+ computeVerifierTag(key, header.encryption.noncePrefix, aad).copy(
+ headerBytes,
+ authenticatedHeaderEnd(header.headerLength)
+ );
}
await writeChunk(output, headerBytes);
@@ -127,14 +138,18 @@ export async function writeBackupContainer(
const digestTap = new DigestTap();
const stages: (Readable | Writable)[] = [input];
if (compressed) {
- stages.push(createGzip({ level: options.compressionLevel ?? 6 }), new GzipHeaderNormaliser());
+ stages.push(
+ createGzip({ level: options.compressionLevel ?? 6 }),
+ new GzipHeaderNormaliser()
+ );
}
if (header.encryption && key) {
stages.push(new FrameEncryptor(key, header.encryption.noncePrefix, aad));
}
stages.push(digestTap, output);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- pipeline's overloads do not accept a built array.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- pipeline's overloads do not
+ // accept a built array.
await pipeline(stages as any);
const digest = digestTap.digest();