Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
packages: implement a stand-alone Trilium backup container read/write utility
Adorian Doran66fbd5f6cc16
diff --git a/packages/trilium-backup-container/package.json b/packages/trilium-backup-container/package.jsonnew file mode 100644index 0000000000..6e1be9bc44--- /dev/null+++ b/packages/trilium-backup-container/package.json@@ -0,0 +1,19 @@+{+ "name": "@triliumnext/backup-container",+ "description": "Reader and writer for the Trilium `.tbak` backup container format: a SQLite database wrapped with optional gzip compression and optional AES-256-GCM encryption.",+ "license": "MIT",+ "version": "1.0.0",+ "type": "module",+ "private": true,+ "main": "./src/index.ts",+ "scripts": {+ "test": "vitest"+ },+ "keywords": [+ "backup",+ "container",+ "aes-256-gcm",+ "gzip",+ "sqlite"+ ]+}diff --git a/packages/trilium-backup-container/src/byte-reader.ts b/packages/trilium-backup-container/src/byte-reader.tsnew file mode 100644index 0000000000..ddb3260796--- /dev/null+++ b/packages/trilium-backup-container/src/byte-reader.ts@@ -0,0 +1,73 @@+import type { Readable } from "node:stream";++import { BackupContainerError } from "./errors.js";++/** Pull-based view over a readable stream, so the reader can ask for exact byte counts. */+export class ByteReader {+ readonly #iterator: AsyncIterator<Buffer>;+ #pending: Buffer[] = [];+ #pendingBytes = 0;+ #exhausted = false;+ #consumed = 0;++ constructor(stream: Readable) {+ this.#iterator = stream[Symbol.asyncIterator]() as AsyncIterator<Buffer>;+ }++ /** Bytes handed out so far, which is the offset a failure should be reported at. */+ get consumed(): number {+ return this.#consumed;+ }++ /** Reads exactly `count` bytes, or throws `truncated`. */+ async readExactly(count: number): Promise<Buffer> {+ await this.#buffer(count);++ if (this.#pendingBytes < count) {+ throw new BackupContainerError("truncated", `Expected ${count} bytes at offset ${this.#consumed}, found ${this.#pendingBytes}.`);+ }++ return this.#take(count);+ }++ /** Reads up to `count` bytes, returning fewer at end of input. */+ async readUpTo(count: number): Promise<Buffer> {+ await this.#buffer(count);++ return this.#take(Math.min(count, this.#pendingBytes));+ }++ async atEof(): Promise<boolean> {+ await this.#buffer(1);++ return this.#pendingBytes === 0;+ }++ async #buffer(target: number): Promise<void> {+ while (this.#pendingBytes < target && !this.#exhausted) {+ const next = await this.#iterator.next();+ if (next.done) {+ this.#exhausted = true;+ } else {+ this.#pending.push(next.value);+ this.#pendingBytes += next.value.length;+ }+ }+ }++ #take(count: number): Buffer {+ if (count === 0) {+ return Buffer.alloc(0);+ }++ 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);++ this.#pending = rest.length > 0 ? [rest] : [];+ this.#pendingBytes = rest.length;+ this.#consumed += count;++ return taken;+ }+}diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.tsnew file mode 100644index 0000000000..43853a4674--- /dev/null+++ b/packages/trilium-backup-container/src/container.spec.ts@@ -0,0 +1,355 @@+import { createHash } from "node:crypto";+import { Readable } from "node:stream";+import { gunzipSync } from "node:zlib";+import { describe, expect, it } from "vitest";++import {+ FRAME_SIZE,+ HEADER_BYTES_ENCRYPTED,+ HEADER_BYTES_PLAIN,+ TAG_BYTES+} from "./format.js";+import { readBackupContainer } from "./read.js";+import {+ chunked,+ fakeDatabase,+ FAST_SCRYPT,+ flipByte,+ MemorySink,+ reasonOf,+ readFromBuffer,+ writeToBuffer+} from "./test-helpers.js";+import { writeBackupContainer, type WriteBackupContainerOptions } from "./write.js";++type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;++const PASSPHRASE = "correct horse battery staple";+const FRAME_OVERHEAD = 4 + TAG_BYTES;++describe("round trip", () => {+ const cases: [string, WriteOptions, number][] = [+ ["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]+ ];++ 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 });+ expect(written.result.headerLength).toBe(headerLength);+ expect(written.patchedAt).toEqual([headerLength - 32]);++ const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ expect(read.result).toMatchObject({+ version: 1,+ compressed: options.compress === true,+ encrypted: options.passphrase !== undefined,+ plaintextSize: database.length,+ bytesWritten: database.length+ });+ });++ it("survives input arriving in awkward chunks", async () => {+ const database = fakeDatabase(9_000);+ const written = await writeToBuffer(chunked(database, 7), {+ compress: true,+ passphrase: PASSPHRASE,+ scrypt: FAST_SCRYPT+ });++ const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ });++ it("wraps an empty payload as a single empty final frame", async () => {+ 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 });+ expect(read.result.bytesWritten).toBe(0);+ });++ it("compresses, so a repetitive database gets much smaller", async () => {+ const database = fakeDatabase(256 * 1024);++ const plain = await writeToBuffer(database);+ const compressed = await writeToBuffer(database, { compress: true });++ expect(compressed.bytes.length).toBeLessThan(plain.bytes.length / 10);+ });+});++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 payload = written.bytes.subarray(HEADER_BYTES_ENCRYPTED);+ const stored = written.bytes.subarray(HEADER_BYTES_ENCRYPTED - 32, HEADER_BYTES_ENCRYPTED);++ expect(stored.equals(createHash("sha256").update(payload).digest())).toBe(true);+ expect(written.result.digest.equals(stored)).toBe(true);+ expect(written.result.payloadBytes).toBe(payload.length);+ });++ it("catches damage to an unencrypted payload", async () => {+ const written = await writeToBuffer(fakeDatabase(4096));+ const damaged = flipByte(written.bytes, written.bytes.length - 5);++ expect(await reasonOf(readFromBuffer(damaged))).toBe("digest-mismatch");+ });+});++describe("gzip payload", () => {+ it("is a plain gzip stream with no metadata, recoverable with stock tools", async () => {+ const database = fakeDatabase(5_000);+ const written = await writeToBuffer(database, { compress: true });+ const payload = written.bytes.subarray(HEADER_BYTES_PLAIN);++ expect(payload.readUInt16BE(0)).toBe(0x1f8b);+ expect(payload.readUInt8(3)).toBe(0); // no FNAME, no FEXTRA+ expect(payload.readUInt32LE(4)).toBe(0); // MTIME, so no timestamp leaks+ expect(payload.readUInt8(9)).toBe(255); // OS, so the platform does not leak+ expect(gunzipSync(payload).equals(database)).toBe(true);+ });+});++describe("canonical framing", () => {+ it("ends a payload that is an exact multiple of the frame size with an empty final frame", async () => {+ const database = fakeDatabase(2 * FRAME_SIZE);+ 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);++ const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ });++ 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 });++ expect(written.bytes).toHaveLength(+ HEADER_BYTES_ENCRYPTED + (FRAME_SIZE + FRAME_OVERHEAD) + (1_000 + FRAME_OVERHEAD)+ );+ });+});++describe("passphrase handling", () => {+ it("rejects the wrong passphrase before reading any frame", async () => {+ const written = await writeToBuffer(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });++ expect(await reasonOf(readFromBuffer(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 });++ expect(await reasonOf(readFromBuffer(written.bytes))).toBe("passphrase-required");+ });++ it("normalises to NFC, so a decomposed and a composed passphrase agree", async () => {+ const decomposed = "café secret"; // e plus combining acute+ const composed = "café secret"; // precomposed e-acute+ expect(decomposed).not.toBe(composed);++ 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 });++ 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 });++ 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 })))+ .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 });+ expect(recovered.bytes.equals(fakeDatabase(2 * FRAME_SIZE))).toBe(true);+ });++ it("rejects a flipped bit in the salt, which no recovery can undo", async () => {+ const written = await encrypted();+ const damaged = flipByte(written.bytes, 40);++ expect(await reasonOf(readFromBuffer(damaged, { passphrase: PASSPHRASE, skipVerifier: true })))+ .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");+ });++ 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");+ });++ 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");+ });++ it("rejects a non-final frame that is not exactly one frame long", async () => {+ const written = await encrypted();+ const tampered = Buffer.from(written.bytes);+ tampered.writeUInt32LE(5, HEADER_BYTES_ENCRYPTED);++ expect(await reasonOf(readFromBuffer(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 tampered = Buffer.from(written.bytes);+ tampered.writeUInt32LE(0xffffffff, HEADER_BYTES_ENCRYPTED); // final flag plus a 2 GiB claim++ expect(await reasonOf(readFromBuffer(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)));+ });+});++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"]+ ])("rejects %s", async (_label, bytes, reason) => {+ expect(await reasonOf(readFromBuffer(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");+ });+});++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");+ });++ 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 tightened = Buffer.from(written.bytes);+ tightened.writeBigUInt64LE(1_000n, 24);++ expect(await reasonOf(readFromBuffer(tightened))).toBe("output-too-large");+ });++ it("never lets a crafted plaintext size widen the ceiling", async () => {+ const written = await writeToBuffer(fakeDatabase(64 * 1024), { compress: true });+ const crafted = Buffer.from(written.bytes);+ crafted.writeBigUInt64LE(2n ** 63n, 24);++ expect(await reasonOf(readFromBuffer(crafted, { maxOutputBytes: 1_000 }))).toBe("output-too-large");+ });++ it("rejects output whose length disagrees with the recorded size", async () => {+ const database = fakeDatabase(4096);+ const written = await writeToBuffer(database, { plaintextSize: database.length });+ const lying = Buffer.from(written.bytes);+ lying.writeBigUInt64LE(5_000n, 24);++ expect(await reasonOf(readFromBuffer(lying))).toBe("size-mismatch");+ });+});++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);+ });++ 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");+ });+});++describe("option validation", () => {+ it("requires patchHeader, since the digest is written after the payload", async () => {+ const reason = await reasonOf(+ writeBackupContainer(Readable.from([fakeDatabase()]), new MemorySink(), {} as never)+ );++ expect(reason).toBe("invalid-options");+ });++ 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"]+ ])("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 });++ expect(await reasonOf(readFromBuffer(written.bytes, { passphrase: PASSPHRASE, maxKdfMemoryBytes: 1024 })))+ .toBe("invalid-kdf-params");+ });+});++describe("errors", () => {+ it("carries a machine-readable reason and a plain English message", async () => {+ try {+ await readFromBuffer(Buffer.alloc(300, 9));+ expect.unreachable("should have thrown");+ } catch (error) {+ expect(error).toMatchObject({ name: "BackupContainerError", reason: "not-a-container" });+ expect((error as Error).message).toMatch(/container magic/);+ }+ });++ 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"));++ await expect(readBackupContainer(Readable.from([written.bytes]), failing)).rejects.toThrow(/ENOSPC/);+ });+});diff --git a/packages/trilium-backup-container/src/crypto.ts b/packages/trilium-backup-container/src/crypto.tsnew file mode 100644index 0000000000..98535afc8a--- /dev/null+++ b/packages/trilium-backup-container/src/crypto.ts@@ -0,0 +1,96 @@+import { createCipheriv, createDecipheriv, scrypt } from "node:crypto";++import { BackupContainerError } from "./errors.js";+import {+ KEY_BYTES,+ nonceFor,+ type ScryptParams,+ scryptMemoryBytes,+ TAG_BYTES,+ VERIFIER_COUNTER+} 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.+ */+const MAXMEM_SLACK_BYTES = 1024 * 1024;++/**+ * Derives the 32-byte file key.+ *+ * The passphrase is normalised to Unicode NFC and encoded as UTF-8, which is part of the format:+ * neither JavaScript nor Node normalises implicitly, so a composed and a decomposed `é` would+ * otherwise derive different keys on different machines.+ */+export function deriveKey(passphrase: string, salt: Buffer, params: ScryptParams): Promise<Buffer> {+ const secret = Buffer.from(passphrase.normalize("NFC"), "utf8");+ const options = {+ N: 2 ** params.log2N,+ r: params.r,+ p: params.p,+ maxmem: scryptMemoryBytes(params) + MAXMEM_SLACK_BYTES+ };++ return new Promise((resolve, reject) => {+ const fail = (error: Error) =>+ reject(new BackupContainerError("invalid-kdf-params", `Key derivation failed: ${error.message}`));++ // 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)));+ } catch (error) {+ fail(error as Error);+ }+ });+}++/** 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 {+ const cipher = createCipheriv("aes-256-gcm", key, nonceFor(noncePrefix, counter));+ cipher.setAAD(Buffer.concat([aad, lengthField]));++ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);++ return Buffer.concat([lengthField, ciphertext, cipher.getAuthTag()]);+}++/** 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 {+ const decipher = createDecipheriv("aes-256-gcm", key, nonceFor(noncePrefix, counter));+ decipher.setAAD(Buffer.concat([aad, lengthField]));+ decipher.setAuthTag(tag);++ try {+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);+ } catch {+ throw new BackupContainerError("damaged-payload", `Frame ${counter} failed authentication at byte offset ${offset}.`);+ }+}++/** Computes the verifier tag: GCM over an empty plaintext, on the reserved counter. */+export function computeVerifierTag(key: Buffer, noncePrefix: Buffer, aad: Buffer): Buffer {+ const cipher = createCipheriv("aes-256-gcm", key, nonceFor(noncePrefix, VERIFIER_COUNTER));+ cipher.setAAD(aad);+ cipher.final();++ return cipher.getAuthTag();+}++/**+ * 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.+ */+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));++ try {+ decipher.final();+ } catch {+ 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.tsnew file mode 100644index 0000000000..aa4ede958a--- /dev/null+++ b/packages/trilium-backup-container/src/errors.ts@@ -0,0 +1,60 @@+/**+ * 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.+ */+export type BackupContainerErrorReason =+ /** The first bytes are not the container magic, i.e. this is not a `.tbak` file at all. */+ | "not-a-container"+ /** Written by a newer version of the format than this reader implements. */+ | "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. */+ | "invalid-header-length"+ /** The key derivation function id is not one this reader implements. */+ | "unsupported-kdf"+ /** Key derivation parameters are outside the accepted bounds, or too expensive to honour. */+ | "invalid-kdf-params"+ /** The container is encrypted and no passphrase was supplied. */+ | "passphrase-required"+ /** The verifier tag did not match: a wrong passphrase, or a damaged header. */+ | "wrong-passphrase-or-damaged-header"+ /** A frame failed authentication, i.e. the payload is damaged or was tampered with. */+ | "damaged-payload"+ /** A frame declared a length the format does not allow. */+ | "invalid-frame-length"+ /** Bytes follow the final frame. */+ | "trailing-data"+ /** The file ends before the container does. */+ | "truncated"+ /** The payload digest did not match the payload as read. */+ | "digest-mismatch"+ /** The output length disagrees with the plaintext size recorded in the header. */+ | "size-mismatch"+ /** The output exceeded the ceiling before it was written, e.g. a crafted compressed payload. */+ | "output-too-large"+ /** The unwrapped payload is not a SQLite database. */+ | "not-a-database"+ /** The input is larger than the format can represent. */+ | "payload-too-large"+ /** The caller passed options this module cannot act on. */+ | "invalid-options";++/** Error thrown by every entry point in this module. */+export class BackupContainerError extends Error {+ /** Machine-readable cause, for callers that must map failures to their own messages. */+ readonly reason: BackupContainerErrorReason;++ constructor(reason: BackupContainerErrorReason, message: string) {+ super(message);+ this.name = "BackupContainerError";+ this.reason = reason;+ }+}++/** Narrowing helper for callers that catch errors from this module. */+export function isBackupContainerError(error: unknown): error is BackupContainerError {+ return error instanceof BackupContainerError;+}diff --git a/packages/trilium-backup-container/src/file-destination.spec.ts b/packages/trilium-backup-container/src/file-destination.spec.tsnew file mode 100644index 0000000000..ee2e867fc8--- /dev/null+++ b/packages/trilium-backup-container/src/file-destination.spec.ts@@ -0,0 +1,59 @@+import { createReadStream, createWriteStream } from "node:fs";+import { mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { readBackupContainer } from "./read.js";+import { fakeDatabase, FAST_SCRYPT } from "./test-helpers.js";+import { writeBackupContainer } from "./write.js";++/** Exercises the file destination from the module docs, including the out-of-order digest patch. */+describe("file destination", () => {+ let directory = "";++ beforeAll(async () => {+ directory = await mkdtemp(join(tmpdir(), "tbak-"));+ });++ afterAll(async () => {+ await rm(directory, { recursive: true, force: true });+ });++ it("writes to a file, patches the digest, and reads back byte for byte", async () => {+ const database = fakeDatabase(3 * 1024 * 1024);+ const source = join(directory, "document.db");+ const partial = join(directory, "backup.tbak.part");+ const container = join(directory, "backup.tbak");+ const restored = join(directory, "restored.db");+ await writeFile(source, database);++ const result = await writeBackupContainer(createReadStream(source), createWriteStream(partial), {+ compress: true,+ passphrase: "file test",+ scrypt: FAST_SCRYPT,+ plaintextSize: (await stat(source)).size,+ patchHeader: async (offset, data) => {+ const handle = await open(partial, "r+");+ try {+ await handle.write(data, 0, data.length, offset);+ await handle.sync();+ } finally {+ await handle.close();+ }+ }+ });++ expect(result).toMatchObject({ headerLength: 108, compressed: true, encrypted: true });++ await rename(partial, container);+ expect((await stat(container)).size).toBeLessThan(database.length);++ const info = await readBackupContainer(createReadStream(container), createWriteStream(restored), {+ passphrase: "file test"+ });++ 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.tsnew file mode 100644index 0000000000..25ef1ff510--- /dev/null+++ b/packages/trilium-backup-container/src/format.spec.ts@@ -0,0 +1,194 @@+import { describe, expect, it } from "vitest";++import { BackupContainerError } from "./errors.js";+import {+ authenticatedHeaderEnd,+ type ContainerHeader,+ decodeFixedHeader,+ decodeHeader,+ DEFAULT_MAX_HEADER_BYTES,+ digestOffset,+ encodeHeader,+ FIXED_HEADER_BYTES,+ HEADER_BYTES_ENCRYPTED,+ HEADER_BYTES_PLAIN,+ KDF_SCRYPT,+ nonceFor,+ SQLITE_MAGIC,+ scryptMemoryBytes,+ validateScryptParams,+ validateSqliteHeader+} from "./format.js";++function plainHeader(overrides: Partial<ContainerHeader> = {}): ContainerHeader {+ return {+ version: 1,+ compressed: true,+ encrypted: false,+ plaintextSize: 4096,+ headerLength: HEADER_BYTES_PLAIN,+ encryption: null,+ digest: Buffer.alloc(32, 7),+ ...overrides+ };+}++function encryptedHeader(): ContainerHeader {+ return {+ version: 1,+ compressed: false,+ encrypted: true,+ plaintextSize: 123456789,+ headerLength: HEADER_BYTES_ENCRYPTED,+ encryption: {+ kdfId: KDF_SCRYPT,+ log2N: 17,+ r: 8,+ p: 1,+ salt: Buffer.alloc(16, 1),+ noncePrefix: Buffer.alloc(8, 2),+ verifierTag: Buffer.alloc(16, 3)+ },+ digest: Buffer.alloc(32, 4)+ };+}++describe("header layout", () => {+ it("round-trips an unencrypted header and matches the documented offsets", () => {+ const bytes = encodeHeader(plainHeader());++ expect(bytes).toHaveLength(64);+ expect(bytes.subarray(0, 20).toString("ascii")).toBe("Trilium Notes Backup");+ expect(bytes.readUInt8(20)).toBe(1);+ expect(bytes.readUInt8(21)).toBe(0b01);+ expect(bytes.readUInt16LE(22)).toBe(64);+ expect(bytes.readBigUInt64LE(24)).toBe(4096n);+ 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.encryption).toBeNull();+ expect(decoded.digest.equals(Buffer.alloc(32, 7))).toBe(true);+ });++ it("round-trips an encrypted header, with the tag and digest as the last two fields", () => {+ const header = encryptedHeader();+ const bytes = encodeHeader(header);++ expect(bytes).toHaveLength(108);+ expect(bytes.readUInt8(21)).toBe(0b10);+ expect(bytes.readUInt8(32)).toBe(KDF_SCRYPT);+ expect([bytes.readUInt8(33), bytes.readUInt8(34), bytes.readUInt8(35)]).toEqual([17, 8, 1]);+ expect(authenticatedHeaderEnd(108)).toBe(60);+ expect(digestOffset(108)).toBe(76);++ const decoded = decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES);+ expect(decoded.encryption).toMatchObject({ kdfId: KDF_SCRYPT, log2N: 17, r: 8, p: 1 });+ expect(decoded.encryption?.salt.equals(Buffer.alloc(16, 1))).toBe(true);+ expect(decoded.encryption?.verifierTag.equals(Buffer.alloc(16, 3))).toBe(true);+ expect(decoded.plaintextSize).toBe(123456789);+ });++ it("treats an unrepresentable plaintext size as unknown, so it can never widen a bound", () => {+ const bytes = encodeHeader(plainHeader());+ bytes.writeBigUInt64LE(2n ** 63n, 24);++ expect(decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES).plaintextSize).toBe(0);+ });++ it("builds a distinct 12-byte nonce per counter", () => {+ const prefix = Buffer.alloc(8, 9);++ expect(nonceFor(prefix, 0)).toHaveLength(12);+ expect(nonceFor(prefix, 0).equals(nonceFor(prefix, 1))).toBe(false);+ expect(nonceFor(prefix, 0xffffffff).subarray(8).toString("hex")).toBe("ffffffff");+ });+});++describe("fixed header validation", () => {+ const decode = (mutate: (bytes: Buffer) => void, max = DEFAULT_MAX_HEADER_BYTES) => {+ const bytes = encodeHeader(plainHeader()).subarray(0, FIXED_HEADER_BYTES);+ mutate(bytes);++ return () => decodeFixedHeader(bytes, max);+ };++ it.each([+ ["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"]+ ])("rejects %s", (_label, mutate, reason) => {+ expect(decode(mutate)).toThrow(expect.objectContaining({ reason }) as Error);+ });++ it("rejects a header above the ceiling before anything else", () => {+ expect(decode((bytes) => bytes.writeUInt16LE(4000, 22), 128)).toThrow(+ expect.objectContaining({ reason: "invalid-header-length" }) as Error+ );+ });++ 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);+ });++ it("rejects a KDF id it does not implement", () => {+ const bytes = encodeHeader(encryptedHeader());+ bytes.writeUInt8(2, 32);++ expect(() => decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES)).toThrow(+ expect.objectContaining({ reason: "unsupported-kdf" }) as Error+ );+ });+});++describe("scrypt parameter bounds", () => {+ it("reports the working set the ceiling is applied to", () => {+ expect(scryptMemoryBytes({ log2N: 17, r: 8, p: 1 })).toBe(134217728);+ });++ it.each([+ ["log2N below the floor", { log2N: 9, r: 8, p: 1 }],+ ["log2N above the ceiling", { log2N: 21, r: 8, p: 1 }],+ ["r out of range", { log2N: 14, r: 17, p: 1 }],+ ["p out of range", { log2N: 14, r: 8, p: 9 }],+ ["a non-integer", { log2N: 14.5, r: 8, p: 1 }]+ ])("rejects %s", (_label, params) => {+ expect(() => validateScryptParams(params, 1024 ** 3)).toThrow(+ expect.objectContaining({ reason: "invalid-kdf-params" }) as Error+ );+ });++ 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);+ expect(() => validateScryptParams({ log2N: 17, r: 8, p: 1 }, 134217728)).not.toThrow();+ });+});++describe("SQLite header check", () => {+ it("accepts a normal page size and the 1-means-65536 encoding", () => {+ expect(() => validateSqliteHeader(sqliteHead(4096))).not.toThrow();+ expect(() => validateSqliteHeader(sqliteHead(512))).not.toThrow();+ expect(() => validateSqliteHeader(sqliteHead(32768))).not.toThrow();+ expect(() => validateSqliteHeader(sqliteHead(1))).not.toThrow();+ });++ it.each([+ ["a page size that is not a power of two", sqliteHead(3000)],+ ["a page size below the floor", sqliteHead(256)],+ ["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);+ });+});++function sqliteHead(pageSize: number): Buffer {+ const head = Buffer.alloc(18);+ SQLITE_MAGIC.copy(head, 0);+ head.writeUInt16BE(pageSize, 16);++ return head;+}diff --git a/packages/trilium-backup-container/src/format.ts b/packages/trilium-backup-container/src/format.tsnew file mode 100644index 0000000000..b0e1efab80--- /dev/null+++ b/packages/trilium-backup-container/src/format.ts@@ -0,0 +1,269 @@+import { BackupContainerError } from "./errors.js";++/** ASCII magic that opens every container. */+export const MAGIC = Buffer.from("Trilium Notes Backup", "ascii");++/** Format version this module reads and writes. Version 0 is never valid. */+export const FORMAT_VERSION = 1;++export const FLAG_COMPRESSED = 0b0000_0001;+export const FLAG_ENCRYPTED = 0b0000_0010;+export const FLAG_RESERVED = 0b1111_1100;++export const FIXED_HEADER_BYTES = 32;+export const DIGEST_BYTES = 32;+export const TAG_BYTES = 16;+export const SALT_BYTES = 16;+export const NONCE_PREFIX_BYTES = 8;+export const NONCE_BYTES = 12;+export const KEY_BYTES = 32;++/** Header length is fixed per flag combination in version 1, and readers require equality. */+export const HEADER_BYTES_PLAIN = 64;+export const HEADER_BYTES_ENCRYPTED = 108;++/** Default ceiling on the header, applied before anything is allocated or sought. */+export const DEFAULT_MAX_HEADER_BYTES = 4096;++export const FRAME_SIZE = 1_048_576;+export const FRAME_FINAL_FLAG = 0x8000_0000;+export const FRAME_LENGTH_MASK = 0x7fff_ffff;++/** Reserved for the verifier, so frames may use 0 through 0xFFFFFFFE. */+export const VERIFIER_COUNTER = 0xffff_ffff;+export const MAX_FRAME_COUNTER = VERIFIER_COUNTER - 1;++export const KDF_SCRYPT = 1;++/** Bounds a reader accepts for scrypt, so a crafted header cannot exhaust memory. */+export const SCRYPT_BOUNDS = {+ log2N: { min: 10, max: 20 },+ r: { min: 1, max: 16 },+ p: { min: 1, max: 8 }+} as const;++/** Recommended cost for new containers: about 300 ms and 128 MiB per derivation. */+export const SCRYPT_DEFAULTS: ScryptParams = { log2N: 17, r: 8, p: 1 };++/** Default ceiling on a single key derivation, in bytes. */+export const DEFAULT_MAX_KDF_MEMORY_BYTES = 512 * 1024 * 1024;++/** RFC 1952 "unknown" operating system, so the gzip header carries no platform hint. */+export const GZIP_OS_UNKNOWN = 255;++/** First 16 bytes of any SQLite database file. */+export const SQLITE_MAGIC = Buffer.from("SQLite format 3\0", "latin1");++/** Bytes of output needed before the SQLite header can be checked. */+export const SQLITE_HEADER_BYTES = 18;++export interface ScryptParams {+ log2N: number;+ r: number;+ p: number;+}++export interface EncryptionHeader extends ScryptParams {+ kdfId: number;+ salt: Buffer;+ noncePrefix: Buffer;+ verifierTag: Buffer;+}++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. */+ plaintextSize: number;+ headerLength: number;+ encryption: EncryptionHeader | null;+ digest: Buffer;+}++/** Header length implied by the flags, which readers require exactly. */+export function headerLengthFor(encrypted: boolean): number {+ return encrypted ? HEADER_BYTES_ENCRYPTED : HEADER_BYTES_PLAIN;+}++/**+ * 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.+ */+export function authenticatedHeaderEnd(headerLength: number): number {+ return headerLength - TAG_BYTES - DIGEST_BYTES;+}++/** Offset of the payload digest, always the last 32 bytes of the header. */+export function digestOffset(headerLength: number): number {+ return headerLength - DIGEST_BYTES;+}++/** Memory a scrypt derivation needs, which is what the reader ceiling is applied to. */+export function scryptMemoryBytes({ log2N, r }: ScryptParams): number {+ return 128 * 2 ** log2N * r;+}++/** 12-byte GCM nonce for a frame counter, or for {@link VERIFIER_COUNTER}. */+export function nonceFor(noncePrefix: Buffer, counter: number): Buffer {+ const nonce = Buffer.allocUnsafe(NONCE_BYTES);+ noncePrefix.copy(nonce, 0);+ nonce.writeUInt32LE(counter, NONCE_PREFIX_BYTES);+ return nonce;+}++/** 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);+ buffer.writeUInt16LE(header.headerLength, 22);+ buffer.writeBigUInt64LE(BigInt(header.plaintextSize), 24);++ if (header.encryption) {+ const { kdfId, log2N, r, p, salt, noncePrefix, verifierTag } = header.encryption;+ buffer.writeUInt8(kdfId, 32);+ buffer.writeUInt8(log2N, 33);+ buffer.writeUInt8(r, 34);+ buffer.writeUInt8(p, 35);+ salt.copy(buffer, 36);+ noncePrefix.copy(buffer, 52);+ verifierTag.copy(buffer, 60);+ }++ header.digest.copy(buffer, digestOffset(header.headerLength));++ return buffer;+}++export interface FixedHeader {+ version: number;+ compressed: boolean;+ encrypted: boolean;+ plaintextSize: number;+ headerLength: number;+}++/**+ * 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.");+ }++ const version = buffer.readUInt8(MAGIC.length);+ if (version === 0) {+ 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}.`);+ }++ const flags = buffer.readUInt8(21);+ if (flags & FLAG_RESERVED) {+ 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.`);+ }+ 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)}.`);+ }++ // A hint that may only ever tighten a bound, so an unrepresentable value is the same as "unknown".+ const plaintextSize = buffer.readBigUInt64LE(24);++ return {+ version,+ compressed: (flags & FLAG_COMPRESSED) !== 0,+ encrypted,+ plaintextSize: plaintextSize > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(plaintextSize),+ headerLength+ };+}++/** 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);++ let encryption: EncryptionHeader | null = null;+ if (fixed.encrypted) {+ const kdfId = buffer.readUInt8(32);+ if (kdfId !== KDF_SCRYPT) {+ throw new BackupContainerError("unsupported-kdf", `Key derivation function ${kdfId} is not supported.`);+ }++ encryption = {+ kdfId,+ log2N: buffer.readUInt8(33),+ r: buffer.readUInt8(34),+ p: buffer.readUInt8(35),+ salt: buffer.subarray(36, 52),+ noncePrefix: buffer.subarray(52, 60),+ verifierTag: buffer.subarray(60, 76)+ };+ }++ return {+ ...fixed,+ encryption,+ digest: buffer.subarray(digestOffset(fixed.headerLength), fixed.headerLength)+ };+}++/**+ * Rejects scrypt parameters that are out of bounds or too expensive.+ *+ * The memory ceiling is the protection that matters, and it is applied before the derivation runs+ * rather than caught afterwards: a crafted `log2N` of 30 would ask for more than 128 GiB.+ */+export function validateScryptParams(params: ScryptParams, maxMemoryBytes: number): void {+ 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)) {+ throw new BackupContainerError(+ "invalid-kdf-params",+ `scrypt parameters out of bounds: log2N=${params.log2N}, r=${params.r}, p=${params.p}.`+ );+ }++ const needed = scryptMemoryBytes(params);+ if (needed > maxMemoryBytes) {+ throw new BackupContainerError(+ "invalid-kdf-params",+ `scrypt would need ${needed} bytes, above the ${maxMemoryBytes} byte ceiling.`+ );+ }+}++/**+ * Checks that unwrapped output really is a SQLite database.+ *+ * @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.");+ }++ // 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.`);+ }+}diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.tsnew file mode 100644index 0000000000..3a00b5874a--- /dev/null+++ b/packages/trilium-backup-container/src/index.ts@@ -0,0 +1,62 @@+/**+ * Reader and writer for the Trilium `.tbak` 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.+ *+ * @example Writing an encrypted, compressed container+ * ```ts+ * await writeBackupContainer(createReadStream(source), createWriteStream(partial), {+ * compress: true,+ * passphrase,+ * plaintextSize: (await stat(source)).size,+ * // Reopening to patch keeps this simple. Do not hand the payload stream a FileHandle with+ * // `autoClose: false` and patch through that handle: its `close()` then waits forever on a+ * // stream that never emits `close`.+ * patchHeader: async (offset, data) => {+ * const handle = await open(partial, "r+");+ * try {+ * await handle.write(data, 0, data.length, offset);+ * await handle.sync();+ * } finally {+ * await handle.close();+ * }+ * }+ * });+ * await rename(partial, final);+ * ```+ *+ * @example Reading one back+ * ```ts+ * const info = await readBackupContainer(+ * fs.createReadStream(container),+ * fs.createWriteStream(database),+ * { passphrase }+ * );+ * ```+ *+ * @module+ */++export { BackupContainerError, type BackupContainerErrorReason, isBackupContainerError } from "./errors.js";+export {+ FORMAT_VERSION,+ FRAME_SIZE,+ SCRYPT_BOUNDS,+ SCRYPT_DEFAULTS,+ type ScryptParams+} from "./format.js";+export {+ DEFAULT_MAX_OUTPUT_BYTES,+ readBackupContainer,+ type ReadBackupContainerOptions,+ type ReadBackupContainerResult+} from "./read.js";+export {+ type PatchHeader,+ writeBackupContainer,+ type WriteBackupContainerOptions,+ type WriteBackupContainerResult+} from "./write.js";diff --git a/packages/trilium-backup-container/src/internals.spec.ts b/packages/trilium-backup-container/src/internals.spec.tsnew file mode 100644index 0000000000..19157caf9f--- /dev/null+++ b/packages/trilium-backup-container/src/internals.spec.ts@@ -0,0 +1,78 @@+import { createHash, randomBytes } from "node:crypto";+import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";+import { describe, expect, it } from "vitest";++import { ByteReader } from "./byte-reader.js";+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";++describe("BackupContainerError", () => {+ it("narrows only its own errors", () => {+ expect(isBackupContainerError(new BackupContainerError("truncated", "cut short"))).toBe(true);+ expect(isBackupContainerError(new Error("something else"))).toBe(false);+ expect(isBackupContainerError("not even an error")).toBe(false);+ });+});++describe("ByteReader", () => {+ const reader = (...chunks: Buffer[]) => new ByteReader(Readable.from(chunks));++ it("stitches exact reads across chunk boundaries and tracks the offset", async () => {+ const subject = reader(Buffer.from("abc"), Buffer.from("de"), Buffer.from("fgh"));++ expect((await subject.readExactly(4)).toString()).toBe("abcd");+ expect(subject.consumed).toBe(4);+ expect((await subject.readExactly(1)).toString()).toBe("e");+ expect((await subject.readUpTo(99)).toString()).toBe("fgh");+ expect(await subject.atEof()).toBe(true);+ });++ it("returns what is left rather than throwing, when asked for at most n", async () => {+ const subject = reader(Buffer.from("ab"));++ expect(await subject.readUpTo(0)).toHaveLength(0);+ expect((await subject.readUpTo(10)).toString()).toBe("ab");+ expect(await subject.readUpTo(10)).toHaveLength(0);+ });++ it("reports a short input as truncated", async () => {+ const subject = reader(Buffer.from("ab"));++ await expect(subject.readExactly(5)).rejects.toMatchObject({ reason: "truncated" });+ });+});++describe("FrameEncryptor", () => {+ it("refuses a payload that would need more frames than the counter can address", async () => {+ const encryptor = new FrameEncryptor(randomBytes(32), randomBytes(8), Buffer.alloc(60), 0);++ const reason = await reasonOf(+ pipeline(Readable.from([Buffer.alloc(2 * FRAME_SIZE)]), encryptor, new MemorySink())+ );++ expect(reason).toBe("payload-too-large");+ });+});++describe("deriveKey", () => {+ it("surfaces a key derivation the platform refuses", async () => {+ await expect(deriveKey("passphrase", Buffer.alloc(16), { log2N: 10, r: 0, p: 1 }))+ .rejects.toMatchObject({ reason: "invalid-kdf-params" });+ });+});++describe("compressed payload damage", () => {+ it("reports a broken gzip stream as a damaged payload, not as a digest mismatch", async () => {+ const written = await writeToBuffer(fakeDatabase(50_000), { compress: true });++ // 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);++ expect(await reasonOf(readFromBuffer(damaged))).toBe("damaged-payload");+ });+});diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.tsnew file mode 100644index 0000000000..24f23a6231--- /dev/null+++ b/packages/trilium-backup-container/src/read.ts@@ -0,0 +1,223 @@+import { createHash, timingSafeEqual } from "node:crypto";+import type { Readable, Writable } from "node:stream";+import { pipeline } from "node:stream/promises";+import { createGunzip } from "node:zlib";++import { ByteReader } from "./byte-reader.js";+import { deriveKey, openFrame, verifyPassphrase } from "./crypto.js";+import { BackupContainerError } from "./errors.js";+import {+ authenticatedHeaderEnd,+ type ContainerHeader,+ DEFAULT_MAX_HEADER_BYTES,+ DEFAULT_MAX_KDF_MEMORY_BYTES,+ decodeFixedHeader,+ decodeHeader,+ encodeHeader,+ type EncryptionHeader,+ FIXED_HEADER_BYTES,+ FRAME_FINAL_FLAG,+ FRAME_LENGTH_MASK,+ FRAME_SIZE,+ MAGIC,+ TAG_BYTES,+ validateScryptParams+} from "./format.js";+import { OutputGuard } from "./streams.js";++/** Ceiling on unwrapped output when the container does not record a smaller size. */+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. */+ maxOutputBytes?: number;+ /** Refuses a header above this size before anything is allocated. */+ maxHeaderBytes?: number;+ /** Refuses a key derivation that would need more memory than this. */+ maxKdfMemoryBytes?: number;+ /**+ * Recovery path: ignore the verifier tag and go straight to the frames.+ *+ * Useful when the verifier tag itself is the damaged part of the header, since it sits outside+ * what the frames authenticate.+ */+ skipVerifier?: boolean;+ /** Check that the output really is a SQLite database. On by default. */+ requireSqliteHeader?: boolean;+}++export interface ReadBackupContainerResult {+ version: number;+ compressed: boolean;+ encrypted: boolean;+ /** The size recorded in the header, or 0 when it was not recorded. */+ plaintextSize: number;+ /** Bytes actually written to the output. */+ bytesWritten: number;+}++/**+ * 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.+ *+ * @param input the container bytes.+ * @param output the destination for the database, which is ended by this call.+ * @param options see {@link ReadBackupContainerOptions}.+ * @returns what was read, see {@link ReadBackupContainerResult}.+ * @throws BackupContainerError with a `reason` property identifying the failure.+ */+export async function readBackupContainer(+ input: Readable,+ output: Writable,+ options: ReadBackupContainerOptions = {}+): Promise<ReadBackupContainerResult> {+ const reader = new ByteReader(input);+ const header = await readHeader(reader, options.maxHeaderBytes ?? DEFAULT_MAX_HEADER_BYTES);++ 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.");+ }++ 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);+ }+ }++ // 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+ );+ const guard = new OutputGuard(ceiling, options.requireSqliteHeader !== false);++ const payload = header.encryption && key+ ? readFrames(reader, header, header.encryption, key)+ : readPlainPayload(reader, header);++ 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.+ await pipeline(stages as any);+ } catch (error) {+ throw translatePipelineError(error);+ }++ if (header.plaintextSize > 0 && guard.bytesWritten !== header.plaintextSize) {+ throw new BackupContainerError(+ "size-mismatch",+ `Output is ${guard.bytesWritten} bytes, header records ${header.plaintextSize}.`+ );+ }++ return {+ version: header.version,+ compressed: header.compressed,+ encrypted: header.encrypted,+ plaintextSize: header.plaintextSize,+ bytesWritten: guard.bytesWritten+ };+}++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.+ 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("truncated", `File ends after ${fixedBytes.length} bytes, inside the header.`);+ }++ const fixed = decodeFixedHeader(fixedBytes, maxHeaderBytes);+ const rest = await reader.readExactly(fixed.headerLength - FIXED_HEADER_BYTES);++ return decodeHeader(Buffer.concat([fixedBytes, rest]), maxHeaderBytes);+}++/** Re-encodes the header so the authenticated span comes from the same layout the writer used. */+function aadOf(header: ContainerHeader): Buffer {+ return encodeHeader(header).subarray(0, authenticatedHeaderEnd(header.headerLength));+}++/** 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> {+ const aad = aadOf(header);+ const hash = createHash("sha256");+ let counter = 0;++ for (;;) {+ const offset = reader.consumed;+ const lengthField = await reader.readExactly(4);+ const raw = lengthField.readUInt32LE(0);+ const final = (raw & FRAME_FINAL_FLAG) !== 0;+ const length = raw & FRAME_LENGTH_MASK;++ // 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.`);+ }++ 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);++ if (final) {+ break;+ }+ counter++;+ }++ if (!(await reader.atEof())) {+ 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> {+ const hash = createHash("sha256");++ for (;;) {+ const chunk = await reader.readUpTo(FRAME_SIZE);+ if (chunk.length === 0) {+ break;+ }+ hash.update(chunk);+ yield chunk;+ }++ verifyDigest(hash.digest(), header.digest);+}++function verifyDigest(actual: Buffer, expected: Buffer): void {+ if (!timingSafeEqual(actual, expected)) {+ 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. */+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 error;+}diff --git a/packages/trilium-backup-container/src/streams.ts b/packages/trilium-backup-container/src/streams.tsnew file mode 100644index 0000000000..9cf17d5c3b--- /dev/null+++ b/packages/trilium-backup-container/src/streams.ts@@ -0,0 +1,181 @@+import { createHash, type Hash } from "node:crypto";+import { Transform, type TransformCallback } from "node:stream";++import { BackupContainerError } from "./errors.js";+import {+ FRAME_FINAL_FLAG,+ FRAME_SIZE,+ GZIP_OS_UNKNOWN,+ MAX_FRAME_COUNTER,+ SQLITE_HEADER_BYTES,+ validateSqliteHeader+} from "./format.js";+import { sealFrame } from "./crypto.js";++/** Passes bytes through untouched while hashing them, so the digest costs no extra pass. */+export class DigestTap extends Transform {+ readonly #hash: Hash = createHash("sha256");+ #bytes = 0;++ /** Payload bytes seen, i.e. the bytes the digest covers. */+ get bytesHashed(): number {+ return this.#bytes;+ }++ override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {+ this.#hash.update(chunk);+ this.#bytes += chunk.length;+ callback(null, chunk);+ }++ digest(): Buffer {+ return this.#hash.digest();+ }+}++/**+ * 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.+ */+export class GzipHeaderNormaliser extends Transform {+ #seen = 0;++ 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.+ chunk = Buffer.from(chunk);+ chunk[osByteIndex] = GZIP_OS_UNKNOWN;+ }+ this.#seen += chunk.length;+ callback(null, chunk);+ }+}++/**+ * 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.+ */+export class FrameEncryptor extends Transform {+ readonly #frame = Buffer.allocUnsafe(FRAME_SIZE);+ #filled = 0;+ #counter = 0;++ constructor(+ private readonly key: Buffer,+ private readonly noncePrefix: Buffer,+ private readonly aad: Buffer,+ /** Highest counter a frame may use. Lowered only by tests, which cannot write 4 PiB. */+ private readonly maxCounter: number = MAX_FRAME_COUNTER+ ) {+ super();+ }++ override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {+ let offset = 0;++ try {+ while (offset < chunk.length) {+ const take = Math.min(FRAME_SIZE - this.#filled, chunk.length - offset);+ chunk.copy(this.#frame, this.#filled, offset, offset + take);+ this.#filled += take;+ offset += take;++ if (this.#filled === FRAME_SIZE) {+ this.push(this.#seal(false));+ }+ }+ } catch (error) {+ callback(error as Error);+ return;+ }++ callback();+ }++ override _flush(callback: TransformCallback): void {+ try {+ callback(null, this.#seal(true));+ } catch (error) {+ callback(error as Error);+ }+ }++ #seal(final: boolean): Buffer {+ if (this.#counter > this.maxCounter) {+ 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));++ this.#counter++;+ this.#filled = 0;++ return frame;+ }+}++/**+ * Guards the unwrapped output: enforces the ceiling before bytes reach the destination, checks the+ * SQLite header as soon as enough of it has passed, and counts what was written.+ */+export class OutputGuard extends Transform {+ #written = 0;+ #head: Buffer[] = [];+ #headBytes = 0;+ #headChecked = false;++ constructor(+ private readonly ceiling: number,+ private readonly requireSqliteHeader: boolean+ ) {+ super();+ }++ get bytesWritten(): number {+ return this.#written;+ }++ 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.`));+ return;+ }+ this.#written += chunk.length;++ if (this.requireSqliteHeader && !this.#headChecked) {+ this.#head.push(chunk);+ this.#headBytes += chunk.length;++ if (this.#headBytes >= SQLITE_HEADER_BYTES) {+ this.#headChecked = true;+ try {+ validateSqliteHeader(Buffer.concat(this.#head, this.#headBytes));+ } catch (error) {+ callback(error as Error);+ return;+ }+ this.#head = [];+ }+ }++ callback(null, chunk);+ }++ 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."));+ return;+ }+ callback();+ }+}diff --git a/packages/trilium-backup-container/src/test-helpers.ts b/packages/trilium-backup-container/src/test-helpers.tsnew file mode 100644index 0000000000..7d8a6c10c9--- /dev/null+++ b/packages/trilium-backup-container/src/test-helpers.ts@@ -0,0 +1,100 @@+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";++/** Cheap scrypt cost, so the suite is not dominated by key derivation. */+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 {+ this.chunks.push(Buffer.from(chunk));+ callback();+ }++ toBuffer(): Buffer {+ return Buffer.concat(this.chunks);+ }+}++/** A byte pattern that starts with a valid SQLite header and compresses well. */+export function fakeDatabase(size = 4096, pageSize = 4096): Buffer {+ const database = Buffer.alloc(Math.max(size, 18));+ SQLITE_MAGIC.copy(database, 0);+ database.writeUInt16BE(pageSize, 16);+ database.fill("trilium notes ", 18);++ return database.subarray(0, size);+}++/** Splits a buffer so the reader and writer are exercised across chunk boundaries. */+export function chunked(data: Buffer, chunkSize: number): Readable {+ const chunks: Buffer[] = [];+ for (let offset = 0; offset < data.length; offset += chunkSize) {+ chunks.push(data.subarray(offset, offset + chunkSize));+ }++ return Readable.from(chunks.length > 0 ? chunks : [Buffer.alloc(0)]);+}++export interface WrittenContainer {+ bytes: Buffer;+ result: WriteBackupContainerResult;+ patchedAt: number[];+}++/** Writes a container in memory, applying the digest patch the way a file destination would. */+export async function writeToBuffer(+ input: Buffer | Readable,+ options: Omit<WriteBackupContainerOptions, "patchHeader"> = {}+): Promise<WrittenContainer> {+ const sink = new MemorySink();+ const patches: { offset: number; data: Buffer }[] = [];++ const result = await writeBackupContainer(+ Buffer.isBuffer(input) ? Readable.from([input]) : input,+ sink,+ { ...options, patchHeader: (offset, data) => { patches.push({ offset, data: Buffer.from(data) }); } }+ );++ const bytes = sink.toBuffer();+ for (const patch of patches) {+ patch.data.copy(bytes, patch.offset);+ }++ return { bytes, result, patchedAt: patches.map((patch) => patch.offset) };+}++export interface ReadContainer {+ bytes: Buffer;+ result: ReadBackupContainerResult;+}++export async function readFromBuffer(container: Buffer, options: ReadBackupContainerOptions = {}): Promise<ReadContainer> {+ const sink = new MemorySink();+ const result = await readBackupContainer(Readable.from([container]), sink, options);++ return { bytes: sink.toBuffer(), result };+}++/** Returns a copy with one byte flipped, for tamper tests. */+export function flipByte(data: Buffer, offset: number): Buffer {+ const copy = Buffer.from(data);+ copy[offset] ^= 0xff;++ return copy;+}++/** Runs `read` and returns the `reason` of the BackupContainerError it throws. */+export async function reasonOf(operation: Promise<unknown>): Promise<string> {+ try {+ await operation;+ } catch (error) {+ return (error as { reason?: string }).reason ?? `no reason: ${String(error)}`;+ }++ return "did not throw";+}diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.tsnew file mode 100644index 0000000000..9b868609c2--- /dev/null+++ b/packages/trilium-backup-container/src/write.ts@@ -0,0 +1,156 @@+import { randomBytes } from "node:crypto";+import type { Readable, Writable } from "node:stream";+import { pipeline } from "node:stream/promises";+import { createGzip } from "node:zlib";++import { computeVerifierTag, deriveKey } from "./crypto.js";+import { BackupContainerError } from "./errors.js";+import {+ authenticatedHeaderEnd,+ type ContainerHeader,+ DEFAULT_MAX_KDF_MEMORY_BYTES,+ DIGEST_BYTES,+ digestOffset,+ encodeHeader,+ FORMAT_VERSION,+ headerLengthFor,+ KDF_SCRYPT,+ NONCE_PREFIX_BYTES,+ SALT_BYTES,+ type ScryptParams,+ SCRYPT_DEFAULTS,+ TAG_BYTES,+ validateScryptParams+} from "./format.js";+import { DigestTap, FrameEncryptor, GzipHeaderNormaliser } from "./streams.js";++/**+ * Writes `data` at an absolute offset in the destination that is already being streamed to.+ *+ * The payload digest is only known once the payload has been written, so it is patched into the+ * header afterwards. A destination that cannot be written out of order cannot hold this format.+ */+export type PatchHeader = (offset: number, data: Buffer) => Promise<void> | void;++export interface WriteBackupContainerOptions {+ /** Patches the payload digest into the header once the payload is complete. Required. */+ patchHeader: PatchHeader;+ /** Compress the payload with gzip. */+ compress?: boolean;+ /** Encrypt the payload. Encryption is on exactly when a passphrase is given. */+ passphrase?: string;+ /** Size of the wrapped database, recorded as a hint for restore progress. Omit when unknown. */+ plaintextSize?: number;+ /** scrypt cost. Defaults to {@link SCRYPT_DEFAULTS}. */+ scrypt?: ScryptParams;+ /** Refuses a cost above this many bytes, guarding the writer's own memory. */+ maxKdfMemoryBytes?: number;+ /** zlib compression level. 6 is the speed to ratio sweet spot. */+ compressionLevel?: number;+}++export interface WriteBackupContainerResult {+ headerLength: number;+ compressed: boolean;+ encrypted: boolean;+ /** SHA-256 of the payload as stored, i.e. what was patched into the header. */+ digest: Buffer;+ /** Payload bytes written, excluding the header. */+ payloadBytes: number;+}++/**+ * Wraps a database into a container.+ *+ * The header is written first with a zeroed digest, then the payload streams through gzip and the+ * frame encryptor as configured, and finally the digest is patched into the header.+ *+ * @param input the database bytes.+ * @param output the destination, which is ended by this call.+ * @param options see {@link WriteBackupContainerOptions}; `patchHeader` is required.+ * @returns what was written, see {@link WriteBackupContainerResult}.+ * @throws BackupContainerError with `reason` set, see {@link BackupContainerErrorReason}.+ */+export async function writeBackupContainer(+ input: Readable,+ output: Writable,+ options: WriteBackupContainerOptions+): Promise<WriteBackupContainerResult> {+ if (typeof options.patchHeader !== "function") {+ 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}.`);+ }++ 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.+ const header: ContainerHeader = {+ version: FORMAT_VERSION,+ compressed,+ encrypted,+ plaintextSize,+ headerLength: headerLengthFor(encrypted),+ encryption: null,+ digest: Buffer.alloc(DIGEST_BYTES)+ };++ let key: Buffer | null = null;+ if (options.passphrase !== undefined) {+ const params = options.scrypt ?? SCRYPT_DEFAULTS;+ validateScryptParams(params, options.maxKdfMemoryBytes ?? DEFAULT_MAX_KDF_MEMORY_BYTES);++ header.encryption = {+ kdfId: KDF_SCRYPT,+ ...params,+ salt: randomBytes(SALT_BYTES),+ noncePrefix: randomBytes(NONCE_PREFIX_BYTES),+ verifierTag: Buffer.alloc(TAG_BYTES)+ };+ key = await deriveKey(options.passphrase, header.encryption.salt, params);+ }++ const headerBytes = encodeHeader(header);+ const aad = headerBytes.subarray(0, authenticatedHeaderEnd(header.headerLength));++ if (header.encryption && key) {+ computeVerifierTag(key, header.encryption.noncePrefix, aad).copy(headerBytes, authenticatedHeaderEnd(header.headerLength));+ }++ await writeChunk(output, headerBytes);++ // input -> gzip -> frames -> digest -> output, with the stages the flags call for.+ const digestTap = new DigestTap();+ const stages: (Readable | Writable)[] = [input];+ if (compressed) {+ 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.+ await pipeline(stages as any);++ const digest = digestTap.digest();+ await options.patchHeader(digestOffset(header.headerLength), digest);++ return {+ headerLength: header.headerLength,+ compressed,+ encrypted,+ digest,+ payloadBytes: digestTap.bytesHashed+ };+}++function writeChunk(stream: Writable, chunk: Buffer): Promise<void> {+ return new Promise((resolve, reject) => {+ stream.write(chunk, (error) => (error ? reject(error) : resolve()));+ });+}diff --git a/packages/trilium-backup-container/tsconfig.json b/packages/trilium-backup-container/tsconfig.jsonnew file mode 100644index 0000000000..62ebbd9464--- /dev/null+++ b/packages/trilium-backup-container/tsconfig.json@@ -0,0 +1,13 @@+{+ "extends": "../../tsconfig.base.json",+ "files": [],+ "include": [],+ "references": [+ {+ "path": "./tsconfig.lib.json"+ },+ {+ "path": "./tsconfig.spec.json"+ }+ ]+}diff --git a/packages/trilium-backup-container/tsconfig.lib.json b/packages/trilium-backup-container/tsconfig.lib.jsonnew file mode 100644index 0000000000..915b55d790--- /dev/null+++ b/packages/trilium-backup-container/tsconfig.lib.json@@ -0,0 +1,20 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "dist",+ "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo",+ "emitDeclarationOnly": false,+ "types": [+ "node"+ ]+ },+ "include": [+ "src/**/*.ts"+ ],+ "references": [],+ "exclude": [+ "vite.config.ts",+ "src/**/*.spec.ts"+ ]+}diff --git a/packages/trilium-backup-container/tsconfig.spec.json b/packages/trilium-backup-container/tsconfig.spec.jsonnew file mode 100644index 0000000000..f9bba0fa63--- /dev/null+++ b/packages/trilium-backup-container/tsconfig.spec.json@@ -0,0 +1,16 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "outDir": "./out-tsc/vitest",+ "types": [+ "node",+ "vitest"+ ]+ },+ "include": [+ "vite.config.ts",+ "src/**/*.spec.ts",+ "src/**/*.d.ts",+ "src/**/*.ts"+ ]+}diff --git a/packages/trilium-backup-container/vite.config.ts b/packages/trilium-backup-container/vite.config.tsnew file mode 100644index 0000000000..fbd6b2ba6e--- /dev/null+++ b/packages/trilium-backup-container/vite.config.ts@@ -0,0 +1,32 @@+/// <reference types='vitest' />+import { resolve } from "node:path";+import { defineConfig } from "vite";++export default defineConfig(() => ({+ root: __dirname,+ cacheDir: "../../node_modules/.vite/packages/trilium-backup-container",+ plugins: [],+ test: {+ watch: false,+ globals: true,+ environment: "node",+ include: ["src/**/*.{test,spec}.ts"],+ reporters: [+ "default",+ ["junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true }]+ ],+ coverage: {+ thresholds: {+ lines: 99,+ functions: 100,+ branches: 98,+ statements: 99+ },+ reportsDirectory: "./test-output/vitest/coverage",+ provider: "v8" as const,+ include: ["src/**/*.ts"],+ exclude: ["**/*.spec.ts", "**/*.d.ts", "src/index.ts", "src/test-helpers.ts"],+ reporter: ["text", ["lcov", { projectRoot: resolve(__dirname, "../..") }]]+ }+ }+}));diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b3052cdbe3..d91e6382a0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1382,6 +1382,8 @@ importers:specifier: 4.1.10version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ packages/trilium-backup-container: {}+packages/trilium-core:dependencies:'@braintree/sanitize-url':