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/backup container: update the file format, move the digest to the trailer, add a timestamp
Adorian Dorand9907af93bab
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.tsindex 845d0d5810..1fca6dd1b9 100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@ -11,7 +11,6 @@ import type {import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService, utils as coreUtils, ws } from "@triliumnext/core";import type { Response } from "express";import fs from "fs";-import fsp from "fs/promises";import { t } from "i18next";import path from "path";@@ -401,17 +400,7 @@ async function writeContainer(compress: format.compress,passphrase: format.passphrase ?? undefined,plaintextSize: fs.statSync(snapshot).size,- onProgress,- // The digest is only known once the payload is written, so it is patched in afterwards.- patchHeader: async (offset, data) => {- const handle = await fsp.open(partial, "r+");- try {- await handle.write(data, 0, data.length, offset);- await handle.sync();- } finally {- await handle.close();- }- }+ onProgress});// Renamed last, so a half-written container is never mistaken for a finished one.diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.tsindex 1c1a6651d2..7a6aee39ba 100644--- a/apps/server/src/services/database_restore.spec.ts+++ b/apps/server/src/services/database_restore.spec.ts@@ -2,7 +2,6 @@ import { writeBackupContainer } from "@triliumnext/backup-container";import { app_info as appInfo, getLog, getSql } from "@triliumnext/core";import Database from "better-sqlite3";import fs from "fs";-import fsp from "fs/promises";import os from "os";import path from "path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -57,15 +56,7 @@ async function containerOf(source: string, passphrase?: string, compress = falseawait writeBackupContainer(fs.createReadStream(source), fs.createWriteStream(filePath), {compress,passphrase,- plaintextSize: fs.statSync(source).size,- patchHeader: async (offset, data) => {- const handle = await fsp.open(filePath, "r+");- try {- await handle.write(data, 0, data.length, offset);- } finally {- await handle.close();- }- }+ plaintextSize: fs.statSync(source).size});return filePath;diff --git a/apps/standalone/src/lightweight/backup-download.spec.ts b/apps/standalone/src/lightweight/backup-download.spec.tsindex b78e64b379..349d8a528d 100644--- a/apps/standalone/src/lightweight/backup-download.spec.ts+++ b/apps/standalone/src/lightweight/backup-download.spec.ts@@ -1,5 +1,5 @@import { readBackupContainer } from "@triliumnext/backup-container";-import { streamedContainerSize } from "@triliumnext/backup-container/web";+import { containerSize } from "@triliumnext/backup-container/web";import { Readable, Writable } from "stream";import { afterEach, describe, expect, it, vi } from "vitest";@@ -106,7 +106,7 @@ describe("streamDatabaseDownload", () => {expect(outcome).toEqual({ status: "done" });// One format whether or not a password was given, so one extension and one restore path.expect(port.sent[0])- .toEqual({ type: "begin", byteSize: streamedContainerSize(PAGE_SIZE * PAGE_COUNT, false) });+ .toEqual({ type: "begin", byteSize: containerSize(PAGE_SIZE * PAGE_COUNT, false) });expect(port.chunks().reduce((total, chunk) => total + chunk.byteLength, 0)).toBe(port.sent[0].byteSize);expect(port.sent.at(-1)).toEqual({ type: "end" });@@ -131,7 +131,7 @@ describe("streamDatabaseDownload", () => {expect(outcome).toEqual({ status: "done" });// The announced size is what the download's Content-Length becomes, so it must be exact.const announced = port.sent[0].byteSize;- expect(announced).toBe(streamedContainerSize(PAGE_SIZE * PAGE_COUNT, true));+ expect(announced).toBe(containerSize(PAGE_SIZE * PAGE_COUNT, true));const streamed = port.chunks().reduce((total, chunk) => total + chunk.byteLength, 0);expect(streamed).toBe(announced);diff --git a/apps/standalone/src/lightweight/backup-download.ts b/apps/standalone/src/lightweight/backup-download.tsindex 5ab98b04b9..b98e230744 100644--- a/apps/standalone/src/lightweight/backup-download.ts+++ b/apps/standalone/src/lightweight/backup-download.ts@@ -1,6 +1,6 @@import {type ScryptParams,- streamedContainerSize,+ containerSize,writeBackupContainer} from "@triliumnext/backup-container/web";@@ -19,11 +19,11 @@ import { type LiveDatabaseReader, streamLiveDatabasePages } from "./backup-strea* the service worker asks for a chunk each time the download can take more, so a slow disk slows* the database reads rather than piling chunks up in a message queue.*- * The payload is the plain database, or, given a passphrase, a streamed encrypted container: the- * format's forward-only shape, whose GCM frames carry the integrity a patched-in digest cannot on- * a destination already streamed away. Compression is never used here — at these sizes it is more- * than a low-end device can afford — and either shape's exact size is known up front, which is- * what gives the download its `Content-Length` and the browser its progress bar.+ * The payload is always a container, encrypted when a passphrase is given and plain otherwise, and+ * either way its trailer carries a digest over what was written. Nothing is ever written back to,+ * which is what lets a destination like this one hold the format at all. Compression is never used+ * here, at these sizes it is more than a low-end device can afford, and leaving it off is also what+ * keeps the size exact: that is what gives the download its `Content-Length` and its progress bar.** Protocol, from the service worker's side: it receives `begin` (with the exact byte size), then* one `chunk` per `pull` it sends, then `end`; `error` may arrive at any point, and `cancel` may@@ -47,7 +47,7 @@ export interface DownloadOutcome {}export interface DownloadOptions {- /** Wraps the stream in an encrypted, streamed container. Plain database bytes otherwise. */+ /** Encrypts the container. Without one it is still a container, just an unlocked one. */passphrase?: string;/** scrypt cost override, for tests that cannot afford the production one. */scrypt?: ScryptParams;@@ -130,18 +130,18 @@ export async function streamDatabaseDownload(source = stream;// A container either way, so every backup this application writes has one shape and one- // extension. Without a passphrase it is the database with a header in front of it, held to- // the size that header records; with one, every frame is authenticated as well.+ // extension. Without a passphrase it is the database between a header and a trailer, the+ // trailer's digest vouching for it; with one, every frame is authenticated as well.const encrypted = !!options.passphrase;- port.postMessage({ type: "begin", byteSize: streamedContainerSize(byteSize, encrypted) });+ port.postMessage({ type: "begin", byteSize: containerSize(byteSize, encrypted) });await writeBackupContainer(stream,new WritableStream<Uint8Array>({ write: sendChunk }),{passphrase: options.passphrase,- streamed: true,// Never compressed: at these sizes it costs more than a low-end device can spare,- // and the browser is downloading to a disk rather than over a wire.+ // and the browser is downloading to a disk rather than over a wire. It is also what+ // keeps the size above exact, which is what gives the download a progress bar.plaintextSize: byteSize,scrypt: options.scrypt}diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.tsindex 60e4dd8d7f..4ce5a81415 100644--- a/apps/standalone/src/lightweight/database_restore.spec.ts+++ b/apps/standalone/src/lightweight/database_restore.spec.ts@@ -70,7 +70,10 @@ async function containerOf(payload: Uint8Array, options: { passphrase?: string;* The same, written front to back the way the standalone download writes one: no digest patched in* afterwards, and the plaintext size recorded, which is what makes its total length predictable.*/-async function streamedContainerOf(payload: Uint8Array, options: { passphrase?: string } = {}) {+async function streamedContainerOf(+ payload: Uint8Array,+ options: { passphrase?: string; compress?: boolean } = {}+) {const filePath = path.join(tempRoot, `streamed-${Math.random().toString(36).slice(2)}.tnbackup`);await writeBackupContainer(@@ -79,7 +82,7 @@ async function streamedContainerOf(payload: Uint8Array, options: { passphrase?:fs.createWriteStream(filePath),{streamed: true,- compress: false,+ compress: options.compress ?? false,passphrase: options.passphrase,scrypt: { log2N: 10, r: 8, p: 1 },plaintextSize: payload.length@@ -416,6 +419,20 @@ describe("a backup that cannot be restored", () => {});});+ it("does not measure a streamed container that is compressed, since its length is not stated", async () => {+ const { files, pool } = fakePool();+ const { target } = fakeTarget(pool);+ const original = databaseBytes();+ // Compresses to far less than the plaintext size the header records, so measuring the file+ // against that size would condemn a complete backup.+ const whole = await streamedContainerOf(original, { compress: true });+ expect(whole.size).toBeLessThan(original.length);++ await restoreDatabase(target, whole);++ expect(files.get(CANDIDATE_NAME)).toEqual(original);+ });+it("refuses a streamed container the file is too small to hold, without reading it", async () => {const { pool, files } = fakePool();const { target } = fakeTarget(pool);diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex 636d44edf0..cdc4fe7741 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -6,7 +6,7 @@ import {peekBackupContainer,type ProgressCallback,readBackupContainer,- streamedContainerSize+ containerSize} from "@triliumnext/backup-container/web";import {type CandidateDatabase,@@ -413,16 +413,16 @@ async function readBackupFormat(backup: Blob): Promise<{ container: boolean; enc/*** Refuses a container the file is too small to hold, before a minute of work goes into it.*- * Only a streamed one can be measured this way: it is written front to back with no compression, so- * its length follows from the size it records. Anything else is compressed, or was written by a- * writer that could revisit its own header, and its length says nothing in advance.+ * Only an uncompressed one can be measured this way: its length follows exactly from the size its+ * header records. Compression breaks the derivation, since the payload is then shorter than the+ * plaintext by a ratio nothing states in advance.*/function requireWholeContainer(container: BackupContainerInfo, size: number): void {- if (!container.streamed || container.plaintextSize <= 0) {+ if (container.compressed || container.plaintextSize <= 0) {return;}- const expected = streamedContainerSize(container.plaintextSize, container.encrypted);+ const expected = containerSize(container.plaintextSize, container.encrypted);if (size < expected) {throw incompleteBackup(size, expected);}diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.tsindex e8678b6291..dcc0ab572c 100644--- a/packages/trilium-backup-container/src/container.spec.ts+++ b/packages/trilium-backup-container/src/container.spec.ts@@ -8,7 +8,8 @@ import {FRAME_SIZE,HEADER_BYTES_ENCRYPTED,HEADER_BYTES_PLAIN,- streamedContainerSize,+ containerSize,+ TRAILER_BYTES,TAG_BYTES} from "./format.js";import { readBackupContainer, writeBackupContainer } from "./node-streams.js";@@ -51,7 +52,6 @@ describe("round trip", () => {{ ...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);@@ -81,7 +81,7 @@ describe("round trip", () => {Buffer.alloc(0),{ passphrase: PASSPHRASE, scrypt: FAST_SCRYPT });- expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + FRAME_OVERHEAD);+ expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + FRAME_OVERHEAD + TRAILER_BYTES);const read = await readFromBuffer(written.bytes,@@ -101,14 +101,14 @@ describe("round trip", () => {});describe("payload digest", () => {- it("is the SHA-256 of the payload as stored, patched in after the payload", async () => {+ it("is the SHA-256 of the payload as stored, written into the trailer after it", 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);+ const payload = written.bytes.subarray(HEADER_BYTES_ENCRYPTED, -TRAILER_BYTES);+ const stored = written.bytes.subarray(-TRAILER_BYTES, -TRAILER_BYTES + 32);expect(stored.equals(createHash("sha256").update(payload).digest())).toBe(true);expect(Buffer.from(written.result.digest).equals(stored)).toBe(true);@@ -117,7 +117,7 @@ describe("payload digest", () => {it("catches damage to an unencrypted payload", async () => {const written = await writeToBuffer(fakeDatabase(4096));- const damaged = flipByte(written.bytes, written.bytes.length - 5);+ const damaged = flipByte(written.bytes, written.bytes.length - TRAILER_BYTES - 5);expect(await failureOf(damaged)).toBe("digest-mismatch");});@@ -127,7 +127,7 @@ 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);+ const payload = written.bytes.subarray(HEADER_BYTES_PLAIN, -TRAILER_BYTES);expect(payload.readUInt16BE(0)).toBe(0x1f8b);expect(payload.readUInt8(3)).toBe(0); // no FNAME, no FEXTRA@@ -146,7 +146,7 @@ describe("canonical framing", () => {);const fullFrames = 2 * (FRAME_SIZE + FRAME_OVERHEAD);- expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + fullFrames + FRAME_OVERHEAD);+ expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + fullFrames + FRAME_OVERHEAD + TRAILER_BYTES);const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });expect(read.bytes.equals(database)).toBe(true);@@ -161,6 +161,7 @@ describe("canonical framing", () => {expect(written.bytes).toHaveLength(HEADER_BYTES_ENCRYPTED + (FRAME_SIZE + FRAME_OVERHEAD) + (1_000 + FRAME_OVERHEAD)+ + TRAILER_BYTES);});});@@ -221,7 +222,7 @@ describe("damage and tampering", () => {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+ const damaged = flipByte(written.bytes, 73); // inside the verifier tag, bytes 68 to 83expect(await failureOf(damaged, { passphrase: PASSPHRASE })).toBe("wrong-passphrase-or-damaged-header");@@ -236,7 +237,7 @@ describe("damage and tampering", () => {it("rejects a flipped bit in the salt, which no recovery can undo", async () => {const written = await encrypted();- const damaged = flipByte(written.bytes, 40);+ const damaged = flipByte(written.bytes, 48);const reason = await failureOf(damaged, { passphrase: PASSPHRASE, skipVerifier: true });@@ -324,7 +325,7 @@ describe("peeking at a container", () => {expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES))).toEqual({version: 1,plaintextSize: 9_000,- streamed: false,+ timestamp: expect.any(Number),...expected});});@@ -339,7 +340,7 @@ describe("peeking at a container", () => {[ "fewer bytes than a header", Buffer.alloc(20) ],[ "something that is not a container", Buffer.alloc(64, 9) ],[ "a version it does not know", tamper((bytes) => bytes.writeUInt8(2, 20)) ],- [ "a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b1000, 21)) ]+ [ "a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b100, 29)) ]])("answers null for %s, so one bad file cannot derail a listing", (_label, bytes) => {expect(peekBackupContainer(bytes)).toBeNull();});@@ -349,7 +350,7 @@ function tamper(mutate: (bytes: Buffer) => void): Buffer {const header = Buffer.alloc(FIXED_HEADER_BYTES);Buffer.from("Trilium Notes Backup", "ascii").copy(header, 0);header.writeUInt8(1, 20);- header.writeUInt16LE(64, 22);+ header.writeUInt16LE(40, 30);mutate(header);return header;@@ -392,7 +393,7 @@ describe("output bounds", () => {{ compress: true, plaintextSize: database.length });const tightened = Buffer.from(written.bytes);- tightened.writeBigUInt64LE(1_000n, 24);+ tightened.writeBigUInt64LE(1_000n, 32);expect(await failureOf(tightened)).toBe("output-too-large");});@@ -400,7 +401,7 @@ describe("output bounds", () => {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);+ crafted.writeBigUInt64LE(2n ** 63n, 32);expect(await failureOf(crafted, { maxOutputBytes: 1_000 })).toBe("output-too-large");});@@ -409,7 +410,7 @@ describe("output bounds", () => {const database = fakeDatabase(4096);const written = await writeToBuffer(database, { plaintextSize: database.length });const lying = Buffer.from(written.bytes);- lying.writeBigUInt64LE(5_000n, 24);+ lying.writeBigUInt64LE(5_000n, 32);expect(await failureOf(lying)).toBe("size-mismatch");});@@ -432,83 +433,23 @@ describe("SQLite check", () => {});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 failureOf(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"));-- const read = readBackupContainer(Readable.from([ written.bytes ]), failing);-- await expect(read).rejects.toThrow(/ENOSPC/);+ it("rejects a plaintext size that is not a non-negative safe integer", async () => {+ expect(await reasonOf(writeToBuffer(fakeDatabase(), { plaintextSize: -1 })))+ .toBe("invalid-options");});});-describe("streamed containers", () => {- const STREAMED: WriteOptions = { streamed: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT };+describe("forward-only writing", () => {+ const FORWARD: WriteOptions = { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT };- it("writes front to back, sized exactly as stated, and reads back on both runtimes", async () => {+ it("is sized exactly as derived, and reads back on both runtimes", async () => {const database = fakeDatabase(64 * 1024);- const written = await writeToBuffer(database, { ...STREAMED, plaintextSize: database.length });-- // No patch was asked of the destination, and none was needed.- expect(written.patchedAt).toEqual([]);- expect(written.bytes.length).toBe(streamedContainerSize(database.length, true));- // The digest field stays zeros, which is what "no digest" looks like in the header.- expect(written.bytes.subarray(HEADER_BYTES_ENCRYPTED - 32, HEADER_BYTES_ENCRYPTED)- .every((byte) => byte === 0)).toBe(true);+ const written = await writeToBuffer(database, { ...FORWARD, plaintextSize: database.length });++ // Nothing was written back to: what the sink received in order is the whole file.+ expect(written.bytes.length).toBe(containerSize(database.length, true));expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES)))- .toMatchObject({ encrypted: true, streamed: true, compressed: false });+ .toMatchObject({ encrypted: true, compressed: false });const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });expect(read.bytes.equals(database)).toBe(true);@@ -519,29 +460,30 @@ describe("streamed containers", () => {it("sizes a payload that is an exact multiple of the frame size, empty final frame included", async () => {const database = fakeDatabase(FRAME_SIZE);- const written = await writeToBuffer(database, STREAMED);+ const written = await writeToBuffer(database, FORWARD);- expect(written.bytes.length).toBe(streamedContainerSize(FRAME_SIZE, true));+ expect(written.bytes.length).toBe(containerSize(FRAME_SIZE, true));const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });expect(read.bytes.equals(database)).toBe(true);});- it("still catches tampering: the frames authenticate what the digest no longer covers", async () => {+ it("catches tampering through the frames as well as the digest", async () => {const database = fakeDatabase(64 * 1024);- const written = await writeToBuffer(database, STREAMED);+ const written = await writeToBuffer(database, FORWARD);const tampered = flipByte(written.bytes, HEADER_BYTES_ENCRYPTED + 4 + 100);expect(await failureOf(tampered, { passphrase: PASSPHRASE })).toBe("damaged-payload");});- it("writes and reads one without a passphrase, held together by its recorded size", async () => {+ it("writes and reads a container with neither compression nor encryption", async () => {+ // The case with nothing else standing behind it: the trailer's digest is the whole of its+ // integrity, and it is there because no writer has to seek to produce one any more.const database = fakeDatabase(64 * 1024);- const written = await writeToBuffer(database, { streamed: true, plaintextSize: database.length });+ const written = await writeToBuffer(database, { plaintextSize: database.length });- expect(written.patchedAt).toEqual([]);- expect(written.bytes.length).toBe(streamedContainerSize(database.length, false));+ expect(written.bytes.length).toBe(containerSize(database.length, false));expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES)))- .toMatchObject({ encrypted: false, streamed: true, compressed: false });+ .toMatchObject({ encrypted: false, compressed: false });expect((await readFromBuffer(written.bytes)).bytes.equals(database)).toBe(true);expect((await readFromBufferWeb(written.bytes)).bytes.equals(database)).toBe(true);@@ -549,16 +491,18 @@ describe("streamed containers", () => {it("catches a truncated unencrypted one, which is what a broken download leaves", async () => {const database = fakeDatabase(64 * 1024);- const written = await writeToBuffer(database, { streamed: true, plaintextSize: database.length });+ const written = await writeToBuffer(database, { plaintextSize: database.length });- // The digest is gone, so the recorded size is what stands between a half-written- // download and a restore that trusts it.+ // Cutting the end takes the trailer with it, so what is left cannot even claim a digest.expect(await failureOf(written.bytes.subarray(0, written.bytes.length - 1024)))- .toBe("size-mismatch");+ .toBe("digest-mismatch");});- it("refuses to write an unencrypted streamed container that states no size", async () => {- expect(await reasonOf(writeToBuffer(fakeDatabase(), { streamed: true })))- .toBe("invalid-options");+ it("records the length it actually wrote, whatever it was told in advance", async () => {+ const database = fakeDatabase(64 * 1024);+ // Told nothing: the trailer still states the size, counted as the payload went past.+ const written = await writeToBuffer(database, {});++ expect((await readFromBuffer(written.bytes)).result.bytesWritten).toBe(database.length);});});diff --git a/packages/trilium-backup-container/src/cross-backend.spec.ts b/packages/trilium-backup-container/src/cross-backend.spec.tsindex 1c14c75299..f801802005 100644--- a/packages/trilium-backup-container/src/cross-backend.spec.ts+++ b/packages/trilium-backup-container/src/cross-backend.spec.ts@@ -3,7 +3,7 @@ import { gunzipSync } from "node:zlib";import { afterEach, describe, expect, it, vi } from "vitest";import { webBackend } from "./backend-web.js";-import { FRAME_SIZE, HEADER_BYTES_PLAIN } from "./format.js";+import { FRAME_SIZE, HEADER_BYTES_PLAIN, TRAILER_BYTES } from "./format.js";import {failureOfWeb,fakeDatabase,@@ -119,7 +119,7 @@ describe("web gzip canonical form", () => {it("normalises MTIME and the OS byte whatever the platform compressor emits", async () => {const database = fakeDatabase(5_000);const written = await writeToBufferWeb(database, { compress: true });- const payload = written.bytes.subarray(HEADER_BYTES_PLAIN);+ const payload = written.bytes.subarray(HEADER_BYTES_PLAIN, -TRAILER_BYTES);expect(payload.readUInt16BE(0)).toBe(0x1f8b);expect(payload.readUInt32LE(4)).toBe(0); // MTIME, so no timestamp leaks@@ -144,7 +144,7 @@ describe("web failure reasons", () => {it("recovers with skipVerifier 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+ const damaged = flipByte(written.bytes, 73); // inside the verifier tag, bytes 68 to 83const recovered = await readFromBufferWeb(damaged,@@ -176,17 +176,15 @@ describe("web failure reasons", () => {// Corrupt the deflate data, then repair the digest so the failure can only come from the// decoder.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, -TRAILER_BYTES)).digest()+ .copy(damaged, damaged.length - TRAILER_BYTES);expect(await failureOfWeb(damaged)).toBe("damaged-payload");});it("surfaces a digest mismatch through the decompressor untranslated", async () => {const written = await writeToBuffer(fakeDatabase(50_000), { compress: true });- const damaged = flipByte(written.bytes, HEADER_BYTES_PLAIN - 5); // inside the digest+ const damaged = flipByte(written.bytes, written.bytes.length - TRAILER_BYTES + 5); // in the digestexpect(await failureOfWeb(damaged)).toBe("digest-mismatch");});diff --git a/packages/trilium-backup-container/src/file-destination.spec.ts b/packages/trilium-backup-container/src/file-destination.spec.tsindex c102968eb8..bdf987691d 100644--- a/packages/trilium-backup-container/src/file-destination.spec.ts+++ b/packages/trilium-backup-container/src/file-destination.spec.ts@@ -19,7 +19,7 @@ describe("file destination", () => {await rm(directory, { recursive: true, force: true });});- it("writes to a file, patches the digest, and reads back byte for byte", async () => {+ it("writes to a file in one pass and reads back byte for byte", async () => {const database = fakeDatabase(3 * 1024 * 1024);const source = join(directory, "document.db");const partial = join(directory, "backup.part");@@ -32,19 +32,10 @@ describe("file destination", () => {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();- }- }+ plaintextSize: (await stat(source)).size});- expect(result).toMatchObject({ headerLength: 108, compressed: true, encrypted: true });+ expect(result).toMatchObject({ headerLength: 84, compressed: true, encrypted: true });await rename(partial, container);expect((await stat(container)).size).toBeLessThan(database.length);diff --git a/packages/trilium-backup-container/src/format.spec.ts b/packages/trilium-backup-container/src/format.spec.tsindex cc6266b3af..adedb2ae0f 100644--- a/packages/trilium-backup-container/src/format.spec.ts+++ b/packages/trilium-backup-container/src/format.spec.ts@@ -3,12 +3,14 @@ import { describe, expect, it } from "vitest";import { BackupContainerError } from "./errors.js";import {authenticatedHeaderEnd,+ containerSize,type ContainerHeader,decodeFixedHeader,decodeHeader,+ decodeTrailer,DEFAULT_MAX_HEADER_BYTES,- digestOffset,encodeHeader,+ encodeTrailer,FIXED_HEADER_BYTES,HEADER_BYTES_ENCRYPTED,HEADER_BYTES_PLAIN,@@ -16,20 +18,22 @@ import {nonceFor,SQLITE_MAGIC,scryptMemoryBytes,+ TRAILER_BYTES,validateScryptParams,validateSqliteHeader} from "./format.js";+const TIMESTAMP = 1_700_000_000_000;+function plainHeader(overrides: Partial<ContainerHeader> = {}): ContainerHeader {return {version: 1,+ timestamp: TIMESTAMP,compressed: true,encrypted: false,- streamed: false,plaintextSize: 4096,headerLength: HEADER_BYTES_PLAIN,encryption: null,- digest: Buffer.alloc(32, 7),...overrides};}@@ -37,6 +41,7 @@ function plainHeader(overrides: Partial<ContainerHeader> = {}): ContainerHeaderfunction encryptedHeader(): ContainerHeader {return {version: 1,+ timestamp: TIMESTAMP,compressed: false,encrypted: true,plaintextSize: 123456789,@@ -49,8 +54,7 @@ function encryptedHeader(): ContainerHeader {salt: Buffer.alloc(16, 1),noncePrefix: Buffer.alloc(8, 2),verifierTag: Buffer.alloc(16, 3)- },- digest: Buffer.alloc(32, 4)+ }};}@@ -58,36 +62,36 @@ describe("header layout", () => {it("round-trips an unencrypted header and matches the documented offsets", () => {const bytes = Buffer.from(encodeHeader(plainHeader()));- expect(bytes).toHaveLength(64);+ expect(bytes).toHaveLength(40);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);+ expect(bytes.readBigUInt64LE(21)).toBe(BigInt(TIMESTAMP));+ expect(bytes.readUInt8(29)).toBe(0b01);+ expect(bytes.readUInt16LE(30)).toBe(40);+ expect(bytes.readBigUInt64LE(32)).toBe(4096n);const decoded = decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES);expect(decoded).toMatchObject({version: 1,+ timestamp: TIMESTAMP,compressed: true,encrypted: false,plaintextSize: 4096});expect(decoded.encryption).toBeNull();- expect(Buffer.from(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", () => {+ it("round-trips an encrypted header, with the verifier tag as its last field", () => {const header = encryptedHeader();const bytes = Buffer.from(encodeHeader(header));- expect(bytes).toHaveLength(108);- expect(bytes.readUInt8(21)).toBe(0b10);- expect(bytes.readUInt8(32)).toBe(KDF_SCRYPT);- const params = [ bytes.readUInt8(33), bytes.readUInt8(34), bytes.readUInt8(35) ];+ expect(bytes).toHaveLength(84);+ expect(bytes.readUInt8(29)).toBe(0b10);+ expect(bytes.readUInt8(40)).toBe(KDF_SCRYPT);+ const params = [ bytes.readUInt8(41), bytes.readUInt8(42), bytes.readUInt8(43) ];expect(params).toEqual([ 17, 8, 1 ]);- expect(authenticatedHeaderEnd(108)).toBe(60);- expect(digestOffset(108)).toBe(76);+ // Everything up to the tag is authenticated, the timestamp with it.+ expect(authenticatedHeaderEnd(84)).toBe(68);const decoded = decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES);expect(decoded.encryption).toMatchObject({ kdfId: KDF_SCRYPT, log2N: 17, r: 8, p: 1 });@@ -98,13 +102,53 @@ describe("header layout", () => {expect(decoded.plaintextSize).toBe(123456789);});- it("treats an unrepresentable plaintext size as unknown, so it can never widen a bound", () => {+ it("treats an unrepresentable plaintext size or timestamp as unknown", () => {+ // Neither may widen a bound or be shown as a date, so both read as "not stated".const bytes = Buffer.from(encodeHeader(plainHeader()));- bytes.writeBigUInt64LE(2n ** 63n, 24);+ bytes.writeBigUInt64LE(2n ** 63n, 32);+ bytes.writeBigUInt64LE(2n ** 63n, 21);++ const decoded = decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES);+ expect(decoded.plaintextSize).toBe(0);+ expect(decoded.timestamp).toBe(0);+ });+});++describe("trailer", () => {+ it("round-trips the digest and the length the payload came to", () => {+ const digest = Buffer.alloc(32, 9);+ const bytes = Buffer.from(encodeTrailer({ digest, plaintextSize: 987654321 }));- expect(decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES).plaintextSize).toBe(0);+ expect(bytes).toHaveLength(TRAILER_BYTES);+ expect(bytes).toHaveLength(40);++ const decoded = decodeTrailer(bytes);+ expect(Buffer.from(decoded.digest)).toEqual(digest);+ expect(decoded.plaintextSize).toBe(987654321);});+ it("refuses anything that is not exactly a trailer, which is what a short file leaves", () => {+ expect(() => decodeTrailer(Buffer.alloc(TRAILER_BYTES - 1)))+ .toThrow(expect.objectContaining({ reason: "truncated" }) as Error);+ });+});++describe("derived container size", () => {+ it("counts the header, the payload and the trailer", () => {+ expect(containerSize(4096, false)).toBe(HEADER_BYTES_PLAIN + 4096 + TRAILER_BYTES);+ });++ it("counts every frame's length field and tag when encrypted, the empty final one included", () => {+ // An exact multiple of the frame size still ends with an empty final frame.+ const oneFrame = 1_048_576;+ expect(containerSize(oneFrame, true))+ .toBe(HEADER_BYTES_ENCRYPTED + oneFrame + 2 * 20 + TRAILER_BYTES);+ expect(containerSize(oneFrame + 1, true))+ .toBe(HEADER_BYTES_ENCRYPTED + oneFrame + 1 + 2 * 20 + TRAILER_BYTES);+ });+});++describe("nonces", () => {it("builds a distinct 12-byte nonce per counter", () => {const prefix = Buffer.alloc(8, 9);@@ -133,12 +177,12 @@ describe("fixed header validation", () => {[ "a newer version", (bytes: Buffer) => bytes.writeUInt8(2, 20), "unsupported-version" ],["a reserved flag bit",- (bytes: Buffer) => bytes.writeUInt8(0b1000, 21),+ (bytes: Buffer) => bytes.writeUInt8(0b100, 29),"unsupported-flags"],["a header length that does not match the flags",- (bytes: Buffer) => bytes.writeUInt16LE(65, 22),+ (bytes: Buffer) => bytes.writeUInt16LE(41, 30),"invalid-header-length"]])("rejects %s", (_label, mutate, reason) => {@@ -146,7 +190,7 @@ describe("fixed header validation", () => {});it("rejects a header above the ceiling before anything else", () => {- expect(decode((bytes) => bytes.writeUInt16LE(4000, 22), 128)).toThrow(+ expect(decode((bytes) => bytes.writeUInt16LE(4000, 30), 128)).toThrow(expect.objectContaining({ reason: "invalid-header-length" }) as Error);});@@ -154,17 +198,17 @@ describe("fixed header validation", () => {it("accepts the exact length each flag combination requires", () => {const lengthOf = (header: ContainerHeader) =>decodeFixedHeader(- encodeHeader(header).subarray(0, 32),+ encodeHeader(header).subarray(0, FIXED_HEADER_BYTES),DEFAULT_MAX_HEADER_BYTES).headerLength;- expect(lengthOf(plainHeader())).toBe(64);- expect(lengthOf(encryptedHeader())).toBe(108);+ expect(lengthOf(plainHeader())).toBe(HEADER_BYTES_PLAIN);+ expect(lengthOf(encryptedHeader())).toBe(HEADER_BYTES_ENCRYPTED);});it("rejects a KDF id it does not implement", () => {const bytes = Buffer.from(encodeHeader(encryptedHeader()));- bytes.writeUInt8(2, 32);+ bytes.writeUInt8(2, 40);expect(() => decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES)).toThrow(expect.objectContaining({ reason: "unsupported-kdf" }) as Errordiff --git a/packages/trilium-backup-container/src/format.ts b/packages/trilium-backup-container/src/format.tsindex fcb0ada018..16901656a0 100644--- a/packages/trilium-backup-container/src/format.ts+++ b/packages/trilium-backup-container/src/format.ts@@ -18,29 +18,32 @@ export const FORMAT_VERSION = 1;export const FLAG_COMPRESSED = 0b0000_0001;export const FLAG_ENCRYPTED = 0b0000_0010;-/**- * Written front to back, with no payload digest: the destination could not be revisited to patch- * one in — a download already on its way to the user, for instance.- *- * What stands in for the digest depends on the other flags. Encrypted, every frame carries its own- * authentication tag, which covers each payload byte. Unencrypted, the recorded plaintext size is- * the check: the reader refuses output that does not measure exactly that, which is what a- * truncated download looks like. A streamed container therefore always records its size.- */-export const FLAG_STREAMED = 0b0000_0100;-export const FLAG_RESERVED = 0b1111_1000;+export const FLAG_RESERVED = 0b1111_1100;-export const FIXED_HEADER_BYTES = 32;+export const FIXED_HEADER_BYTES = 40;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;+export const TIMESTAMP_BYTES = 8;+export const SIZE_BYTES = 8;-/** 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;+/** Header length is fixed per flag combination, and readers require equality. */+export const HEADER_BYTES_PLAIN = 40;+export const HEADER_BYTES_ENCRYPTED = 84;++/**+ * What follows the payload: the digest over it, and the length it actually came to.+ *+ * Both are only knowable once the payload has been written, which is why they sit at the end rather+ * than in the header. Nothing in a container therefore has to be written back to, so any writer can+ * produce one in a single forward pass, and every container carries a digest whatever its flags+ * say, including the plain uncompressed unencrypted one, which would otherwise have nothing at all+ * standing behind its contents.+ */+export const TRAILER_BYTES = DIGEST_BYTES + SIZE_BYTES;/** Default ceiling on the header, applied before anything is allocated or sought. */export const DEFAULT_MAX_HEADER_BYTES = 4096;@@ -92,18 +95,38 @@ export interface EncryptionHeader extends ScryptParams {export interface ContainerHeader {version: number;+ /**+ * When the backup was taken, in milliseconds since the Unix epoch, or `0` when not recorded.+ *+ * Stated in the clear so that a directory of backups can be dated without opening any of them,+ * and without depending on a filesystem timestamp that copying does not preserve.+ */+ timestamp: number;compressed: boolean;encrypted: boolean;- /** Written front to back, so the digest field holds zeros. See {@link FLAG_STREAMED}. */- streamed: boolean;/*** Size of the wrapped database before compression, or 0 when unknown. A hint, never an- * instruction.+ * instruction: the authoritative figure is the one the trailer records once the payload is+ * written. This one is here for what has to be known in advance, such as the length of a+ * download or a progress bar to draw against.*/plaintextSize: number;headerLength: number;encryption: EncryptionHeader | null;+}++/**+ * What follows the payload, once there is a payload to describe. See {@link TRAILER_BYTES}.+ *+ * Not covered by anything the header authenticates, for the same reason the digest never was: it is+ * written after the fact. In an encrypted container the frames already make tampering detectable,+ * and here the digest does what it has always done, which is catch bit rot and truncation.+ */+export interface ContainerTrailer {+ /** SHA-256 over the payload exactly as stored. */digest: Uint8Array;+ /** The plaintext length as counted while writing, which the reader holds the output to. */+ plaintextSize: number;}/** Header length implied by the flags, which readers require exactly. */@@ -114,17 +137,12 @@ 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 is the last field of the header and is written once the key exists, so it cannot+ * be inside what it authenticates. Stopping here also keeps a bit flip in the verifier tag from+ * invalidating every frame in the file. Everything before it, the timestamp included, is covered.*/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;+ return headerLength - TAG_BYTES;}/** Memory a scrypt derivation needs, which is what the reader ceiling is applied to. */@@ -140,43 +158,65 @@ export function nonceFor(noncePrefix: Uint8Array, counter: number): Uint8Array {return nonce;}-/**- * Serialises a header. The digest is written as supplied, so a writer passes zeros and patches- * later.- */+/** Serialises a header. Every field is known before the payload, so nothing is patched in later. */export function encodeHeader(header: ContainerHeader): Uint8Array {const buffer = new Uint8Array(header.headerLength);buffer.set(MAGIC, 0);buffer[MAGIC.length] = header.version;+ writeU64LE(buffer, 21, BigInt(header.timestamp));const compressed = header.compressed ? FLAG_COMPRESSED : 0;const encrypted = header.encrypted ? FLAG_ENCRYPTED : 0;- const streamed = header.streamed ? FLAG_STREAMED : 0;- buffer[21] = compressed | encrypted | streamed;- writeU16LE(buffer, 22, header.headerLength);- writeU64LE(buffer, 24, BigInt(header.plaintextSize));+ buffer[29] = compressed | encrypted;+ writeU16LE(buffer, 30, header.headerLength);+ writeU64LE(buffer, 32, BigInt(header.plaintextSize));if (header.encryption) {const { kdfId, log2N, r, p, salt, noncePrefix, verifierTag } = header.encryption;- buffer[32] = kdfId;- buffer[33] = log2N;- buffer[34] = r;- buffer[35] = p;- buffer.set(salt, 36);- buffer.set(noncePrefix, 52);- buffer.set(verifierTag, 60);+ buffer[40] = kdfId;+ buffer[41] = log2N;+ buffer[42] = r;+ buffer[43] = p;+ buffer.set(salt, 44);+ buffer.set(noncePrefix, 60);+ buffer.set(verifierTag, 68);}- buffer.set(header.digest, digestOffset(header.headerLength));+ return buffer;+}++/** Serialises the trailer, which is written once the payload is complete. */+export function encodeTrailer(trailer: ContainerTrailer): Uint8Array {+ const buffer = new Uint8Array(TRAILER_BYTES);++ buffer.set(trailer.digest, 0);+ writeU64LE(buffer, DIGEST_BYTES, BigInt(trailer.plaintextSize));return buffer;}+/** Parses the trailer out of exactly {@link TRAILER_BYTES} bytes. */+export function decodeTrailer(buffer: Uint8Array): ContainerTrailer {+ if (buffer.length !== TRAILER_BYTES) {+ throw new BackupContainerError(+ "truncated",+ `Trailer is ${buffer.length} bytes, expected ${TRAILER_BYTES}.`+ );+ }++ const plaintextSize = readU64LE(buffer, DIGEST_BYTES);++ return {+ digest: buffer.subarray(0, DIGEST_BYTES),+ plaintextSize: plaintextSize > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(plaintextSize)+ };+}+export interface FixedHeader {version: number;+ timestamp: number;compressed: boolean;encrypted: boolean;- streamed: boolean;plaintextSize: number;headerLength: number;}@@ -207,7 +247,7 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F);}- const flags = buffer[21];+ const flags = buffer[29];if (flags & FLAG_RESERVED) {throw new BackupContainerError("unsupported-flags",@@ -215,9 +255,8 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F);}const encrypted = (flags & FLAG_ENCRYPTED) !== 0;- const streamed = (flags & FLAG_STREAMED) !== 0;- const headerLength = readU16LE(buffer, 22);+ const headerLength = readU16LE(buffer, 30);if (headerLength > maxHeaderBytes) {throw new BackupContainerError("invalid-header-length",@@ -233,37 +272,40 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F}// A hint that may only ever tighten a bound, so an unrepresentable value is the same as- // "unknown".- const plaintextSize = readU64LE(buffer, 24);+ // "unknown". The same goes for a date nothing could have produced.+ const plaintextSize = readU64LE(buffer, 32);+ const timestamp = readU64LE(buffer, 21);return {version,+ timestamp: timestamp > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(timestamp),compressed: (flags & FLAG_COMPRESSED) !== 0,encrypted,- streamed,plaintextSize: plaintextSize > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(plaintextSize),headerLength};}/**- * Exact byte length of a streamed, uncompressed container wrapping `plaintextSize` bytes.+ * Exact byte length of an uncompressed container wrapping `plaintextSize` bytes.*- * Encrypted, that is the header, the payload, and the length field and tag around every frame —- * including the final frame, which is empty when the payload is an exact multiple of the frame- * size. Unencrypted, the payload is written as it stands and only the header precedes it.+ * Encrypted, that is the header, the payload, the length field and tag around every frame including+ * the final one, which is empty when the payload is an exact multiple of the frame size, and the+ * trailer. Unencrypted, the payload is written as it stands between the header and the trailer.*- * Exactness is the point: a download that states its size correctly is one the browser can draw a- * progress bar for.+ * Exactness is the point twice over: a download that states its size correctly is one the browser+ * can draw a progress bar for, and a file that does not measure this much is one a reader can+ * refuse before reading any of it. Compression breaks the derivation, since the payload is then+ * shorter than the plaintext by a ratio nothing states in advance.*/-export function streamedContainerSize(plaintextSize: number, encrypted: boolean): number {+export function containerSize(plaintextSize: number, encrypted: boolean): number {if (!encrypted) {- return HEADER_BYTES_PLAIN + plaintextSize;+ return HEADER_BYTES_PLAIN + plaintextSize + TRAILER_BYTES;}const frames = Math.floor(plaintextSize / FRAME_SIZE) + 1;- return HEADER_BYTES_ENCRYPTED + plaintextSize + frames * (4 + TAG_BYTES);+ return HEADER_BYTES_ENCRYPTED + plaintextSize + frames * (4 + TAG_BYTES) + TRAILER_BYTES;}/**@@ -275,7 +317,7 @@ export function decodeHeader(buffer: Uint8Array, maxHeaderBytes: number): Contailet encryption: EncryptionHeader | null = null;if (fixed.encrypted) {- const kdfId = buffer[32];+ const kdfId = buffer[40];if (kdfId !== KDF_SCRYPT) {throw new BackupContainerError("unsupported-kdf",@@ -285,20 +327,16 @@ export function decodeHeader(buffer: Uint8Array, maxHeaderBytes: number): Contaiencryption = {kdfId,- log2N: buffer[33],- r: buffer[34],- p: buffer[35],- salt: buffer.subarray(36, 52),- noncePrefix: buffer.subarray(52, 60),- verifierTag: buffer.subarray(60, 76)+ log2N: buffer[41],+ r: buffer[42],+ p: buffer[43],+ salt: buffer.subarray(44, 60),+ noncePrefix: buffer.subarray(60, 68),+ verifierTag: buffer.subarray(68, 84)};}- return {- ...fixed,- encryption,- digest: buffer.subarray(digestOffset(fixed.headerLength), fixed.headerLength)- };+ return { ...fixed, encryption };}/**diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.tsindex 538db6af49..0b17cf7eaa 100644--- a/packages/trilium-backup-container/src/index.ts+++ b/packages/trilium-backup-container/src/index.ts@@ -57,7 +57,11 @@ export {SCRYPT_BOUNDS,SCRYPT_DEFAULTS,type ScryptParams,- streamedContainerSize+ containerSize,+ type ContainerTrailer,+ decodeTrailer,+ encodeTrailer,+ TRAILER_BYTES} from "./format.js";export { readBackupContainer, writeBackupContainer } from "./node-streams.js";export {@@ -73,7 +77,6 @@ export {type ReadBackupContainerResult} from "./read.js";export {- type PatchHeader,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.tsindex 2cbaf0215c..622b56367a 100644--- a/packages/trilium-backup-container/src/internals.spec.ts+++ b/packages/trilium-backup-container/src/internals.spec.ts@@ -6,7 +6,7 @@ import { nodeBackend } from "./backend-node.js";import { deriveContainerKey } from "./backend.js";import { ByteReader } from "./byte-reader.js";import { BackupContainerError, isBackupContainerError } from "./errors.js";-import { FRAME_SIZE, HEADER_BYTES_PLAIN } from "./format.js";+import { FRAME_SIZE, HEADER_BYTES_PLAIN, TRAILER_BYTES } from "./format.js";import {fakeDatabase,failureOf,@@ -93,19 +93,18 @@ 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.+ // Corrupt the deflate data, then repair the trailer's digest over it, 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, -TRAILER_BYTES)).digest()+ .copy(damaged, damaged.length - TRAILER_BYTES);expect(await failureOf(damaged)).toBe("damaged-payload");});it("surfaces a digest mismatch through the decompressor untranslated", async () => {const written = await writeToBuffer(fakeDatabase(50_000), { compress: true });- const damaged = flipByte(written.bytes, HEADER_BYTES_PLAIN - 5); // inside the digest+ const damaged = flipByte(written.bytes, written.bytes.length - TRAILER_BYTES + 5); // in the digestexpect(await failureOf(damaged)).toBe("digest-mismatch");});diff --git a/packages/trilium-backup-container/src/progress.spec.ts b/packages/trilium-backup-container/src/progress.spec.tsindex aa8dbc3bb8..5a76b1ef93 100644--- a/packages/trilium-backup-container/src/progress.spec.ts+++ b/packages/trilium-backup-container/src/progress.spec.ts@@ -117,7 +117,12 @@ describe("reading", () => {await readFromBuffer(written.bytes, { onProgress, progressIntervalMs: 0 });- expect(reports).toEqual([ 0.5, 1, 1 ]);+ // Not exact fractions: an unencrypted payload is emitted a trailer's length behind the+ // input, since that much is held back until the input ends and it can be told apart from+ // the payload. What has to hold is that it climbs and arrives.+ expect(reports.at(-1)).toBe(1);+ expect(reports).toEqual([ ...reports ].sort((left, right) => left - right));+ expect(reports[0]).toBeCloseTo(0.5, 3);});it.each(FORMATS)("measures the database coming out of a %s container", async (@@ -198,16 +203,21 @@ describe("reading", () => {const database = fakeDatabase(2 * FRAME_SIZE);const written = await writeToBuffer(database, { plaintextSize: database.length });- // Claim a third more than the container actually holds, which is only caught at the end.+ // Claim a third more than the container actually holds, which is only caught at the end,+ // where the header's figure meets the one the trailer counted.const lying = Buffer.from(written.bytes);- lying.writeBigUInt64LE(BigInt(3 * FRAME_SIZE), 24);+ lying.writeBigUInt64LE(BigInt(3 * FRAME_SIZE), 32);const failure = await reasonOf(readFromBuffer(lying, { onProgress, progressIntervalMs: 0 }));expect(failure).toBe("size-mismatch");- expect(reports).toEqual([ 1 / 3, 2 / 3 ]);+ // Climbs towards the size it was told and stops where the payload really ended, which is+ // the point: completion is never reported for a database that did not measure up.+ expect(reports[0]).toBeCloseTo(1 / 3, 3);+ expect(reports.at(-1)).toBeCloseTo(2 / 3, 3);+ expect(reports).not.toContain(1);});it("stops reporting when the destination fails, without reporting completion after it", async () => {diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.tsindex e032ff414d..b8a3e9daba 100644--- a/packages/trilium-backup-container/src/read.ts+++ b/packages/trilium-backup-container/src/read.ts@@ -10,10 +10,12 @@ import { BackupContainerError } from "./errors.js";import {authenticatedHeaderEnd,type ContainerHeader,+ type ContainerTrailer,DEFAULT_MAX_HEADER_BYTES,DEFAULT_MAX_KDF_MEMORY_BYTES,decodeFixedHeader,decodeHeader,+ decodeTrailer,encodeHeader,type EncryptionHeader,FIXED_HEADER_BYTES,@@ -24,6 +26,7 @@ import {nonceFor,SQLITE_HEADER_BYTES,TAG_BYTES,+ TRAILER_BYTES,validateScryptParams,validateSqliteHeader,VERIFIER_COUNTER@@ -62,8 +65,8 @@ export interface BackupContainerInfo {version: number;compressed: boolean;encrypted: boolean;- /** Written front to back with no payload digest; the frames alone carry the integrity. */- streamed: boolean;+ /** When the backup was taken, in milliseconds since the Unix epoch, or 0 when not recorded. */+ timestamp: number;/** Size of the wrapped database before compression, or 0 when the writer did not record it. */plaintextSize: number;}@@ -84,12 +87,12 @@ export function peekBackupContainer(}try {- const { version, compressed, encrypted, streamed, plaintextSize } = decodeFixedHeader(+ const { version, timestamp, compressed, encrypted, plaintextSize } = decodeFixedHeader(head.subarray(0, FIXED_HEADER_BYTES),maxHeaderBytes);- return { version, compressed, encrypted, streamed, plaintextSize };+ return { version, timestamp, compressed, encrypted, plaintextSize };} catch {return null;}@@ -165,9 +168,10 @@ export async function readContainer(const progress = createProgressReporter(header.plaintextSize, options);const guard = new OutputGuard(ceiling, options.requireSqliteHeader !== false, progress);+ const found: FoundTrailer = { trailer: null };const payload = header.encryption && key !== null- ? readFrames(reader, header, header.encryption, key, backend)- : readPlainPayload(reader, header, backend);+ ? readFrames(reader, header, header.encryption, key, backend, found)+ : readPlainPayload(reader, backend, found);const unwrapped = header.compressed ? backend.gunzip(payload) : payload;for await (const chunk of unwrapped) {@@ -177,10 +181,26 @@ export async function readContainer(guard.finish();await output.end();- if (header.plaintextSize > 0 && guard.bytesWritten !== header.plaintextSize) {+ // The payload readers always leave one behind or throw, so this is a guard on their contract+ // rather than on the file.+ const trailer = found.trailer;+ if (!trailer) {+ throw new BackupContainerError("truncated", "The container ended without a trailer.");+ }++ // The trailer's size is the authoritative one, counted as the payload was written rather than+ // promised in advance, and it is what an unencrypted container leans on to notice truncation.+ if (guard.bytesWritten !== trailer.plaintextSize) {+ throw new BackupContainerError(+ "size-mismatch",+ `Output is ${guard.bytesWritten} bytes, the container records ${trailer.plaintextSize}.`+ );+ }+ // Both stated the size, and they disagree: whichever is wrong, the file is not intact.+ if (header.plaintextSize > 0 && header.plaintextSize !== trailer.plaintextSize) {throw new BackupContainerError("size-mismatch",- `Output is ${guard.bytesWritten} bytes, header records ${header.plaintextSize}.`+ `Header records ${header.plaintextSize} bytes, the trailer ${trailer.plaintextSize}.`);}@@ -325,11 +345,11 @@ async function* readFrames(header: ContainerHeader,encryption: EncryptionHeader,key: unknown,- backend: ContainerBackend+ backend: ContainerBackend,+ found: FoundTrailer): AsyncGenerator<Uint8Array> {const aad = aadOf(header);- // A streamed container records no digest, so hashing towards one would only slow the restore.- const hash = header.streamed ? null : backend.createSha256();+ const hash = backend.createSha256();let counter = 0;for (;;) {@@ -349,11 +369,9 @@ async function* readFrames(const ciphertext = await reader.readExactly(length);const tag = await reader.readExactly(TAG_BYTES);- if (hash) {- hash.update(lengthField);- hash.update(ciphertext);- hash.update(tag);- }+ hash.update(lengthField);+ hash.update(ciphertext);+ hash.update(tag);const plaintext = await backend.gcmOpen(key,@@ -376,40 +394,61 @@ async function* readFrames(counter++;}+ // The frames say where they end, so the trailer is simply what follows the final one.+ found.trailer = decodeTrailer(await reader.readExactly(TRAILER_BYTES));+if (!(await reader.atEof())) {throw new BackupContainerError("trailing-data",- `Bytes follow the final frame at offset ${reader.consumed}.`+ `Bytes follow the trailer at offset ${reader.consumed}.`);}- if (hash) {- verifyDigest(hash.digest(), header.digest);- }+ verifyDigest(hash.digest(), found.trailer.digest);}-/** Yields the payload of an unencrypted container, which runs to end of file. */+/**+ * Yields the payload of an unencrypted container, which runs to the trailer.+ *+ * Nothing announces where that is, so the last {@link TRAILER_BYTES} bytes are held back as they go+ * past and whatever is still held when the input ends is the trailer. That keeps the reader+ * forward-only: it never has to know the file's length, let alone seek to it, which is what lets the+ * same code read a file, a download and a stream that is still arriving.+ */async function* readPlainPayload(reader: ByteReader,- header: ContainerHeader,- backend: ContainerBackend+ backend: ContainerBackend,+ found: FoundTrailer): AsyncGenerator<Uint8Array> {- // A streamed container records no digest, so hashing towards one would only slow the restore.- // What it records instead is its size, which `readContainer` holds the output to.- const hash = header.streamed ? null : backend.createSha256();+ const hash = backend.createSha256();+ let held = EMPTY;for (;;) {const chunk = await reader.readUpTo(FRAME_SIZE);if (chunk.length === 0) {break;}- hash?.update(chunk);- yield chunk;- }- if (hash) {- verifyDigest(hash.digest(), header.digest);+ const pending = held.length === 0 ? chunk : concatBytes(held, chunk);+ if (pending.length <= TRAILER_BYTES) {+ // Copied, since it has to outlive the reader's own view of these bytes.+ held = pending.slice();+ continue;+ }++ const payload = pending.subarray(0, pending.length - TRAILER_BYTES);+ held = pending.slice(pending.length - TRAILER_BYTES);+ hash.update(payload);+ yield payload;}++ found.trailer = decodeTrailer(held);+ verifyDigest(hash.digest(), found.trailer.digest);+}++/** Where a payload reader leaves the trailer it consumed, for the caller that checks it. */+interface FoundTrailer {+ trailer: ContainerTrailer | null;}function verifyDigest(actual: Uint8Array, expected: Uint8Array): void {diff --git a/packages/trilium-backup-container/src/test-helpers.ts b/packages/trilium-backup-container/src/test-helpers.tsindex a80dff53a8..e4b5457f54 100644--- a/packages/trilium-backup-container/src/test-helpers.ts+++ b/packages/trilium-backup-container/src/test-helpers.ts@@ -52,34 +52,29 @@ export function chunked(data: Buffer, chunkSize: number): Readable {export interface WrittenContainer {bytes: Buffer;result: WriteBackupContainerResult;- patchedAt: number[];}-export type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;+export type WriteOptions = WriteBackupContainerOptions;-/** Writes a container in memory, applying the digest patch the way a file destination would. */+/**+ * Writes a container in memory.+ *+ * Nothing is written back to: a container is produced in one forward pass, so what the sink+ * received in order is the whole file.+ */export async function writeToBuffer(input: Buffer | Readable,options: WriteOptions = {}): 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) }); }- }+ options);- const bytes = sink.toBuffer();- for (const patch of patches) {- patch.data.copy(bytes, patch.offset);- }-- return { bytes, result, patchedAt: patches.map((patch) => patch.offset) };+ return { bytes: sink.toBuffer(), result };}export interface ReadContainer {@@ -103,23 +98,14 @@ export async function writeToBufferWeb(options: WriteOptions = {}): Promise<WrittenContainer> {const collector = webCollector();- const patches: { offset: number; data: Buffer }[] = [];const result = await writeBackupContainerWeb(Buffer.isBuffer(input) ? webSource(input) : input,collector.stream,- {- ...options,- patchHeader: (offset, data) => { patches.push({ offset, data: Buffer.from(data) }); }- }+ options);- const bytes = collector.toBuffer();- for (const patch of patches) {- patch.data.copy(bytes, patch.offset);- }-- return { bytes, result, patchedAt: patches.map((patch) => patch.offset) };+ return { bytes: collector.toBuffer(), result };}/** The web counterpart of {@link readFromBuffer}. */diff --git a/packages/trilium-backup-container/src/web.ts b/packages/trilium-backup-container/src/web.tsindex a520b2ead1..207848e60c 100644--- a/packages/trilium-backup-container/src/web.ts+++ b/packages/trilium-backup-container/src/web.ts@@ -35,7 +35,11 @@ export {SCRYPT_BOUNDS,SCRYPT_DEFAULTS,type ScryptParams,- streamedContainerSize+ containerSize,+ type ContainerTrailer,+ decodeTrailer,+ encodeTrailer,+ TRAILER_BYTES} from "./format.js";export {DEFAULT_PROGRESS_INTERVAL_MS,@@ -51,7 +55,6 @@ export {} from "./read.js";export { readBackupContainer, writeBackupContainer } from "./web-streams.js";export {- type PatchHeader,type WriteBackupContainerOptions,type WriteBackupContainerResult} from "./write.js";diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.tsindex c6065e52e5..d325d565f3 100644--- a/packages/trilium-backup-container/src/write.ts+++ b/packages/trilium-backup-container/src/write.ts@@ -10,9 +10,8 @@ import {authenticatedHeaderEnd,type ContainerHeader,DEFAULT_MAX_KDF_MEMORY_BYTES,- DIGEST_BYTES,- digestOffset,encodeHeader,+ encodeTrailer,FORMAT_VERSION,FRAME_FINAL_FLAG,FRAME_SIZE,@@ -33,29 +32,14 @@ import { createProgressReporter, type ProgressOptions, type ProgressReporter } fconst EMPTY = new Uint8Array(0);-/**- * 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: Uint8Array) => Promise<void> | void;-export interface WriteBackupContainerOptions extends ProgressOptions {/**- * Patches the payload digest into the header once the payload is complete. Required, except- * for a {@link streamed} container, which records no digest and never writes backwards.- */- patchHeader?: PatchHeader;- /**- * Write front to back, recording no payload digest — for a destination that cannot be- * revisited, such as a download already on its way to the user.+ * When the backup was taken, in milliseconds since the Unix epoch. Defaults to now.*- * Encrypted, the GCM frame tags stand in for the digest. Unencrypted, {@link- * WriteBackupContainerOptions.plaintextSize} does, so it is required: without either, nothing- * about the payload could be checked.+ * Taken as an option rather than read here so that a caller can record when the database was+ * actually copied, which for a backup written from a snapshot is not when this ran.*/- streamed?: boolean;+ timestamp?: number;/** Compress the payload with gzip. */compress?: boolean;/** Encrypt the payload. Encryption is on exactly when a passphrase is given. */@@ -106,21 +90,6 @@ export async function writeContainer(backend: ContainerBackend,options: WriteBackupContainerOptions): Promise<WriteBackupContainerResult> {- const streamed = options.streamed === true;- if (streamed && options.passphrase === undefined && !(options.plaintextSize ?? 0)) {- throw new BackupContainerError(- "invalid-options",- "A streamed container that is not encrypted must record its plaintext size: with "- + "neither that nor frame tags, nothing about the payload could be checked."- );- }- if (!streamed && typeof options.patchHeader !== "function") {- 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(@@ -137,13 +106,12 @@ export async function writeContainer(// final.const header: ContainerHeader = {version: FORMAT_VERSION,+ timestamp: options.timestamp ?? Date.now(),compressed,encrypted,- streamed,plaintextSize,headerLength: headerLengthFor(encrypted),- encryption: null,- digest: new Uint8Array(DIGEST_BYTES)+ encryption: null};let key: unknown = null;@@ -180,7 +148,10 @@ export async function writeContainer(await output.write(headerBytes);// input -> gzip -> frames -> digest -> output, with the stages the flags call for.- let payload = input;+ // Counted at the input, before any of them, so the trailer records the database's own length+ // rather than whatever the payload compressed or framed to.+ const plaintext = { bytes: 0 };+ let payload: ByteSource = countBytes(input, plaintext);if (progress) {payload = tapProgress(payload, progress);}@@ -198,17 +169,16 @@ export async function writeContainer(payloadBytes += chunk.length;await output.write(chunk);}- await output.end();+ // The trailer is the last thing in the file, and the only part that could not be written until+ // now. Written before the sink is closed, so a destination that can only be appended to still+ // ends up holding a complete container.const digest = hash.digest();- // A streamed container keeps the zeros: its frames authenticate themselves, and there is no- // going back to the header of a destination already streamed away.- if (!streamed) {- await options.patchHeader?.(digestOffset(header.headerLength), digest);- }+ await output.write(encodeTrailer({ digest, plaintextSize: plaintext.bytes }));+ await output.end();- // After the patch rather than after the payload: the container is not written until the digest- // is in its header.+ // After the trailer rather than after the payload: the container is not written until what+ // vouches for it is.progress?.complete();return {@@ -236,6 +206,14 @@ async function* tapProgress(source: ByteSource, progress: ProgressReporter): Byt}}+/** Counts what passes through, so the trailer can state a length nobody had to be told. */+async function* countBytes(source: ByteSource, counted: { bytes: number }): ByteSource {+ for await (const chunk of source) {+ counted.bytes += chunk.length;+ yield chunk;+ }+}+/*** Forces the gzip MTIME field to zero and the OS byte to "unknown".*