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: add a method to retrieve container information
Adorian Doran069771247029
diff --git a/packages/trilium-backup-container/README.md b/packages/trilium-backup-container/README.mdindex 1b8fd9915f..cd46652acb 100644--- a/packages/trilium-backup-container/README.md+++ b/packages/trilium-backup-container/README.md@@ -31,35 +31,51 @@ database, and `skipVerifier: true` is a recovery path for a container whose veri## Writing a container-The payload digest is only known once the payload has been written, so the caller supplies-`patchHeader` to write it into the header afterwards.+Everything only knowable once the payload has been written, the digest and the length it came to,+goes in a trailer after it. Nothing is written back to, so a container is produced in one forward+pass and the destination need not be seekable.```tsimport { createReadStream, createWriteStream } from "node:fs";-import { open, rename, stat } from "node:fs/promises";+import { rename, stat } from "node:fs/promises";import { writeBackupContainer } from "@triliumnext/backup-container";await writeBackupContainer(createReadStream(source), createWriteStream(partial), {compress: true,passphrase, // omit to leave the container unencrypted- 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});await rename(partial, destination); // rename last, so a partial file never looks finished```-Write to a temporary name and rename on success. Do not hand the payload stream a `FileHandle` opened-with `autoClose: false` and patch through that same handle: its `close()` then waits forever on a-stream that never emits `close`.+Write to a temporary name and rename on success.++## Describing a container without opening it++What a container is, is stated in the clear, so a listing can be built from the first+`FIXED_HEADER_BYTES` bytes of each file: no passphrase, no payload, nothing to decompress.++```ts+import { FIXED_HEADER_BYTES, getInfo } from "@triliumnext/backup-container";++const info = getInfo(head); // ArrayBuffer, Uint8Array, Buffer or any view+```++It never throws, so one foreign or damaged file among a hundred costs the listing a row rather than+the listing, and it answers in three parts:++| Answer | Means |+| --- | --- |+| `{ isValid: false }` | Not a container: the magic is not there |+| `{ isValid: true, isSupported: false, version }` | One of ours, past what this build implements |+| `{ isValid: true, isSupported: true, … }` | Readable, and described below |++The fields exist only in the third case, because a version whose layout this module does not+implement is one whose flags and sizes it would only be guessing at: `size` is the database inside+before compression, or 0 where the writer did not record it; `creationTimestamp` is when the backup+was taken, in milliseconds since the Unix epoch, or 0 where it was not recorded; `isCompressed` and+`isEncrypted` are the flags.## Using it in a browser@@ -83,10 +99,9 @@ Three platform limits are worth knowing. WebCrypto's `subtle` interface only exicontexts (HTTPS, localhost, workers of either), so encrypted containers cannot be handled on a pageserved over plain HTTP. `CompressionStream` takes no compression level, so `compressionLevel` isignored and the platform default applies; the header normalisation keeps the output canonical-regardless. And `patchHeader` still needs random access to the finished bytes, which OPFS provides-(`write` with `at`) but a streamed download does not, so writing a container means staging it-somewhere seekable first. Key derivation is pure JavaScript here and takes seconds rather than-milliseconds at the default cost; run it in a worker and say so in the UI.+regardless. And key derivation is pure JavaScript here and takes seconds rather than milliseconds at+the default cost; run it in a worker and say so in the UI. Writing needs nothing seekable, so a+container may be streamed straight into a download.## Reporting progress@@ -143,13 +158,13 @@ The ones worth handling by name:| `passphrase-required` | The container is encrypted and no passphrase was given || `wrong-passphrase-or-damaged-header` | The verifier tag did not match. A wrong passphrase, or a damaged header, and the two cannot be told apart from the tag alone || `damaged-payload` | A frame failed authentication, or a compressed payload could not be decoded |-| `digest-mismatch` | The payload does not match the digest recorded in the header, i.e. bit rot |+| `digest-mismatch` | The payload does not match the digest recorded in the trailer, i.e. bit rot || `truncated` | The file ends before the container does || `trailing-data` | Bytes follow the final frame || `not-a-database` | The unwrapped payload is not a SQLite database || `output-too-large` | Output hit the ceiling, which is how a crafted compressed payload is stopped || `unsupported-version` | Written by a newer Trilium |-| `invalid-options` | The caller's options are unusable, e.g. a missing `patchHeader` |+| `invalid-options` | The caller's options are unusable, e.g. a negative `plaintextSize` |The full set is the `BackupContainerErrorReason` union.diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.tsindex dcc0ab572c..89ec545e2a 100644--- a/packages/trilium-backup-container/src/container.spec.ts+++ b/packages/trilium-backup-container/src/container.spec.ts@@ -13,7 +13,7 @@ import {TAG_BYTES} from "./format.js";import { readBackupContainer, writeBackupContainer } from "./node-streams.js";-import { peekBackupContainer } from "./read.js";+import { getInfo } from "./read.js";import {chunked,fakeDatabase,@@ -27,7 +27,7 @@ import {type WriteOptions,writeToBuffer} from "./test-helpers.js";-type PeekCase = [string, WriteOptions, { compressed: boolean; encrypted: boolean }];+type PeekCase = [string, WriteOptions, { isCompressed: boolean; isEncrypted: boolean }];const PASSPHRASE = "correct horse battery staple";const FRAME_OVERHEAD = 4 + TAG_BYTES;@@ -296,19 +296,19 @@ describe("damage and tampering", () => {});});-describe("peeking at a container", () => {+describe("describing a container for a listing", () => {it.each([- [ "plain", {}, { compressed: false, encrypted: false } ],- [ "compressed", { compress: true }, { compressed: true, encrypted: false } ],+ [ "plain", {}, { isCompressed: false, isEncrypted: false } ],+ [ "compressed", { compress: true }, { isCompressed: true, isEncrypted: false } ],["encrypted",{ passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },- { compressed: false, encrypted: true }+ { isCompressed: false, isEncrypted: true }],["both",{ compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT },- { compressed: true, encrypted: true }+ { isCompressed: true, isEncrypted: true }]] as PeekCase[])("reports a %s container from its first bytes alone", async (_label,@@ -321,31 +321,89 @@ describe("peeking at a container", () => {{ ...options, plaintextSize: database.length });- // Only the fixed header, and no passphrase, which is the whole point of the peek.- expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES))).toEqual({+ // Only the fixed header, and no passphrase, which is the whole point of describing one.+ expect(getInfo(written.bytes.subarray(0, FIXED_HEADER_BYTES))).toEqual({+ isValid: true,+ isSupported: true,version: 1,- plaintextSize: 9_000,- timestamp: expect.any(Number),+ size: 9_000,+ creationTimestamp: expect.any(Number),...expected});});- it("reports an unrecorded plaintext size as zero rather than guessing", async () => {+ it("dates the backup from the container, not from the file it sits in", async () => {+ const taken = Date.UTC(2026, 1, 3, 4, 5, 6);+ const written = await writeToBuffer(fakeDatabase(4096), { timestamp: taken });++ const info = getInfo(written.bytes);++ expect(info).toMatchObject({ isValid: true, isSupported: true });+ expect(info.isValid && info.isSupported && info.creationTimestamp).toBe(taken);+ });++ it("reports an unrecorded size as zero rather than guessing", async () => {const written = await writeToBuffer(fakeDatabase(4096), { compress: true });+ const info = getInfo(written.bytes);++ expect(info.isValid && info.isSupported && info.size).toBe(0);+ });++ it.each([+ [ "an ArrayBuffer", (head: Uint8Array) => copyOf(head, 0) ],+ [ "a view over one", (head: Uint8Array) => new DataView(copyOf(head, 0)) ],+ // The one an offset-blind reader gets silently wrong, since the bytes it wants are there.+ [+ "a view starting partway into one",+ (head: Uint8Array) => new DataView(copyOf(head, 8), 8)+ ]+ ])("takes the head as %s, since callers hold it differently", async (_label, wrap) => {+ const written = await writeToBuffer(fakeDatabase(4096), { plaintextSize: 4096 });+ const head = written.bytes.subarray(0, FIXED_HEADER_BYTES);- expect(peekBackupContainer(written.bytes)?.plaintextSize).toBe(0);+ expect(getInfo(wrap(head))).toEqual(getInfo(head));});it.each([[ "fewer bytes than a header", Buffer.alloc(20) ],[ "something that is not a container", Buffer.alloc(64, 9) ],- [ "a version it does not know", tamper((bytes) => bytes.writeUInt8(2, 20)) ],- [ "a reserved flag bit", tamper((bytes) => bytes.writeUInt8(0b100, 29)) ]- ])("answers null for %s, so one bad file cannot derail a listing", (_label, bytes) => {- expect(peekBackupContainer(bytes)).toBeNull();+ [ "an empty file", Buffer.alloc(0) ]+ ])("says %s is not a backup at all, so one foreign file cannot derail a listing", (+ _label,+ bytes+ ) => {+ expect(getInfo(bytes)).toEqual({ isValid: false });+ });++ it.each([+ [ "a version written after this build", (bytes: Buffer) => bytes.writeUInt8(2, 20), 2 ],+ [ "a version nothing could have written", (bytes: Buffer) => bytes.writeUInt8(0, 20), 0 ],+ [ "a reserved flag bit", (bytes: Buffer) => bytes.writeUInt8(0b100, 29), 1 ],+ [ "a header that does not measure up", (bytes: Buffer) => bytes.writeUInt16LE(64, 30), 1 ]+ ])("owns %s as a backup it cannot open, rather than disowning it", (+ _label,+ mutate,+ version+ ) => {+ // The difference a listing lives on: "not a backup" and "a backup this build is too old+ // for" are the same null to a reader that only answers yes or no.+ expect(getInfo(tamper(mutate))).toEqual({ isValid: true, isSupported: false, version });});});+/**+ * The bytes in an `ArrayBuffer` of their own, which a `Buffer` never has: Node allocates those out+ * of a shared pool, so `.buffer` on one is most of the heap and starts nowhere near the bytes.+ *+ * @param offset how far into the buffer to put them, so a view at a non-zero offset can be built.+ */+function copyOf(bytes: Uint8Array, offset: number): ArrayBuffer {+ const buffer = new ArrayBuffer(offset + bytes.length);+ new Uint8Array(buffer).set(bytes, offset);++ return buffer;+}+function tamper(mutate: (bytes: Buffer) => void): Buffer {const header = Buffer.alloc(FIXED_HEADER_BYTES);Buffer.from("Trilium Notes Backup", "ascii").copy(header, 0);@@ -448,8 +506,8 @@ describe("forward-only writing", () => {// 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, compressed: false });+ expect(getInfo(written.bytes.subarray(0, FIXED_HEADER_BYTES)))+ .toMatchObject({ isEncrypted: true, isCompressed: false });const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });expect(read.bytes.equals(database)).toBe(true);@@ -482,8 +540,8 @@ describe("forward-only writing", () => {const written = await writeToBuffer(database, { plaintextSize: database.length });expect(written.bytes.length).toBe(containerSize(database.length, false));- expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES)))- .toMatchObject({ encrypted: false, compressed: false });+ expect(getInfo(written.bytes.subarray(0, FIXED_HEADER_BYTES)))+ .toMatchObject({ isEncrypted: false, isCompressed: false });expect((await readFromBuffer(written.bytes)).bytes.equals(database)).toBe(true);expect((await readFromBufferWeb(written.bytes)).bytes.equals(database)).toBe(true);diff --git a/packages/trilium-backup-container/src/cross-backend.spec.ts b/packages/trilium-backup-container/src/cross-backend.spec.tsindex f801802005..33db27e9ec 100644--- a/packages/trilium-backup-container/src/cross-backend.spec.ts+++ b/packages/trilium-backup-container/src/cross-backend.spec.ts@@ -71,9 +71,12 @@ describe("cross-backend round trips", () => {it("writes byte-identical plain containers on both backends", async () => {const database = fakeDatabase(9_000);+ // Stated rather than taken from the clock, which is the one field two writes are entitled+ // to disagree on: a millisecond between them would fail this for the wrong reason.+ const shared = { plaintextSize: database.length, timestamp: Date.UTC(2026, 0, 2, 3, 4, 5) };- const node = await writeToBuffer(database, { plaintextSize: database.length });- const web = await writeToBufferWeb(database, { plaintextSize: database.length });+ const node = await writeToBuffer(database, shared);+ const web = await writeToBufferWeb(database, shared);expect(web.bytes.equals(node.bytes)).toBe(true);});diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.tsindex 0b17cf7eaa..ed8a1e4306 100644--- a/packages/trilium-backup-container/src/index.ts+++ b/packages/trilium-backup-container/src/index.ts@@ -13,22 +13,12 @@** @example Writing an encrypted, compressed container* ```ts+ * // One forward pass, so the destination is never written back to: write to a temporary name and+ * // rename on success, and a partial file never looks finished.* 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();- * }- * }+ * plaintextSize: (await stat(source)).size* });* await rename(partial, final);* ```@@ -42,6 +32,14 @@* );* ```*+ * @example Listing a directory of them, opening none+ * ```ts+ * const info = getInfo(await read(path, FIXED_HEADER_BYTES));+ * if (info.isValid && info.isSupported) {+ * rows.push({ path, taken: info.creationTimestamp, size: info.size });+ * }+ * ```+ ** @module*/@@ -70,11 +68,13 @@ export {type ProgressOptions} from "./progress.js";export {- type BackupContainerInfo,+ type BackupContainerSummary,+ type ContainerHead,DEFAULT_MAX_OUTPUT_BYTES,- peekBackupContainer,+ getInfo,type ReadBackupContainerOptions,- type ReadBackupContainerResult+ type ReadBackupContainerResult,+ type SupportedBackupContainer} from "./read.js";export {type WriteBackupContainerOptions,diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.tsindex b8a3e9daba..5c3236dc0b 100644--- a/packages/trilium-backup-container/src/read.ts+++ b/packages/trilium-backup-container/src/read.ts@@ -60,44 +60,107 @@ export interface ReadBackupContainerOptions extends ProgressOptions {requireSqliteHeader?: boolean;}-/** What a container says about itself, before any of its payload is read. */-export interface BackupContainerInfo {+/** The head of a container, however the caller happens to be holding it. */+export type ContainerHead = ArrayBuffer | ArrayBufferView;++/**+ * What a container says about itself, before any of its payload is read.+ *+ * Three answers rather than two, because "not a backup" and "a backup this build is too old to+ * open" call for entirely different things to be said to the user, and the fields below only exist+ * for the third: a version whose layout this module does not implement is one whose flags and sizes+ * it would only be guessing at.+ */+export type BackupContainerSummary =+ /** Not a container at all: whatever else this file is, it did not come from here. */+ | { isValid: false }+ /** One of ours, but past what this module implements: nothing beyond the version is known. */+ | { isValid: true; isSupported: false; version: number }+ | SupportedBackupContainer;++/** A container this module can act on, which is the only case any of these fields is known in. */+export interface SupportedBackupContainer {+ isValid: true;+ isSupported: true;version: number;- compressed: boolean;- encrypted: boolean;+ /**+ * Size of the database inside, before compression, or 0 where the writer did not record it. Not+ * the size of the file, which is this plus the wrapping and, once compressed, less than this by+ * an amount nothing states in advance.+ */+ size: number;/** 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;+ creationTimestamp: number;+ isCompressed: boolean;+ isEncrypted: boolean;}/*** Identifies a container from its first {@link FIXED_HEADER_BYTES} bytes, without touching the* payload and without the passphrase: what a container is, is stated in the clear.*- * Returns `null` for anything this reader does not recognise, so that listing a directory of- * backups is never derailed by one damaged or foreign file.+ * Built for listing a directory of them, so it is O(1) over a view of what it is given, copies+ * nothing, and never throws: one damaged or foreign file among a hundred costs the listing a row,+ * not the listing.+ *+ * @param head at least {@link FIXED_HEADER_BYTES} bytes from offset 0 of the file. Anything longer+ * is fine and nothing past those bytes is read, so a caller holding the whole file may+ * pass it as it stands.+ * @param maxHeaderBytes ceiling above which a header is not worth describing.*/-export function peekBackupContainer(- head: Uint8Array,+export function getInfo(+ head: ContainerHead,maxHeaderBytes: number = DEFAULT_MAX_HEADER_BYTES-): BackupContainerInfo | null {- if (head.length < FIXED_HEADER_BYTES) {- return null;+): BackupContainerSummary {+ const bytes = asBytes(head);++ // Settled here rather than by catching what the decoder throws, because this is the rejection+ // that happens in bulk: a folder of backups is also a folder of everything else the user keeps+ // there, and each of those should cost a comparison rather than an exception.+ const isContainer = bytes.length >= FIXED_HEADER_BYTES+ && bytesEqual(bytes.subarray(0, MAGIC.length), MAGIC);+ if (!isContainer) {+ return { isValid: false };}+ // Past the magic, so this field is where the format has always promised to keep it, which is+ // the one thing that stays true of a version written after this module.+ const version = bytes[MAGIC.length];+try {- const { version, timestamp, compressed, encrypted, plaintextSize } = decodeFixedHeader(- head.subarray(0, FIXED_HEADER_BYTES),+ const { timestamp, compressed, encrypted, plaintextSize } = decodeFixedHeader(+ bytes.subarray(0, FIXED_HEADER_BYTES),maxHeaderBytes);- return { version, timestamp, compressed, encrypted, plaintextSize };+ return {+ isValid: true,+ isSupported: true,+ version,+ size: plaintextSize,+ creationTimestamp: timestamp,+ isCompressed: compressed,+ isEncrypted: encrypted+ };} catch {- return null;+ // Every remaining way the head can be refused says the same thing to a listing: ours, and+ // not for this build to open. A version it does not implement and a header that does not+ // measure what this version requires are both answered by pointing at the version.+ return { isValid: true, isSupported: false, version };}}+/** Views whatever the caller holds as bytes, copying none of them. */+function asBytes(head: ContainerHead): Uint8Array {+ if (head instanceof Uint8Array) {+ return head;+ }++ return ArrayBuffer.isView(head)+ ? new Uint8Array(head.buffer, head.byteOffset, head.byteLength)+ : new Uint8Array(head);+}+export interface ReadBackupContainerResult {version: number;compressed: boolean;diff --git a/packages/trilium-backup-container/src/web.ts b/packages/trilium-backup-container/src/web.tsindex 207848e60c..89bf7be4e7 100644--- a/packages/trilium-backup-container/src/web.ts+++ b/packages/trilium-backup-container/src/web.ts@@ -47,11 +47,13 @@ export {type ProgressOptions} from "./progress.js";export {- type BackupContainerInfo,+ type BackupContainerSummary,+ type ContainerHead,DEFAULT_MAX_OUTPUT_BYTES,- peekBackupContainer,+ getInfo,type ReadBackupContainerOptions,- type ReadBackupContainerResult+ type ReadBackupContainerResult,+ type SupportedBackupContainer} from "./read.js";export { readBackupContainer, writeBackupContainer } from "./web-streams.js";export {diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.tsindex d325d565f3..981e0add1d 100644--- a/packages/trilium-backup-container/src/write.ts+++ b/packages/trilium-backup-container/src/write.ts@@ -74,13 +74,14 @@ export interface WriteBackupContainerResult {* Wraps a database into a container. This is the runtime-neutral core; the Node and web entry* points wrap it with their stream types and their backend.*- * 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.+ * The header is written first and never returned to, then the payload streams through gzip and the+ * frame encryptor as configured, and finally the trailer records the digest and the length the+ * payload came to. One forward pass, so the destination need not be seekable.** @param input the database bytes.* @param output the destination, which is ended by this call.* @param backend the platform's crypto and compression primitives.- * @param options see {@link WriteBackupContainerOptions}; `patchHeader` is required.+ * @param options see {@link WriteBackupContainerOptions}.* @returns what was written, see {@link WriteBackupContainerResult}.* @throws BackupContainerError with `reason` set, see {@link BackupContainerErrorReason}.*/