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 support for browser environment (standalone) as well
Adorian Doran66479ad2c51e
diff --git a/packages/trilium-backup-container/README.md b/packages/trilium-backup-container/README.mdindex d3047a2b14..1b8fd9915f 100644--- a/packages/trilium-backup-container/README.md+++ b/packages/trilium-backup-container/README.md@@ -5,8 +5,9 @@ with optional gzip compression and optional AES-256-GCM encryption. It exists sobe made smaller and unreadable to anyone else who can see the folder it is written to, which mattersmost when that folder is synced to the cloud. Both directions stream, so a multi-gigabyte database isnever held in memory, and the reader authenticates every chunk before handing any of it to the-destination. The module depends on nothing outside the Node standard library and contains no-user-facing strings.+destination. The module contains no user-facing strings and ships two entry points over one shared+format layer: the root entry for Node, which depends on nothing outside the Node standard library,+and `@triliumnext/backup-container/web` for browsers. A container written by either is read by both.## Reading a container@@ -60,6 +61,33 @@ Write to a temporary name and rename on success. Do not hand the payload streamwith `autoClose: false` and patch through that same handle: its `close()` then waits forever on astream that never emits `close`.+## Using it in a browser++`@triliumnext/backup-container/web` exposes the same two operations on Web Streams instead of Node+streams, with the same options, results and errors. AES-256-GCM and randomness come from WebCrypto,+gzip from the platform's `CompressionStream`, and the two primitives WebCrypto does not offer,+scrypt and incremental SHA-256, from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes),+the entry point's only dependency. The Node entry point never loads it.++```ts+import { readBackupContainer } from "@triliumnext/backup-container/web";++const handle = await directory.getFileHandle("document.db", { create: true });+const info = await readBackupContainer(file.stream(), await handle.createWritable(), {+ passphrase,+ onProgress: (progress) => report(Math.round(progress * 100))+});+```++Three platform limits are worth knowing. WebCrypto's `subtle` interface only exists in secure+contexts (HTTPS, localhost, workers of either), so encrypted containers cannot be handled on a page+served over plain HTTP. `CompressionStream` takes no compression level, so `compressionLevel` is+ignored 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.+## Reporting progressBoth directions accept `onProgress`, which is called with a number from 0 to 1 at most once everydiff --git a/packages/trilium-backup-container/package.json b/packages/trilium-backup-container/package.jsonindex 53142a86ef..3140e48a17 100644--- a/packages/trilium-backup-container/package.json+++ b/packages/trilium-backup-container/package.json@@ -6,9 +6,16 @@"type": "module","private": true,"main": "./src/index.ts",+ "exports": {+ ".": "./src/index.ts",+ "./web": "./src/web.ts"+ },"scripts": {"test": "vitest"},+ "dependencies": {+ "@noble/hashes": "^2.2.0"+ },"keywords": ["backup","container",diff --git a/packages/trilium-backup-container/src/backend-node.ts b/packages/trilium-backup-container/src/backend-node.tsnew file mode 100644index 0000000000..3ddf81e8e3--- /dev/null+++ b/packages/trilium-backup-container/src/backend-node.ts@@ -0,0 +1,156 @@+import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt } from "node:crypto";+import { once } from "node:events";+import type { Duplex } from "node:stream";+import { createGunzip, createGzip } from "node:zlib";++import type { ByteSource, ContainerBackend } from "./backend.js";+import { BackupContainerError } from "./errors.js";+import { KEY_BYTES } from "./format.js";++/**+ * The zero-dependency backend: OpenSSL's scrypt and AES-256-GCM, zlib's gzip, all through the Node+ * standard library.+ */+export const nodeBackend: ContainerBackend = {++ randomBytes(size) {+ return randomBytes(size);+ },++ createSha256() {+ const hash = createHash("sha256");++ return {+ update(chunk: Uint8Array) {+ hash.update(chunk);+ },+ digest() {+ return hash.digest();+ }+ };+ },++ deriveKey(passphrase, salt, params, maxMemoryBytes) {+ const options = {+ N: 2 ** params.log2N,+ r: params.r,+ p: params.p,+ maxmem: maxMemoryBytes+ };++ return new Promise((resolve, reject) => {+ // scrypt rejects impossible parameters synchronously and everything else through the+ // callback.+ try {+ scrypt(+ passphrase,+ salt,+ KEY_BYTES,+ options,+ (error, key) => (error ? reject(error) : resolve(key))+ );+ } catch (error) {+ reject(error);+ }+ });+ },++ async gcmSeal(key, nonce, aad, plaintext) {+ const cipher = createCipheriv("aes-256-gcm", key as Uint8Array, nonce);+ cipher.setAAD(aad);++ const ciphertext = Buffer.concat([ cipher.update(plaintext), cipher.final() ]);++ return { ciphertext, tag: cipher.getAuthTag() };+ },++ async gcmOpen(key, nonce, aad, ciphertext, tag) {+ const decipher = createDecipheriv("aes-256-gcm", key as Uint8Array, nonce);+ decipher.setAAD(aad);+ decipher.setAuthTag(tag);++ try {+ return Buffer.concat([ decipher.update(ciphertext), decipher.final() ]);+ } catch {+ return null;+ }+ },++ gzip(source, level) {+ return throughZlib(source, createGzip({ level }), (error) => error);+ },++ gunzip(source) {+ return throughZlib(source, createGunzip(), translateZlibError);+ }++};++/**+ * Runs a byte source through a zlib stream, yielding what comes out the other side.+ *+ * The writing half runs as its own task so a full internal buffer never deadlocks against an+ * unread output side. A failure on either half destroys the stream, which makes the other half+ * fail too; `translate` then decides what the surfaced error means, so the decompressor can call+ * a decode failure a damaged payload while everything else passes through untranslated.+ */+async function* throughZlib(+ source: ByteSource,+ transform: Duplex,+ translate: (error: unknown) => unknown+): AsyncGenerator<Uint8Array> {+ // The stream can be destroyed with an error after its iterator has detached, so a spare+ // listener keeps that from escalating into an uncaught exception.+ transform.on("error", () => {});++ const abort = new AbortController();+ const writing = pumpInto(source, transform, abort.signal);++ try {+ for await (const chunk of transform) {+ yield chunk as Uint8Array;+ }+ await writing;+ } catch (error) {+ throw translate(error);+ } finally {+ abort.abort();+ transform.destroy();+ }+}++/**+ * Feeds the source into the zlib stream, honouring its backpressure. Never rejects: a source+ * failure is planted into the stream instead, where the reading half picks it up, so the returned+ * promise needs no handler of its own.+ */+async function pumpInto(source: ByteSource, transform: Duplex, signal: AbortSignal): Promise<void> {+ try {+ for await (const chunk of source) {+ if (!transform.write(chunk)) {+ await once(transform, "drain", { signal });+ }+ }+ transform.end();+ } catch (error) {+ if (!transform.destroyed) {+ transform.destroy(error as Error);+ }+ }+}++/**+ * zlib decode failures mean a damaged payload; everything else, e.g. an error the payload source+ * threw, belongs to the caller.+ */+function translateZlibError(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/backend-web.ts b/packages/trilium-backup-container/src/backend-web.tsnew file mode 100644index 0000000000..d74fde7b29--- /dev/null+++ b/packages/trilium-backup-container/src/backend-web.ts@@ -0,0 +1,227 @@+import { scryptAsync } from "@noble/hashes/scrypt.js";+import { sha256 } from "@noble/hashes/sha2.js";++import type { ByteSource, ContainerBackend } from "./backend.js";+import { concatBytes } from "./bytes.js";+import { BackupContainerError } from "./errors.js";+import { KEY_BYTES, TAG_BYTES } from "./format.js";++/**+ * The browser backend: AES-256-GCM and randomness from WebCrypto, gzip from the platform's+ * `CompressionStream`, and the two primitives WebCrypto does not offer, scrypt and incremental+ * SHA-256, from `@noble/hashes`. Runs under Node just as well, which is how the cross-backend+ * tests exercise it.+ *+ * WebCrypto's `subtle` interface only exists in secure contexts (HTTPS, localhost, workers of+ * either), so this backend cannot serve a page loaded over plain HTTP.+ */+export const webBackend: ContainerBackend = {++ randomBytes(size) {+ const bytes = new Uint8Array(size);+ globalThis.crypto.getRandomValues(bytes);+ return bytes;+ },++ createSha256() {+ const hash = sha256.create();++ return {+ update(chunk: Uint8Array) {+ hash.update(chunk);+ },+ digest() {+ return hash.digest();+ }+ };+ },++ async deriveKey(passphrase, salt, params, maxMemoryBytes) {+ const raw = await scryptAsync(passphrase, salt, {+ N: 2 ** params.log2N,+ r: params.r,+ p: params.p,+ dkLen: KEY_BYTES,+ maxmem: maxMemoryBytes+ });++ // A non-extractable key: once imported, the raw bytes never need to exist again.+ return subtleOrThrow().importKey(+ "raw",+ asBytes(raw),+ "AES-GCM",+ false,+ [ "encrypt", "decrypt" ]+ );+ },++ async gcmSeal(key, nonce, aad, plaintext) {+ const sealed = new Uint8Array(await subtleOrThrow().encrypt(+ { name: "AES-GCM", iv: asBytes(nonce), additionalData: asBytes(aad) },+ key as CryptoKey,+ asBytes(plaintext)+ ));++ // WebCrypto appends the tag to the ciphertext; the format stores it separately.+ return {+ ciphertext: sealed.subarray(0, sealed.length - TAG_BYTES),+ tag: sealed.subarray(sealed.length - TAG_BYTES)+ };+ },++ async gcmOpen(key, nonce, aad, ciphertext, tag) {+ try {+ return new Uint8Array(await subtleOrThrow().decrypt(+ { name: "AES-GCM", iv: asBytes(nonce), additionalData: asBytes(aad) },+ key as CryptoKey,+ asBytes(concatBytes(ciphertext, tag))+ ));+ } catch {+ // WebCrypto reports an authentication failure as an opaque OperationError.+ return null;+ }+ },++ gzip(source) {+ // CompressionStream takes no level, so the platform default applies.+ return throughWebTransform(+ source,+ byteTransform(new CompressionStream("gzip")),+ (error) => error+ );+ },++ gunzip(source) {+ return throughWebTransform(+ source,+ byteTransform(new DecompressionStream("gzip")),+ () => new BackupContainerError(+ "damaged-payload",+ "Compressed payload could not be read."+ )+ );+ }++};++/** A transform pair as this module uses it: bytes in, bytes out. */+interface ByteTransform {+ readable: ReadableStream<Uint8Array>;+ writable: WritableStream<Uint8Array>;+}++/**+ * TypeScript models the platform codec streams over `BufferSource`, which since the typed-array+ * generics also insists on a non-shared backing buffer. Every chunk this module produces is a+ * plain `Uint8Array`, which the codecs accept, so the mismatch is nominal.+ */+function byteTransform(transform: CompressionStream | DecompressionStream): ByteTransform {+ return transform as unknown as ByteTransform;+}++/**+ * Narrows to a non-shared backing buffer, which WebCrypto's typings insist on. Nothing in this+ * package ever allocates from a `SharedArrayBuffer`.+ */+function asBytes(view: Uint8Array): Uint8Array<ArrayBuffer> {+ return view as Uint8Array<ArrayBuffer>;+}++/** The one WebCrypto probe, so an insecure context fails with an explanation, not `undefined`. */+function subtleOrThrow(): SubtleCrypto {+ const subtle = globalThis.crypto?.subtle;+ if (!subtle) {+ throw new Error(+ "WebCrypto is unavailable: backup containers need a secure context "+ + "(HTTPS, localhost, or a worker of either)."+ );+ }++ return subtle;+}++/**+ * Runs a byte source through a web `TransformStream` pair, yielding what comes out the other side.+ *+ * The writing half runs as its own task so a full internal queue never deadlocks against an unread+ * output side. Errors are kept apart by origin: a failure thrown by the source itself aborts the+ * transform and resurfaces as that same error, while a failure raised by the transform, i.e. a+ * decode error, surfaces through `translate`. Errors thrown by the consumer of this generator+ * simply stop both halves.+ */+async function* throughWebTransform(+ source: ByteSource,+ transform: { readable: ReadableStream<Uint8Array>; writable: WritableStream<Uint8Array> },+ translate: (error: unknown) => unknown+): AsyncGenerator<Uint8Array> {+ const writer = transform.writable.getWriter();+ const reader = transform.readable.getReader();++ // Set exactly when the source itself failed; the abort carries it to the read side.+ let sourceError: unknown = null;+ const writing = (async () => {+ const iterator = source[Symbol.asyncIterator]();+ for (;;) {+ let next: IteratorResult<Uint8Array>;+ try {+ next = await iterator.next();+ } catch (error) {+ sourceError = error;+ try {+ await writer.abort(error);+ } catch {+ // The transform had already failed on its own; the read side has it.+ }+ return;+ }+ if (next.done) {+ break;+ }+ try {+ await writer.write(next.value);+ } catch {+ // The transform refused the bytes; the read side holds the real error. The source+ // is closed so it does not sit suspended forever.+ try {+ await iterator.return?.(undefined);+ } catch {+ // The source's own cleanup failure has nowhere better to go.+ }+ return;+ }+ }+ try {+ await writer.close();+ } catch {+ // A decode error at the flush; it surfaces on the read side.+ }+ })();++ try {+ for (;;) {+ let result: { done: boolean; value?: Uint8Array };+ try {+ result = await reader.read();+ } catch (error) {+ // A source failure is always recorded before the abort that carries it lands+ // here, so the writing task need not be awaited: it could be sitting on a source+ // that will never speak again.+ throw sourceError ?? translate(error);+ }+ if (result.done || result.value === undefined) {+ break;+ }+ yield result.value;+ }+ // The readable only completes after a clean close, which only a cleanly ended source+ // gets, so this settles promptly and surfaces nothing but its own completion.+ await writing;+ } finally {+ // Unblocks a pending write, which in turn ends the writing task.+ try {+ await reader.cancel();+ } catch {+ // An already-errored readable refuses the cancel; that error has been dealt with.+ }+ }+}diff --git a/packages/trilium-backup-container/src/backend.ts b/packages/trilium-backup-container/src/backend.tsnew file mode 100644index 0000000000..6c0ffc0a25--- /dev/null+++ b/packages/trilium-backup-container/src/backend.ts@@ -0,0 +1,99 @@+import { utf8 } from "./bytes.js";+import { BackupContainerError } from "./errors.js";+import { type ScryptParams, scryptMemoryBytes } from "./format.js";++/** The shape every payload flows through: plain byte chunks, pulled one at a time. */+export type ByteSource = AsyncIterable<Uint8Array>;++/**+ * Where unwrapped or wrapped bytes go. `write` resolves once the destination has taken the chunk+ * and rejects with the destination's own error, which this module passes through untranslated.+ */+export interface ByteSink {+ write(chunk: Uint8Array): Promise<void>;+ end(): Promise<void>;+}++/** Incremental SHA-256, which WebCrypto cannot provide and both directions need. */+export interface StreamingHash {+ update(chunk: Uint8Array): void;+ digest(): Uint8Array;+}++/**+ * The primitives that differ between runtimes. Everything else in this module: the format, the+ * framing, the guards and the progress reporting, is shared verbatim between Node and the browser.+ *+ * The key returned by {@link ContainerBackend.deriveKey} is opaque to the core, which only ever+ * hands it back to the same backend: raw bytes under Node, a non-extractable `CryptoKey` on the+ * web.+ */+export interface ContainerBackend {+ randomBytes(size: number): Uint8Array;+ createSha256(): StreamingHash;+ /**+ * Derives the 32-byte file key with scrypt. The passphrase arrives already NFC-normalised+ * and UTF-8 encoded. Throws whatever the platform throws; the core wraps it.+ */+ deriveKey(+ passphrase: Uint8Array,+ salt: Uint8Array,+ params: ScryptParams,+ maxMemoryBytes: number+ ): Promise<unknown>;+ /** Seals one AES-256-GCM frame. */+ gcmSeal(+ key: unknown,+ nonce: Uint8Array,+ aad: Uint8Array,+ plaintext: Uint8Array+ ): Promise<{ ciphertext: Uint8Array; tag: Uint8Array }>;+ /** Opens one AES-256-GCM frame, answering `null` when authentication fails. */+ gcmOpen(+ key: unknown,+ nonce: Uint8Array,+ aad: Uint8Array,+ ciphertext: Uint8Array,+ tag: Uint8Array+ ): Promise<Uint8Array | null>;+ /** Compresses to a single RFC 1952 gzip stream. */+ gzip(source: ByteSource, level: number): ByteSource;+ /**+ * Decompresses a single gzip stream. A stream the decoder cannot make sense of must surface as+ * a `damaged-payload` {@link BackupContainerError}; errors thrown by `source` itself must pass+ * through untranslated.+ */+ gunzip(source: ByteSource): ByteSource;+}++/**+ * OpenSSL needs a little more than the `128 * N * r` working set, so the ceiling handed to the+ * backend 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:+ * no JavaScript runtime normalises implicitly, so a composed and a decomposed `é` would otherwise+ * derive different keys on different machines.+ */+export async function deriveContainerKey(+ backend: ContainerBackend,+ passphrase: string,+ salt: Uint8Array,+ params: ScryptParams+): Promise<unknown> {+ const secret = utf8(passphrase.normalize("NFC"));+ const maxMemoryBytes = scryptMemoryBytes(params) + MAXMEM_SLACK_BYTES;++ try {+ return await backend.deriveKey(secret, salt, params, maxMemoryBytes);+ } catch (error) {+ throw new BackupContainerError(+ "invalid-kdf-params",+ `Key derivation failed: ${(error as Error).message}`+ );+ }+}diff --git a/packages/trilium-backup-container/src/byte-reader.ts b/packages/trilium-backup-container/src/byte-reader.tsindex 3ccead8c67..5c1c0dfa6b 100644--- a/packages/trilium-backup-container/src/byte-reader.ts+++ b/packages/trilium-backup-container/src/byte-reader.ts@@ -1,18 +1,20 @@-import type { Readable } from "node:stream";-+import type { ByteSource } from "./backend.js";+import { concatBytes } from "./bytes.js";import { BackupContainerError } from "./errors.js";-/** Pull-based view over a readable stream, so the reader can ask for exact byte counts. */+const EMPTY = new Uint8Array(0);++/** Pull-based view over a byte source, so the reader can ask for exact byte counts. */export class ByteReader {- readonly #iterator: AsyncIterator<Buffer>;- #pending: Buffer[] = [];+ readonly #iterator: AsyncIterator<Uint8Array>;+ #pending: Uint8Array[] = [];#pendingBytes = 0;#exhausted = false;#consumed = 0;- constructor(stream: Readable) {- this.#iterator = stream[Symbol.asyncIterator]() as AsyncIterator<Buffer>;+ constructor(source: ByteSource) {+ this.#iterator = source[Symbol.asyncIterator]();}/** Bytes handed out so far, which is the offset a failure should be reported at. */@@ -21,7 +23,7 @@ export class ByteReader {}/** Reads exactly `count` bytes, or throws `truncated`. */- async readExactly(count: number): Promise<Buffer> {+ async readExactly(count: number): Promise<Uint8Array> {await this.#buffer(count);if (this.#pendingBytes < count) {@@ -35,7 +37,7 @@ export class ByteReader {}/** Reads up to `count` bytes, returning fewer at end of input. */- async readUpTo(count: number): Promise<Buffer> {+ async readUpTo(count: number): Promise<Uint8Array> {await this.#buffer(count);return this.#take(Math.min(count, this.#pendingBytes));@@ -59,15 +61,14 @@ export class ByteReader {}}- #take(count: number): Buffer {+ #take(count: number): Uint8Array {if (count === 0) {- return Buffer.alloc(0);+ return EMPTY;}- const merged = this.#pending.length === 1 ? this.#pending[0] : Buffer.concat(- this.#pending,- this.#pendingBytes- );+ const merged = this.#pending.length === 1+ ? this.#pending[0]+ : concatBytes(...this.#pending);const taken = merged.subarray(0, count);const rest = merged.subarray(count);diff --git a/packages/trilium-backup-container/src/bytes.spec.ts b/packages/trilium-backup-container/src/bytes.spec.tsnew file mode 100644index 0000000000..7573e52051--- /dev/null+++ b/packages/trilium-backup-container/src/bytes.spec.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest";++import {+ bytesEqual,+ concatBytes,+ constantTimeEqual,+ readU16BE,+ readU16LE,+ readU32LE,+ readU64LE,+ utf8,+ writeU16LE,+ writeU32LE,+ writeU64LE+} from "./bytes.js";++describe("byte equality", () => {+ it.each([+ [ "bytesEqual", bytesEqual ],+ [ "constantTimeEqual", constantTimeEqual ]+ ])("%s compares contents and refuses mismatched lengths", (_label, equal) => {+ expect(equal(utf8("abc"), utf8("abc"))).toBe(true);+ expect(equal(utf8("abc"), utf8("abd"))).toBe(false);+ expect(equal(utf8("abc"), utf8("abcd"))).toBe(false);+ expect(equal(new Uint8Array(0), new Uint8Array(0))).toBe(true);+ });+});++describe("concatBytes", () => {+ it("joins parts in order and copes with none", () => {+ expect(concatBytes(utf8("ab"), new Uint8Array(0), utf8("c"))).toEqual(utf8("abc"));+ expect(concatBytes()).toHaveLength(0);+ });+});++describe("integer accessors", () => {+ it("round-trip little-endian values at an offset, even on a subarray", () => {+ const bytes = new Uint8Array(32).subarray(4);++ writeU16LE(bytes, 1, 0xbeef);+ expect(readU16LE(bytes, 1)).toBe(0xbeef);++ writeU32LE(bytes, 3, 0xdead_beef);+ expect(readU32LE(bytes, 3)).toBe(0xdead_beef);++ writeU64LE(bytes, 7, 2n ** 53n);+ expect(readU64LE(bytes, 7)).toBe(2n ** 53n);+ });++ it("reads big-endian, which only the SQLite page size needs", () => {+ expect(readU16BE(new Uint8Array([ 0x10, 0x00 ]), 0)).toBe(4096);+ });+});diff --git a/packages/trilium-backup-container/src/bytes.ts b/packages/trilium-backup-container/src/bytes.tsnew file mode 100644index 0000000000..b46a1ab0c8--- /dev/null+++ b/packages/trilium-backup-container/src/bytes.ts@@ -0,0 +1,96 @@+/**+ * Byte-level helpers over plain `Uint8Array`, so the whole format layer runs identically under+ * Node and in a browser. Nothing in this module may touch `Buffer` or any other runtime-specific+ * type: these helpers exist precisely so nothing else has to.+ */++const encoder = new TextEncoder();++/**+ * Encodes text as UTF-8. The format's magic strings are pure ASCII, for which UTF-8 and Latin-1+ * agree byte for byte.+ */+export function utf8(text: string): Uint8Array {+ return encoder.encode(text);+}++export function concatBytes(...parts: Uint8Array[]): Uint8Array {+ let total = 0;+ for (const part of parts) {+ total += part.length;+ }++ const merged = new Uint8Array(total);+ let offset = 0;+ for (const part of parts) {+ merged.set(part, offset);+ offset += part.length;+ }++ return merged;+}++/** Plain equality, for public values such as magics. Not for tags or digests. */+export function bytesEqual(first: Uint8Array, second: Uint8Array): boolean {+ if (first.length !== second.length) {+ return false;+ }++ for (let index = 0; index < first.length; index++) {+ if (first[index] !== second[index]) {+ return false;+ }+ }++ return true;+}++/**+ * Constant-time equality for values a timing side channel could otherwise leak, i.e. the payload+ * digest. Reads every byte whatever it finds along the way.+ */+export function constantTimeEqual(first: Uint8Array, second: Uint8Array): boolean {+ if (first.length !== second.length) {+ return false;+ }++ let difference = 0;+ for (let index = 0; index < first.length; index++) {+ difference |= first[index] ^ second[index];+ }++ return difference === 0;+}++export function readU16LE(bytes: Uint8Array, offset: number): number {+ return viewOf(bytes).getUint16(offset, true);+}++export function writeU16LE(bytes: Uint8Array, offset: number, value: number): void {+ viewOf(bytes).setUint16(offset, value, true);+}++export function readU16BE(bytes: Uint8Array, offset: number): number {+ return viewOf(bytes).getUint16(offset, false);+}++export function readU32LE(bytes: Uint8Array, offset: number): number {+ return viewOf(bytes).getUint32(offset, true);+}++export function writeU32LE(bytes: Uint8Array, offset: number, value: number): void {+ viewOf(bytes).setUint32(offset, value, true);+}++export function readU64LE(bytes: Uint8Array, offset: number): bigint {+ return viewOf(bytes).getBigUint64(offset, true);+}++export function writeU64LE(bytes: Uint8Array, offset: number, value: bigint): void {+ viewOf(bytes).setBigUint64(offset, value, true);+}++/** A view over exactly the array's own span, which `subarray` slices would otherwise escape. */+function viewOf(bytes: Uint8Array): DataView {+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+}diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.tsindex 247384a36e..ef0e25f545 100644--- a/packages/trilium-backup-container/src/container.spec.ts+++ b/packages/trilium-backup-container/src/container.spec.ts@@ -10,7 +10,8 @@ import {HEADER_BYTES_PLAIN,TAG_BYTES} from "./format.js";-import { peekBackupContainer, readBackupContainer } from "./read.js";+import { readBackupContainer, writeBackupContainer } from "./node-streams.js";+import { peekBackupContainer } from "./read.js";import {chunked,fakeDatabase,@@ -20,11 +21,9 @@ import {MemorySink,reasonOf,readFromBuffer,+ type WriteOptions,writeToBuffer} from "./test-helpers.js";-import { writeBackupContainer, type WriteBackupContainerOptions } from "./write.js";--type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;type PeekCase = [string, WriteOptions, { compressed: boolean; encrypted: boolean }];const PASSPHRASE = "correct horse battery staple";@@ -110,7 +109,7 @@ describe("payload digest", () => {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(Buffer.from(written.result.digest).equals(stored)).toBe(true);expect(written.result.payloadBytes).toBe(payload.length);});diff --git a/packages/trilium-backup-container/src/cross-backend.spec.ts b/packages/trilium-backup-container/src/cross-backend.spec.tsnew file mode 100644index 0000000000..1c14c75299--- /dev/null+++ b/packages/trilium-backup-container/src/cross-backend.spec.ts@@ -0,0 +1,295 @@+import { createHash } from "node:crypto";+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 {+ failureOfWeb,+ fakeDatabase,+ FAST_SCRYPT,+ flipByte,+ readFromBuffer,+ readFromBufferWeb,+ reasonOf,+ webSource,+ type WriteOptions,+ writeToBuffer,+ writeToBufferWeb+} from "./test-helpers.js";+import { readBackupContainer as readBackupContainerWeb } from "./web-streams.js";++const PASSPHRASE = "correct horse battery staple";++/** Every format combination, since the backends must agree on all of them. */+const FORMATS: [string, WriteOptions][] = [+ [ "plain", {} ],+ [ "compressed", { compress: true } ],+ [ "encrypted", { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT } ],+ [ "compressed and encrypted", { compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT } ]+];++describe("cross-backend round trips", () => {+ it.each(FORMATS)("what Node writes, the web reads: %s", async (_label, options) => {+ const database = fakeDatabase(64 * 1024);+ const written = await writeToBuffer(database, {+ ...options,+ plaintextSize: database.length+ });++ const read = await readFromBufferWeb(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ expect(read.result).toMatchObject({+ compressed: options.compress === true,+ encrypted: options.passphrase !== undefined,+ bytesWritten: database.length+ });+ });++ it.each(FORMATS)("what the web writes, Node reads: %s", async (_label, options) => {+ const database = fakeDatabase(64 * 1024);+ const written = await writeToBufferWeb(database, {+ ...options,+ plaintextSize: database.length+ });++ const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ expect(read.result.bytesWritten).toBe(database.length);+ });++ it.each(FORMATS)("what the web writes, the web reads: %s", async (_label, options) => {+ const database = fakeDatabase(64 * 1024);+ const written = await writeToBufferWeb(database, {+ ...options,+ plaintextSize: database.length+ });++ const read = await readFromBufferWeb(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ });++ it("writes byte-identical plain containers on both backends", async () => {+ const database = fakeDatabase(9_000);++ const node = await writeToBuffer(database, { plaintextSize: database.length });+ const web = await writeToBufferWeb(database, { plaintextSize: database.length });++ expect(web.bytes.equals(node.bytes)).toBe(true);+ });++ it("survives web input arriving in awkward chunks", async () => {+ const database = fakeDatabase(9_000);+ const written = await writeToBufferWeb(webSource(database, 7), {+ compress: true,+ passphrase: PASSPHRASE,+ scrypt: FAST_SCRYPT+ });++ const read = await readFromBufferWeb(written.bytes, { passphrase: PASSPHRASE });+ expect(read.bytes.equals(database)).toBe(true);+ });++ it("frames a multi-frame payload the same way", async () => {+ const database = fakeDatabase(2 * FRAME_SIZE + 1_000);+ const written = await writeToBufferWeb(database, {+ 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 writeToBufferWeb(+ Buffer.alloc(0),+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }+ );++ const read = await readFromBufferWeb(+ written.bytes,+ { passphrase: PASSPHRASE, requireSqliteHeader: false }+ );+ expect(read.result.bytesWritten).toBe(0);+ });+});++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);++ expect(payload.readUInt16BE(0)).toBe(0x1f8b);+ 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("web failure reasons", () => {+ const encrypted = () => writeToBuffer(+ fakeDatabase(2 * FRAME_SIZE),+ { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT }+ );++ it("rejects the wrong passphrase, and a missing one separately", async () => {+ const written = await encrypted();++ expect(await failureOfWeb(written.bytes, { passphrase: "wrong" }))+ .toBe("wrong-passphrase-or-damaged-header");+ expect(await failureOfWeb(written.bytes)).toBe("passphrase-required");+ });++ 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 recovered = await readFromBufferWeb(+ damaged,+ { passphrase: PASSPHRASE, skipVerifier: true }+ );+ expect(recovered.bytes.equals(fakeDatabase(2 * FRAME_SIZE))).toBe(true);+ });++ it("rejects a flipped bit inside a frame", async () => {+ const written = await encrypted();+ const damaged = flipByte(written.bytes, 200);++ expect(await failureOfWeb(damaged, { passphrase: PASSPHRASE })).toBe("damaged-payload");+ });++ it("rejects trailing data and truncation", async () => {+ const written = await encrypted();++ const extended = Buffer.concat([ written.bytes, Buffer.from("extra") ]);+ expect(await failureOfWeb(extended, { passphrase: PASSPHRASE })).toBe("trailing-data");++ const cut = written.bytes.subarray(0, written.bytes.length - 10);+ expect(await failureOfWeb(cut, { passphrase: PASSPHRASE })).toBe("truncated");+ });++ 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 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+ );++ 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++ expect(await failureOfWeb(damaged)).toBe("digest-mismatch");+ });++ it("stops output that would exceed the ceiling", async () => {+ const written = await writeToBuffer(fakeDatabase(64 * 1024), { compress: true });++ expect(await failureOfWeb(written.bytes, { maxOutputBytes: 1_000 }))+ .toBe("output-too-large");+ });++ it("rejects a payload that is not a database", async () => {+ const written = await writeToBuffer(Buffer.from("this is not a database, it is a note"));++ expect(await failureOfWeb(written.bytes)).toBe("not-a-database");+ });++ it.each([+ [ "a plain container", {} ],+ [ "a compressed container", { compress: true } ]+ ] as [string, WriteOptions][])(+ "lets a destination error through untranslated, reading %s",+ async (_label, options) => {+ const written = await writeToBuffer(fakeDatabase(64 * 1024), options);+ const failing = new WritableStream<Uint8Array>({+ write() {+ throw new Error("ENOSPC: no space left on device");+ }+ });++ const read = readBackupContainerWeb(webSource(written.bytes), failing);++ await expect(read).rejects.toThrow(/ENOSPC/);+ }+ );+});++describe("web transform plumbing", () => {+ it("surfaces a compressor failure untranslated, and stops the source", async () => {+ let sourceClosed = false;+ const poisoned = (async function* (): AsyncGenerator<Uint8Array> {+ try {+ // Not a byte chunk at all, which the compressor rejects mid-write.+ yield {} as unknown as Uint8Array;+ yield fakeDatabase(1024);+ } finally {+ sourceClosed = true;+ }+ })();++ const error = await consume(webBackend.gzip(poisoned, 6)).catch((thrown) => thrown);++ // Untranslated: a compressor failure is not a damaged payload.+ expect(error).toBeInstanceOf(Error);+ expect((error as { reason?: string }).reason).toBeUndefined();+ expect(sourceClosed).toBe(true);+ });+});++describe("web progress", () => {+ it("reports the database coming out, up to and including a final 1", async () => {+ const reports: number[] = [];+ const database = fakeDatabase(2 * FRAME_SIZE);+ const written = await writeToBuffer(database, { plaintextSize: database.length });++ await readFromBufferWeb(written.bytes, {+ onProgress: (progress) => reports.push(progress),+ progressIntervalMs: 0+ });++ expect(reports.at(-1)).toBe(1);+ expect(reports.every((progress) => progress > 0 && progress <= 1)).toBe(true);+ expect([ ...reports ].sort((first, second) => first - second)).toEqual(reports);+ });+});++describe("without WebCrypto", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("refuses encryption with an explanation rather than an undefined access", async () => {+ // What a plain-HTTP page sees: randomness exists, `subtle` does not.+ vi.stubGlobal("crypto", {+ getRandomValues: (target: Uint8Array) => target.fill(7)+ });++ let message = "did not throw";+ const reason = await reasonOf(+ writeToBufferWeb(fakeDatabase(), { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT })+ .catch((error: Error) => {+ message = error.message;+ throw error;+ })+ );++ expect(reason).toBe("invalid-kdf-params");+ expect(message).toMatch(/secure context/);+ });+});++async function consume(source: AsyncIterable<Uint8Array>): Promise<void> {+ for await (const chunk of source) {+ void chunk;+ }+}diff --git a/packages/trilium-backup-container/src/crypto.ts b/packages/trilium-backup-container/src/crypto.tsdeleted file mode 100644index 7716621761..0000000000--- a/packages/trilium-backup-container/src/crypto.ts+++ /dev/null@@ -1,134 +0,0 @@-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/file-destination.spec.ts b/packages/trilium-backup-container/src/file-destination.spec.tsindex 8b28fab12c..c102968eb8 100644--- a/packages/trilium-backup-container/src/file-destination.spec.ts+++ b/packages/trilium-backup-container/src/file-destination.spec.ts@@ -4,9 +4,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";-import { readBackupContainer } from "./read.js";+import { readBackupContainer, writeBackupContainer } from "./node-streams.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", () => {diff --git a/packages/trilium-backup-container/src/format.spec.ts b/packages/trilium-backup-container/src/format.spec.tsindex 9b63aba98b..2beccc9065 100644--- a/packages/trilium-backup-container/src/format.spec.ts+++ b/packages/trilium-backup-container/src/format.spec.ts@@ -55,7 +55,7 @@ function encryptedHeader(): ContainerHeader {describe("header layout", () => {it("round-trips an unencrypted header and matches the documented offsets", () => {- const bytes = encodeHeader(plainHeader());+ const bytes = Buffer.from(encodeHeader(plainHeader()));expect(bytes).toHaveLength(64);expect(bytes.subarray(0, 20).toString("ascii")).toBe("Trilium Notes Backup");@@ -73,12 +73,12 @@ describe("header layout", () => {plaintextSize: 4096});expect(decoded.encryption).toBeNull();- expect(decoded.digest.equals(Buffer.alloc(32, 7))).toBe(true);+ 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", () => {const header = encryptedHeader();- const bytes = encodeHeader(header);+ const bytes = Buffer.from(encodeHeader(header));expect(bytes).toHaveLength(108);expect(bytes.readUInt8(21)).toBe(0b10);@@ -90,13 +90,15 @@ describe("header layout", () => {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.encryption ? Buffer.from(decoded.encryption.salt) : null)+ .toEqual(Buffer.alloc(16, 1));+ expect(decoded.encryption ? Buffer.from(decoded.encryption.verifierTag) : null)+ .toEqual(Buffer.alloc(16, 3));expect(decoded.plaintextSize).toBe(123456789);});it("treats an unrepresentable plaintext size as unknown, so it can never widen a bound", () => {- const bytes = encodeHeader(plainHeader());+ const bytes = Buffer.from(encodeHeader(plainHeader()));bytes.writeBigUInt64LE(2n ** 63n, 24);expect(decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES).plaintextSize).toBe(0);@@ -106,14 +108,15 @@ describe("header layout", () => {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");+ expect(nonceFor(prefix, 0)).not.toEqual(nonceFor(prefix, 1));+ expect(Buffer.from(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);+ const bytes = Buffer.from(encodeHeader(plainHeader())).subarray(0, FIXED_HEADER_BYTES);mutate(bytes);return () => decodeFixedHeader(bytes, max);@@ -159,7 +162,7 @@ describe("fixed header validation", () => {});it("rejects a KDF id it does not implement", () => {- const bytes = encodeHeader(encryptedHeader());+ const bytes = Buffer.from(encodeHeader(encryptedHeader()));bytes.writeUInt8(2, 32);expect(() => decodeHeader(bytes, DEFAULT_MAX_HEADER_BYTES)).toThrow(@@ -215,7 +218,7 @@ describe("SQLite header check", () => {function sqliteHead(pageSize: number): Buffer {const head = Buffer.alloc(18);- SQLITE_MAGIC.copy(head, 0);+ head.set(SQLITE_MAGIC, 0);head.writeUInt16BE(pageSize, 16);return head;diff --git a/packages/trilium-backup-container/src/format.ts b/packages/trilium-backup-container/src/format.tsindex 3cc9219534..4141a62f00 100644--- a/packages/trilium-backup-container/src/format.ts+++ b/packages/trilium-backup-container/src/format.ts@@ -1,7 +1,17 @@+import {+ bytesEqual,+ readU16BE,+ readU16LE,+ readU64LE,+ utf8,+ writeU16LE,+ writeU32LE,+ writeU64LE+} from "./bytes.js";import { BackupContainerError } from "./errors.js";/** ASCII magic that opens every container. */-export const MAGIC = Buffer.from("Trilium Notes Backup", "ascii");+export const MAGIC = utf8("Trilium Notes Backup");/** Format version this module reads and writes. Version 0 is never valid. */export const FORMAT_VERSION = 1;@@ -52,7 +62,7 @@ export const DEFAULT_MAX_KDF_MEMORY_BYTES = 512 * 1024 * 1024;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");+export const SQLITE_MAGIC = utf8("SQLite format 3\0");/** Bytes of output needed before the SQLite header can be checked. */export const SQLITE_HEADER_BYTES = 18;@@ -65,9 +75,9 @@ export interface ScryptParams {export interface EncryptionHeader extends ScryptParams {kdfId: number;- salt: Buffer;- noncePrefix: Buffer;- verifierTag: Buffer;+ salt: Uint8Array;+ noncePrefix: Uint8Array;+ verifierTag: Uint8Array;}export interface ContainerHeader {@@ -81,7 +91,7 @@ export interface ContainerHeader {plaintextSize: number;headerLength: number;encryption: EncryptionHeader | null;- digest: Buffer;+ digest: Uint8Array;}/** Header length implied by the flags, which readers require exactly. */@@ -111,10 +121,10 @@ export function scryptMemoryBytes({ log2N, r }: ScryptParams): number {}/** 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);+export function nonceFor(noncePrefix: Uint8Array, counter: number): Uint8Array {+ const nonce = new Uint8Array(NONCE_BYTES);+ nonce.set(noncePrefix, 0);+ writeU32LE(nonce, NONCE_PREFIX_BYTES, counter);return nonce;}@@ -122,29 +132,29 @@ export function nonceFor(noncePrefix: Buffer, counter: number): Buffer {* 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);+export function encodeHeader(header: ContainerHeader): Uint8Array {+ const buffer = new Uint8Array(header.headerLength);- MAGIC.copy(buffer, 0);- buffer.writeUInt8(header.version, MAGIC.length);+ buffer.set(MAGIC, 0);+ buffer[MAGIC.length] = header.version;const compressed = header.compressed ? FLAG_COMPRESSED : 0;const encrypted = header.encrypted ? FLAG_ENCRYPTED : 0;- buffer.writeUInt8(compressed | encrypted, 21);- buffer.writeUInt16LE(header.headerLength, 22);- buffer.writeBigUInt64LE(BigInt(header.plaintextSize), 24);+ buffer[21] = compressed | encrypted;+ writeU16LE(buffer, 22, header.headerLength);+ writeU64LE(buffer, 24, BigInt(header.plaintextSize));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);+ buffer[32] = kdfId;+ buffer[33] = log2N;+ buffer[34] = r;+ buffer[35] = p;+ buffer.set(salt, 36);+ buffer.set(noncePrefix, 52);+ buffer.set(verifierTag, 60);}- header.digest.copy(buffer, digestOffset(header.headerLength));+ buffer.set(header.digest, digestOffset(header.headerLength));return buffer;}@@ -164,15 +174,15 @@ export interface FixedHeader {* @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)) {+export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): FixedHeader {+ if (!bytesEqual(buffer.subarray(0, MAGIC.length), MAGIC)) {throw new BackupContainerError("not-a-container","File does not start with the container magic.");}- const version = buffer.readUInt8(MAGIC.length);+ const version = buffer[MAGIC.length];if (version === 0) {throw new BackupContainerError("unsupported-version", "Version 0 is never valid.");}@@ -183,7 +193,7 @@ export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): Fixed);}- const flags = buffer.readUInt8(21);+ const flags = buffer[21];if (flags & FLAG_RESERVED) {throw new BackupContainerError("unsupported-flags",@@ -192,7 +202,7 @@ export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): Fixed}const encrypted = (flags & FLAG_ENCRYPTED) !== 0;- const headerLength = buffer.readUInt16LE(22);+ const headerLength = readU16LE(buffer, 22);if (headerLength > maxHeaderBytes) {throw new BackupContainerError("invalid-header-length",@@ -209,7 +219,7 @@ export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): Fixed// A hint that may only ever tighten a bound, so an unrepresentable value is the same as// "unknown".- const plaintextSize = buffer.readBigUInt64LE(24);+ const plaintextSize = readU64LE(buffer, 24);return {version,@@ -224,12 +234,12 @@ export function decodeFixedHeader(buffer: Buffer, maxHeaderBytes: number): Fixed* Parses the fields after the fixed header. `buffer` is the whole header, `headerLength` bytes* long.*/-export function decodeHeader(buffer: Buffer, maxHeaderBytes: number): ContainerHeader {+export function decodeHeader(buffer: Uint8Array, 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);+ const kdfId = buffer[32];if (kdfId !== KDF_SCRYPT) {throw new BackupContainerError("unsupported-kdf",@@ -239,9 +249,9 @@ export function decodeHeader(buffer: Buffer, maxHeaderBytes: number): ContainerHencryption = {kdfId,- log2N: buffer.readUInt8(33),- r: buffer.readUInt8(34),- p: buffer.readUInt8(35),+ log2N: buffer[33],+ r: buffer[34],+ p: buffer[35],salt: buffer.subarray(36, 52),noncePrefix: buffer.subarray(52, 60),verifierTag: buffer.subarray(60, 76)@@ -290,9 +300,9 @@ export function validateScryptParams(params: ScryptParams, maxMemoryBytes: numbe** @param head at least {@link SQLITE_HEADER_BYTES} bytes from offset 0 of the output.*/-export function validateSqliteHeader(head: Buffer): void {+export function validateSqliteHeader(head: Uint8Array): void {const magicMatches = head.length >= SQLITE_HEADER_BYTES- && head.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC);+ && bytesEqual(head.subarray(0, SQLITE_MAGIC.length), SQLITE_MAGIC);if (!magicMatches) {throw new BackupContainerError(@@ -302,7 +312,7 @@ export function validateSqliteHeader(head: Buffer): void {}// Big-endian, and the value 1 encodes 65536 because that does not fit the field.- const pageSize = head.readUInt16BE(16);+ const pageSize = readU16BE(head, 16);const isPowerOfTwo = pageSize >= 512 && pageSize <= 32768 && (pageSize & (pageSize - 1)) === 0;if (pageSize !== 1 && !isPowerOfTwo) {throw new BackupContainerError(diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.tsindex 2c7dc1e4ce..6458cc5e41 100644--- a/packages/trilium-backup-container/src/index.ts+++ b/packages/trilium-backup-container/src/index.ts@@ -2,9 +2,14 @@* Reader and writer for the Trilium backup container: one SQLite database wrapped with* optional gzip compression and optional AES-256-GCM encryption.*- * The module depends on nothing outside the Node standard library, carries no translated strings,- * and reports every failure as a {@link BackupContainerError} whose `reason` is a stable- * machine-readable code the caller maps to its own messages.+ * This is the Node entry point, which depends on nothing outside the Node standard library and+ * takes Node streams. The browser entry point lives at `@triliumnext/backup-container/web`: the+ * same operations on Web Streams, with WebCrypto and `@noble/hashes` underneath. The format layer+ * and every check are shared between the two, so a container written by either is read by both.+ *+ * The module 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@@ -53,6 +58,7 @@ export {SCRYPT_DEFAULTS,type ScryptParams} from "./format.js";+export { readBackupContainer, writeBackupContainer } from "./node-streams.js";export {DEFAULT_PROGRESS_INTERVAL_MS,type ProgressCallback,@@ -62,13 +68,11 @@ export {type BackupContainerInfo,DEFAULT_MAX_OUTPUT_BYTES,peekBackupContainer,- 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.tsindex 458200007e..2cbaf0215c 100644--- a/packages/trilium-backup-container/src/internals.spec.ts+++ b/packages/trilium-backup-container/src/internals.spec.ts@@ -1,22 +1,20 @@import { createHash, randomBytes } from "node:crypto";import { Readable } from "node:stream";-import { pipeline } from "node:stream/promises";import { describe, expect, it } from "vitest";+import { nodeBackend } from "./backend-node.js";+import { deriveContainerKey } from "./backend.js";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,failureOf,flipByte,- MemorySink,reasonOf,- readFromBuffer,writeToBuffer} from "./test-helpers.js";+import { encryptFrames } from "./write.js";describe("BackupContainerError", () => {it("narrows only its own errors", () => {@@ -30,14 +28,15 @@ describe("BackupContainerError", () => {describe("ByteReader", () => {const reader = (...chunks: Buffer[]) => new ByteReader(Readable.from(chunks));+ const text = (bytes: Uint8Array) => Buffer.from(bytes).toString();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(text(await subject.readExactly(4))).toBe("abcd");expect(subject.consumed).toBe(4);- expect((await subject.readExactly(1)).toString()).toBe("e");- expect((await subject.readUpTo(99)).toString()).toBe("fgh");+ expect(text(await subject.readExactly(1))).toBe("e");+ expect(text(await subject.readUpTo(99))).toBe("fgh");expect(await subject.atEof()).toBe(true);});@@ -45,7 +44,7 @@ describe("ByteReader", () => {const subject = reader(Buffer.from("ab"));expect(await subject.readUpTo(0)).toHaveLength(0);- expect((await subject.readUpTo(10)).toString()).toBe("ab");+ expect(text(await subject.readUpTo(10))).toBe("ab");expect(await subject.readUpTo(10)).toHaveLength(0);});@@ -56,22 +55,37 @@ describe("ByteReader", () => {});});-describe("FrameEncryptor", () => {+describe("encryptFrames", () => {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())+ const frames = encryptFrames(+ nodeBackend,+ randomBytes(32),+ randomBytes(8),+ Buffer.alloc(60),+ Readable.from([ Buffer.alloc(2 * FRAME_SIZE) ]),+ 0);+ const reason = await reasonOf((async () => {+ for await (const frame of frames) {+ void frame;+ }+ })());+expect(reason).toBe("payload-too-large");});});-describe("deriveKey", () => {+describe("deriveContainerKey", () => {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" });+ const derivation = deriveContainerKey(+ nodeBackend,+ "passphrase",+ new Uint8Array(16),+ { log2N: 10, r: 0, p: 1 }+ );++ await expect(derivation).rejects.toMatchObject({ reason: "invalid-kdf-params" });});});@@ -88,4 +102,23 @@ describe("compressed payload damage", () => {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++ expect(await failureOf(damaged)).toBe("digest-mismatch");+ });++ it("lets a failing input through the compressor untranslated", async () => {+ const input = Readable.from((async function* (): AsyncGenerator<Buffer> {+ yield fakeDatabase(1024);+ throw new Error("EIO: input went away");+ })());++ const reason = await reasonOf(writeToBuffer(input, { compress: true }));++ // Untranslated: an input failure is not a damaged payload.+ expect(reason).toMatch(/no reason: Error: EIO/);+ });});diff --git a/packages/trilium-backup-container/src/node-streams.ts b/packages/trilium-backup-container/src/node-streams.tsnew file mode 100644index 0000000000..e453072632--- /dev/null+++ b/packages/trilium-backup-container/src/node-streams.ts@@ -0,0 +1,84 @@+import type { Readable, Writable } from "node:stream";+import { finished } from "node:stream/promises";++import { nodeBackend } from "./backend-node.js";+import type { ByteSink } from "./backend.js";+import {+ readContainer,+ type ReadBackupContainerOptions,+ type ReadBackupContainerResult+} from "./read.js";+import {+ type WriteBackupContainerOptions,+ type WriteBackupContainerResult,+ writeContainer+} from "./write.js";++/**+ * Unwraps a container back into a database. The Node entry point: takes Node streams and runs on+ * the Node standard library alone. See {@link readContainer} for the semantics.+ *+ * @param input the container bytes.+ * @param output the destination for the database, which is ended by this call.+ */+export async function readBackupContainer(+ input: Readable,+ output: Writable,+ options: ReadBackupContainerOptions = {}+): Promise<ReadBackupContainerResult> {+ try {+ return await readContainer(input, sinkFor(output), nodeBackend, options);+ } catch (error) {+ destroyBoth(input, output);+ throw error;+ }+}++/**+ * Wraps a database into a container. The Node entry point: takes Node streams and runs on the+ * Node standard library alone. See {@link writeContainer} for the semantics.+ *+ * @param input the database bytes.+ * @param output the destination, which is ended by this call.+ */+export async function writeBackupContainer(+ input: Readable,+ output: Writable,+ options: WriteBackupContainerOptions+): Promise<WriteBackupContainerResult> {+ try {+ return await writeContainer(input, sinkFor(output), nodeBackend, options);+ } catch (error) {+ destroyBoth(input, output);+ throw error;+ }+}++/**+ * A {@link ByteSink} over a Node writable. Chunks resolve through `write`'s own callback, so a+ * destination failure surfaces as the destination's own error, exactly where it happened.+ */+function sinkFor(output: Writable): ByteSink {+ // A failing destination reports through the write callback below, but it also emits `error`,+ // which with nobody listening would escalate into an uncaught exception. `pipeline` used to be+ // that listener.+ output.on("error", () => {});++ return {+ write(chunk) {+ return new Promise<void>((resolve, reject) => {+ output.write(chunk, (error) => (error ? reject(error) : resolve()));+ });+ },+ async end() {+ output.end();+ await finished(output);+ }+ };+}++/** What `stream.pipeline` would have done on failure: neither stream is left half-open. */+function destroyBoth(input: Readable, output: Writable): void {+ input.destroy();+ output.destroy();+}diff --git a/packages/trilium-backup-container/src/progress.spec.ts b/packages/trilium-backup-container/src/progress.spec.tsindex 2e9c07c63d..aa8dbc3bb8 100644--- a/packages/trilium-backup-container/src/progress.spec.ts+++ b/packages/trilium-backup-container/src/progress.spec.ts@@ -2,7 +2,8 @@ import { Readable } from "node:stream";import { afterEach, describe, expect, it, vi } from "vitest";import { FRAME_SIZE } from "./format.js";-import { readBackupContainer, type ReadBackupContainerOptions } from "./read.js";+import { readBackupContainer } from "./node-streams.js";+import type { ReadBackupContainerOptions } from "./read.js";import {chunked,fakeDatabase,@@ -10,11 +11,9 @@ import {MemorySink,reasonOf,readFromBuffer,+ type WriteOptions,writeToBuffer} from "./test-helpers.js";-import type { WriteBackupContainerOptions } from "./write.js";--type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;const PASSPHRASE = "correct horse battery staple";@@ -234,18 +233,26 @@ describe("reading", () => {describe("throttling", () => {it("reports at most once per interval, whatever the clock does in between", async () => {- const { reports, onProgress } = collector();+ const reports: { progress: number; at: number }[] = [];const database = fakeDatabase(64 * 1024);const clock = mockedClock();- // A hundred milliseconds per chunk against the default interval, so two chunks in three go- // unreported.+ // A hundred milliseconds per chunk against the default interval of 250, so most chunks go+ // unreported. The exact chunks that do report depend on how far the stream buffers ahead,+ // so what is asserted is the throttle contract, not one buffering pattern.await writeToBuffer(ticking(chunked(database, 4096), clock, 100), {plaintextSize: database.length,- onProgress+ onProgress: (progress) => reports.push({ progress, at: clock.now })});- expect(reports).toEqual([ 1, 4, 7, 10, 13, 16 ].map((chunk) => chunk / 16).concat(1));+ expect(reports.length).toBeLessThan(17);+ expect(reports.at(-1)?.progress).toBe(1);++ const throttled = reports.slice(0, -1);+ expect(throttled.length).toBeGreaterThan(2);+ for (let index = 1; index < throttled.length; index++) {+ expect(throttled[index].at - throttled[index - 1].at).toBeGreaterThanOrEqual(250);+ }});it("reports the first chunk and the last, however little time passes", async () => {diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.tsindex e9f6bd9a18..1d660e2c90 100644--- a/packages/trilium-backup-container/src/read.ts+++ b/packages/trilium-backup-container/src/read.ts@@ -1,10 +1,11 @@-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 {+ type ByteSink,+ type ByteSource,+ type ContainerBackend,+ deriveContainerKey+} from "./backend.js";+import { bytesEqual, concatBytes, constantTimeEqual, readU32LE } from "./bytes.js";import { ByteReader } from "./byte-reader.js";-import { deriveKey, openFrame, verifyPassphrase } from "./crypto.js";import { BackupContainerError } from "./errors.js";import {authenticatedHeaderEnd,@@ -20,11 +21,16 @@ import {FRAME_LENGTH_MASK,FRAME_SIZE,MAGIC,+ nonceFor,+ SQLITE_HEADER_BYTES,TAG_BYTES,- validateScryptParams+ validateScryptParams,+ validateSqliteHeader,+ VERIFIER_COUNTER} from "./format.js";-import { createProgressReporter, type ProgressOptions } from "./progress.js";-import { OutputGuard } from "./streams.js";+import { createProgressReporter, type ProgressOptions, type ProgressReporter } from "./progress.js";++const EMPTY = new Uint8Array(0);/** Ceiling on unwrapped output when the container does not record a smaller size. */export const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024 * 1024;@@ -68,7 +74,7 @@ export interface BackupContainerInfo {* backups is never derailed by one damaged or foreign file.*/export function peekBackupContainer(- head: Buffer,+ head: Uint8Array,maxHeaderBytes: number = DEFAULT_MAX_HEADER_BYTES): BackupContainerInfo | null {if (head.length < FIXED_HEADER_BYTES) {@@ -98,7 +104,8 @@ export interface ReadBackupContainerResult {}/**- * Unwraps a container back into a database.+ * Unwraps a container back into a database. This is the runtime-neutral core; the Node and web+ * entry points wrap it with their stream types and their backend.** 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@@ -106,19 +113,21 @@ export interface ReadBackupContainerResult {** @param input the container bytes.* @param output the destination for the database, which is ended by this call.+ * @param backend the platform's crypto and compression primitives.* @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,+export async function readContainer(+ input: ByteSource,+ output: ByteSink,+ backend: ContainerBackend,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;+ let key: unknown = null;if (header.encryption) {if (options.passphrase === undefined) {throw new BackupContainerError(@@ -131,15 +140,15 @@ export async function readBackupContainer(header.encryption,options.maxKdfMemoryBytes ?? DEFAULT_MAX_KDF_MEMORY_BYTES);- key = await deriveKey(options.passphrase, header.encryption.salt, header.encryption);+ key = await deriveContainerKey(+ backend,+ options.passphrase,+ header.encryption.salt,+ header.encryption+ );if (options.skipVerifier !== true) {- verifyPassphrase(- key,- header.encryption.noncePrefix,- aadOf(header),- header.encryption.verifierTag- );+ await verifyPassphrase(backend, key, header, header.encryption);}}@@ -154,21 +163,17 @@ export async function readBackupContainer(const progress = createProgressReporter(header.plaintextSize, options);const guard = new OutputGuard(ceiling, options.requireSqliteHeader !== false, progress);- const payload = header.encryption && key- ? readFrames(reader, header, header.encryption, key)- : readPlainPayload(reader, header);+ const payload = header.encryption && key !== null+ ? readFrames(reader, header, header.encryption, key, backend)+ : readPlainPayload(reader, header, backend);- try {- // Spelled out rather than built as an array: the source is an async generator, which only- // the variadic overloads accept.- if (header.compressed) {- await pipeline(payload, createGunzip(), guard, output);- } else {- await pipeline(payload, guard, output);- }- } catch (error) {- throw translatePipelineError(error);+ const unwrapped = header.compressed ? backend.gunzip(payload) : payload;+ for await (const chunk of unwrapped) {+ guard.accept(chunk);+ await output.write(chunk);}+ guard.finish();+ await output.end();if (header.plaintextSize > 0 && guard.bytesWritten !== header.plaintextSize) {throw new BackupContainerError(@@ -188,6 +193,68 @@ export async function readBackupContainer(};}+/**+ * 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.+ *+ * The count it already keeps is what the reader's progress is a fraction of, so the reporting is+ * done from here rather than from a tap of its own.+ */+class OutputGuard {++ #written = 0;+ #head: Uint8Array[] = [];+ #headBytes = 0;+ #headChecked = false;++ constructor(+ private readonly ceiling: number,+ private readonly requireSqliteHeader: boolean,+ private readonly progress: ProgressReporter | null+ ) {}++ get bytesWritten(): number {+ return this.#written;+ }++ /** Vets one chunk on its way to the destination, throwing before a bad one reaches it. */+ accept(chunk: Uint8Array): void {+ if (this.#written + chunk.length > this.ceiling) {+ throw new BackupContainerError(+ "output-too-large",+ `Output would exceed the ${this.ceiling} byte ceiling.`+ );+ }+ 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;+ validateSqliteHeader(concatBytes(...this.#head));+ this.#head = [];+ }+ }++ // Reported only once the chunk has passed every check, so a rejected output never reports+ // having got anywhere.+ this.progress?.at(this.#written);+ }++ /** Called once the payload has ended, to catch an output too short to have been checked. */+ finish(): void {+ if (this.requireSqliteHeader && !this.#headChecked) {+ throw new BackupContainerError(+ "not-a-database",+ "Output is too short to be a SQLite database."+ );+ }+ }++}+async function readHeader(reader: ByteReader, maxHeaderBytes: number): Promise<ContainerHeader> {const fixedBytes = await reader.readUpTo(FIXED_HEADER_BYTES);@@ -195,7 +262,9 @@ async function readHeader(reader: ByteReader, maxHeaderBytes: number): Promise<C// 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)) {+ const couldBeMagic = fixedBytes.length > 0+ && bytesEqual(fixedBytes.subarray(0, prefix.length), prefix);+ if (!couldBeMagic) {throw new BackupContainerError("not-a-container","File does not start with the container magic."@@ -210,29 +279,60 @@ async function readHeader(reader: ByteReader, maxHeaderBytes: number): Promise<Cconst fixed = decodeFixedHeader(fixedBytes, maxHeaderBytes);const rest = await reader.readExactly(fixed.headerLength - FIXED_HEADER_BYTES);- return decodeHeader(Buffer.concat([ fixedBytes, rest ]), maxHeaderBytes);+ return decodeHeader(concatBytes(fixedBytes, rest), maxHeaderBytes);}/** Re-encodes the header so the authenticated span comes from the same layout the writer used. */-function aadOf(header: ContainerHeader): Buffer {+function aadOf(header: ContainerHeader): Uint8Array {return encodeHeader(header).subarray(0, authenticatedHeaderEnd(header.headerLength));}+/**+ * Checks the verifier tag, which tells a wrong passphrase from a usable one before any frame is+ * read: the tag is GCM over an empty plaintext on the reserved counter, so opening it against an+ * empty ciphertext is the check.+ *+ * 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.+ */+async function verifyPassphrase(+ backend: ContainerBackend,+ key: unknown,+ header: ContainerHeader,+ encryption: EncryptionHeader+): Promise<void> {+ const opened = await backend.gcmOpen(+ key,+ nonceFor(encryption.noncePrefix, VERIFIER_COUNTER),+ aadOf(header),+ EMPTY,+ encryption.verifierTag.subarray(0, TAG_BYTES)+ );++ if (opened === null) {+ throw new BackupContainerError(+ "wrong-passphrase-or-damaged-header",+ "Verifier tag did not match."+ );+ }+}+/** 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> {+ key: unknown,+ backend: ContainerBackend+): AsyncGenerator<Uint8Array> {const aad = aadOf(header);- const hash = createHash("sha256");+ const hash = backend.createSha256();let counter = 0;for (;;) {const offset = reader.consumed;const lengthField = await reader.readExactly(4);- const raw = lengthField.readUInt32LE(0);+ const raw = readU32LE(lengthField, 0);const final = (raw & FRAME_FINAL_FLAG) !== 0;const length = raw & FRAME_LENGTH_MASK;@@ -246,18 +346,24 @@ async function* readFrames(const ciphertext = await reader.readExactly(length);const tag = await reader.readExactly(TAG_BYTES);- hash.update(lengthField).update(ciphertext).update(tag);+ hash.update(lengthField);+ hash.update(ciphertext);+ hash.update(tag);- yield openFrame(+ const plaintext = await backend.gcmOpen(key,- encryption.noncePrefix,- aad,- counter,- lengthField,+ nonceFor(encryption.noncePrefix, counter),+ concatBytes(aad, lengthField),ciphertext,- tag,- offset+ tag);+ if (plaintext === null) {+ throw new BackupContainerError(+ "damaged-payload",+ `Frame ${counter} failed authentication at byte offset ${offset}.`+ );+ }+ yield plaintext;if (final) {break;@@ -278,9 +384,10 @@ async function* readFrames(/** 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");+ header: ContainerHeader,+ backend: ContainerBackend+): AsyncGenerator<Uint8Array> {+ const hash = backend.createSha256();for (;;) {const chunk = await reader.readUpTo(FRAME_SIZE);@@ -294,26 +401,11 @@ async function* readPlainPayload(verifyDigest(hash.digest(), header.digest);}-function verifyDigest(actual: Buffer, expected: Buffer): void {- if (!timingSafeEqual(actual, expected)) {+function verifyDigest(actual: Uint8Array, expected: Uint8Array): void {+ if (!constantTimeEqual(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.tsdeleted file mode 100644index bd3db84ffb..0000000000--- a/packages/trilium-backup-container/src/streams.ts+++ /dev/null@@ -1,258 +0,0 @@-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 type { ProgressReporter } from "./progress.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();- }--}--/**- * Passes bytes through untouched while reporting how many of them have gone past.- *- * Sits at the head of the writer's pipeline, where the bytes are still the ones the recorded- * plaintext size counted: further down they are compressed, encrypted, or both, and a fraction of- * those is a fraction of a total nobody knows in advance.- */-export class ProgressTap extends Transform {-- #bytes = 0;-- constructor(private readonly progress: ProgressReporter) {- super();- }-- override _transform(- chunk: Buffer,- _encoding: BufferEncoding,- callback: TransformCallback- ): void {- this.#bytes += chunk.length;- this.progress.at(this.#bytes);- callback(null, chunk);- }--}--/**- * 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.- *- * The count it already keeps is what the reader's progress is a fraction of, so the reporting is- * done from here rather than from a tap of its own.- */-export class OutputGuard extends Transform {-- #written = 0;- #head: Buffer[] = [];- #headBytes = 0;- #headChecked = false;-- constructor(- private readonly ceiling: number,- private readonly requireSqliteHeader: boolean,- private readonly progress: ProgressReporter | null = null- ) {- 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 = [];- }- }-- // Reported only once the chunk has passed every check, so a rejected output never reports- // having got anywhere.- this.progress?.at(this.#written);-- 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.tsindex c610cbeddd..a80dff53a8 100644--- a/packages/trilium-backup-container/src/test-helpers.ts+++ b/packages/trilium-backup-container/src/test-helpers.ts@@ -3,14 +3,14 @@ import { Readable, Writable } from "node:stream";import { SQLITE_MAGIC, type ScryptParams } from "./format.js";import {readBackupContainer,- type ReadBackupContainerOptions,- type ReadBackupContainerResult-} from "./read.js";+ writeBackupContainer+} from "./node-streams.js";+import type { ReadBackupContainerOptions, ReadBackupContainerResult } from "./read.js";import {- writeBackupContainer,- type WriteBackupContainerOptions,- type WriteBackupContainerResult-} from "./write.js";+ readBackupContainer as readBackupContainerWeb,+ writeBackupContainer as writeBackupContainerWeb+} from "./web-streams.js";+import type { WriteBackupContainerOptions, 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 };@@ -37,7 +37,7 @@ export class MemorySink extends Writable {/** 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.set(SQLITE_MAGIC, 0);database.writeUInt16BE(pageSize, 16);database.fill("trilium notes ", 18);@@ -46,12 +46,7 @@ export function fakeDatabase(size = 4096, pageSize = 4096): Buffer {/** 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) ]);+ return Readable.from(chunksOf(data, chunkSize));}export interface WrittenContainer {@@ -60,10 +55,12 @@ export interface WrittenContainer {patchedAt: number[];}+export type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;+/** 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"> = {}+ options: WriteOptions = {}): Promise<WrittenContainer> {const sink = new MemorySink();const patches: { offset: number; data: Buffer }[] = [];@@ -100,6 +97,70 @@ export async function readFromBuffer(return { bytes: sink.toBuffer(), result };}+/** The web counterpart of {@link writeToBuffer}, running the same job through Web Streams. */+export async function writeToBufferWeb(+ input: Buffer | ReadableStream<Uint8Array>,+ 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) }); }+ }+ );++ const bytes = collector.toBuffer();+ for (const patch of patches) {+ patch.data.copy(bytes, patch.offset);+ }++ return { bytes, result, patchedAt: patches.map((patch) => patch.offset) };+}++/** The web counterpart of {@link readFromBuffer}. */+export async function readFromBufferWeb(+ container: Buffer,+ options: ReadBackupContainerOptions = {}+): Promise<ReadContainer> {+ const collector = webCollector();+ const result = await readBackupContainerWeb(webSource(container), collector.stream, options);++ return { bytes: collector.toBuffer(), result };+}++/** A readable Web Stream over a buffer, optionally split so chunk boundaries are exercised. */+export function webSource(data: Buffer, chunkSize = data.length): ReadableStream<Uint8Array> {+ const chunks = chunksOf(data, chunkSize);++ return new ReadableStream<Uint8Array>({+ start(controller) {+ for (const chunk of chunks) {+ controller.enqueue(chunk);+ }+ controller.close();+ }+ });+}++/** A writable Web Stream that collects everything written to it. */+export function webCollector(): { stream: WritableStream<Uint8Array>; toBuffer(): Buffer } {+ const chunks: Buffer[] = [];++ return {+ stream: new WritableStream<Uint8Array>({+ write(chunk) {+ chunks.push(Buffer.from(chunk));+ }+ }),+ toBuffer: () => Buffer.concat(chunks)+ };+}+/** Returns a copy with one byte flipped, for tamper tests. */export function flipByte(data: Buffer, offset: number): Buffer {const copy = Buffer.from(data);@@ -116,6 +177,14 @@ export function failureOf(return reasonOf(readFromBuffer(container, options));}+/** As {@link failureOf}, through the web entry point. */+export function failureOfWeb(+ container: Buffer,+ options: ReadBackupContainerOptions = {}+): Promise<string> {+ return reasonOf(readFromBufferWeb(container, options));+}+/** Runs `read` and returns the `reason` of the BackupContainerError it throws. */export async function reasonOf(operation: Promise<unknown>): Promise<string> {try {@@ -126,3 +195,12 @@ export async function reasonOf(operation: Promise<unknown>): Promise<string> {return "did not throw";}++function chunksOf(data: Buffer, chunkSize: number): Buffer[] {+ const chunks: Buffer[] = [];+ for (let offset = 0; offset < data.length; offset += chunkSize) {+ chunks.push(data.subarray(offset, offset + chunkSize));+ }++ return chunks.length > 0 ? chunks : [ Buffer.alloc(0) ];+}diff --git a/packages/trilium-backup-container/src/web-streams.ts b/packages/trilium-backup-container/src/web-streams.tsnew file mode 100644index 0000000000..aea0ce1323--- /dev/null+++ b/packages/trilium-backup-container/src/web-streams.ts@@ -0,0 +1,106 @@+import { webBackend } from "./backend-web.js";+import type { ByteSink, ByteSource } from "./backend.js";+import {+ readContainer,+ type ReadBackupContainerOptions,+ type ReadBackupContainerResult+} from "./read.js";+import {+ type WriteBackupContainerOptions,+ type WriteBackupContainerResult,+ writeContainer+} from "./write.js";++/**+ * Unwraps a container back into a database. The web entry point: takes Web Streams and runs on+ * WebCrypto, the platform's gzip codec and `@noble/hashes`. See {@link readContainer} for the+ * semantics.+ *+ * @param input the container bytes.+ * @param output the destination for the database, which is closed by this call on success and+ * aborted with the failure otherwise.+ */+export async function readBackupContainer(+ input: ReadableStream<Uint8Array>,+ output: WritableStream<Uint8Array>,+ options: ReadBackupContainerOptions = {}+): Promise<ReadBackupContainerResult> {+ const writer = output.getWriter();+ try {+ return await readContainer(streamSource(input), sinkFor(writer), webBackend, options);+ } catch (error) {+ await abortQuietly(writer, error);+ throw error;+ }+}++/**+ * Wraps a database into a container. The web entry point: takes Web Streams and runs on+ * WebCrypto, the platform's gzip codec and `@noble/hashes`. See {@link writeContainer} for the+ * semantics.+ *+ * @param input the database bytes.+ * @param output the destination, which is closed by this call on success and aborted with the+ * failure otherwise.+ */+export async function writeBackupContainer(+ input: ReadableStream<Uint8Array>,+ output: WritableStream<Uint8Array>,+ options: WriteBackupContainerOptions+): Promise<WriteBackupContainerResult> {+ const writer = output.getWriter();+ try {+ return await writeContainer(streamSource(input), sinkFor(writer), webBackend, options);+ } catch (error) {+ await abortQuietly(writer, error);+ throw error;+ }+}++/**+ * Iterates a readable stream by hand rather than through its own async iterator, which some+ * engines still lack. Cancels what is left of the stream however the iteration ends, so an+ * abandoned read does not leave the input locked and half-consumed.+ */+async function* streamSource(input: ReadableStream<Uint8Array>): ByteSource {+ const reader = input.getReader();+ try {+ for (;;) {+ const result = await reader.read();+ if (result.done) {+ return;+ }+ yield result.value;+ }+ } finally {+ try {+ await reader.cancel();+ } catch {+ // An already-errored input refuses the cancel; its error has been dealt with.+ }+ }+}++/** Hands the failure to the destination; a destination that already failed keeps its own error. */+async function abortQuietly(+ writer: WritableStreamDefaultWriter<Uint8Array>,+ error: unknown+): Promise<void> {+ try {+ await writer.abort(error);+ } catch {+ // The destination failed first, which is what is being reported upstream anyway.+ }+}++/** A {@link ByteSink} over a writable stream's writer, honouring its backpressure. */+function sinkFor(writer: WritableStreamDefaultWriter<Uint8Array>): ByteSink {+ return {+ write(chunk) {+ return writer.write(chunk);+ },+ end() {+ return writer.close();+ }+ };+}diff --git a/packages/trilium-backup-container/src/web.ts b/packages/trilium-backup-container/src/web.tsnew file mode 100644index 0000000000..aa6117a444--- /dev/null+++ b/packages/trilium-backup-container/src/web.ts@@ -0,0 +1,56 @@+/**+ * Reader and writer for the Trilium backup container: one SQLite database wrapped with+ * optional gzip compression and optional AES-256-GCM encryption.+ *+ * This is the browser entry point, `@triliumnext/backup-container/web`: the same operations as+ * the Node entry point, taking Web Streams instead of Node streams. AES-256-GCM and randomness+ * come from WebCrypto, gzip from the platform's `CompressionStream`, and scrypt and incremental+ * SHA-256, which WebCrypto does not offer, from `@noble/hashes`. The format layer and every check+ * are shared with the Node entry point, so a container written by either is read by both.+ *+ * WebCrypto's `subtle` interface only exists in secure contexts (HTTPS, localhost, workers of+ * either), so encrypted containers cannot be handled on a page served over plain HTTP.+ *+ * @example Unwrapping a picked file into an OPFS destination+ * ```ts+ * const handle = await directory.getFileHandle("document.db", { create: true });+ * const info = await readBackupContainer(file.stream(), await handle.createWritable(), {+ * passphrase,+ * onProgress: (progress) => report(Math.round(progress * 100))+ * });+ * ```+ *+ * @module+ */++export {+ BackupContainerError,+ type BackupContainerErrorReason,+ isBackupContainerError+} from "./errors.js";+export {+ FIXED_HEADER_BYTES,+ FORMAT_VERSION,+ FRAME_SIZE,+ SCRYPT_BOUNDS,+ SCRYPT_DEFAULTS,+ type ScryptParams+} from "./format.js";+export {+ DEFAULT_PROGRESS_INTERVAL_MS,+ type ProgressCallback,+ type ProgressOptions+} from "./progress.js";+export {+ type BackupContainerInfo,+ DEFAULT_MAX_OUTPUT_BYTES,+ peekBackupContainer,+ type ReadBackupContainerOptions,+ type ReadBackupContainerResult+} 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 df4ba7e24b..c6d46acbfd 100644--- a/packages/trilium-backup-container/src/write.ts+++ b/packages/trilium-backup-container/src/write.ts@@ -1,9 +1,10 @@-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 {+ type ByteSink,+ type ByteSource,+ type ContainerBackend,+ deriveContainerKey+} from "./backend.js";+import { concatBytes, writeU32LE } from "./bytes.js";import { BackupContainerError } from "./errors.js";import {authenticatedHeaderEnd,@@ -13,20 +14,24 @@ import {digestOffset,encodeHeader,FORMAT_VERSION,+ FRAME_FINAL_FLAG,+ FRAME_SIZE,+ GZIP_OS_UNKNOWN,headerLengthFor,KDF_SCRYPT,+ MAX_FRAME_COUNTER,NONCE_PREFIX_BYTES,+ nonceFor,SALT_BYTES,type ScryptParams,SCRYPT_DEFAULTS,TAG_BYTES,- validateScryptParams+ validateScryptParams,+ VERIFIER_COUNTER} from "./format.js";-import { createProgressReporter, type ProgressOptions } from "./progress.js";-import { DigestTap, FrameEncryptor, GzipHeaderNormaliser, ProgressTap } from "./streams.js";+import { createProgressReporter, type ProgressOptions, type ProgressReporter } from "./progress.js";-/** The stream shapes `pipeline` accepts, so a built array needs no cast at the call. */-type PipelineStage = NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream;+const EMPTY = new Uint8Array(0);/*** Writes `data` at an absolute offset in the destination that is already being streamed to.@@ -34,7 +39,7 @@ type PipelineStage = NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.Read* 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 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. */@@ -52,7 +57,10 @@ export interface WriteBackupContainerOptions extends ProgressOptions {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. */+ /**+ * gzip compression level. 6 is the speed to ratio sweet spot. Only honoured where the+ * platform's compressor takes a level, which the browser's does not.+ */compressionLevel?: number;}@@ -61,26 +69,29 @@ export interface WriteBackupContainerResult {compressed: boolean;encrypted: boolean;/** SHA-256 of the payload as stored, i.e. what was patched into the header. */- digest: Buffer;+ digest: Uint8Array;/** Payload bytes written, excluding the header. */payloadBytes: number;}/**- * Wraps a database into a container.+ * 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.** @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.* @returns what was written, see {@link WriteBackupContainerResult}.* @throws BackupContainerError with `reason` set, see {@link BackupContainerErrorReason}.*/-export async function writeBackupContainer(- input: Readable,- output: Writable,+export async function writeContainer(+ input: ByteSource,+ output: ByteSink,+ backend: ContainerBackend,options: WriteBackupContainerOptions): Promise<WriteBackupContainerResult> {if (typeof options.patchHeader !== "function") {@@ -111,10 +122,10 @@ export async function writeBackupContainer(plaintextSize,headerLength: headerLengthFor(encrypted),encryption: null,- digest: Buffer.alloc(DIGEST_BYTES)+ digest: new Uint8Array(DIGEST_BYTES)};- let key: Buffer | null = null;+ let key: unknown = null;if (options.passphrase !== undefined) {const params = options.scrypt ?? SCRYPT_DEFAULTS;validateScryptParams(params, options.maxKdfMemoryBytes ?? DEFAULT_MAX_KDF_MEMORY_BYTES);@@ -122,49 +133,53 @@ export async function writeBackupContainer(header.encryption = {kdfId: KDF_SCRYPT,...params,- salt: randomBytes(SALT_BYTES),- noncePrefix: randomBytes(NONCE_PREFIX_BYTES),- verifierTag: Buffer.alloc(TAG_BYTES)+ salt: backend.randomBytes(SALT_BYTES),+ noncePrefix: backend.randomBytes(NONCE_PREFIX_BYTES),+ verifierTag: new Uint8Array(TAG_BYTES)};- key = await deriveKey(options.passphrase, header.encryption.salt, params);+ key = await deriveContainerKey(backend, 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)+ if (header.encryption && key !== null) {+ const verifier = await backend.gcmSeal(+ key,+ nonceFor(header.encryption.noncePrefix, VERIFIER_COUNTER),+ aad,+ EMPTY);+ headerBytes.set(verifier.tag, authenticatedHeaderEnd(header.headerLength));}- await writeChunk(output, headerBytes);+ await output.write(headerBytes);// input -> gzip -> frames -> digest -> output, with the stages the flags call for.- const digestTap = new DigestTap();- // Typed as the streams `pipeline` accepts, so the built array needs no cast at the call.- const stages: PipelineStage[] = [ input ];+ let payload = input;if (progress) {- stages.push(new ProgressTap(progress));+ payload = tapProgress(payload, progress);}if (compressed) {- stages.push(- createGzip({ level: options.compressionLevel ?? 6 }),- new GzipHeaderNormaliser()- );+ payload = normaliseGzipHeader(backend.gzip(payload, options.compressionLevel ?? 6));}- if (header.encryption && key) {- stages.push(new FrameEncryptor(key, header.encryption.noncePrefix, aad));+ if (header.encryption && key !== null) {+ payload = encryptFrames(backend, key, header.encryption.noncePrefix, aad, payload);}- stages.push(digestTap, output);- await pipeline(stages);+ const hash = backend.createSha256();+ let payloadBytes = 0;+ for await (const chunk of payload) {+ hash.update(chunk);+ payloadBytes += chunk.length;+ await output.write(chunk);+ }+ await output.end();- const digest = digestTap.digest();+ const digest = hash.digest();await options.patchHeader(digestOffset(header.headerLength), digest);- // After the patch rather than after the pipeline: the container is not written until the digest+ // After the patch rather than after the payload: the container is not written until the digest// is in its header.progress?.complete();@@ -173,12 +188,114 @@ export async function writeBackupContainer(compressed,encrypted,digest,- payloadBytes: digestTap.bytesHashed+ payloadBytes};}-function writeChunk(stream: Writable, chunk: Buffer): Promise<void> {- return new Promise((resolve, reject) => {- stream.write(chunk, (error) => (error ? reject(error) : resolve()));- });+/**+ * Passes bytes through untouched while reporting how many of them have gone past.+ *+ * Sits at the head of the pipeline, where the bytes are still the ones the recorded plaintext+ * size counted: further down they are compressed, encrypted, or both, and a fraction of those is+ * a fraction of a total nobody knows in advance.+ */+async function* tapProgress(source: ByteSource, progress: ProgressReporter): ByteSource {+ let bytes = 0;+ for await (const chunk of source) {+ bytes += chunk.length;+ progress.at(bytes);+ yield chunk;+ }+}++/**+ * Forces the gzip MTIME field to zero and the OS byte to "unknown".+ *+ * Node's compressor already emits MTIME 0 and no FNAME or FEXTRA, but its OS byte follows the+ * build platform (3 on Unix, 10 on Windows), and the browser's compressor makes no promises about+ * either field. Both are informational and outside gzip's CRC, so rewriting them is safe, and+ * doing it here keeps every backend's output canonical: no timestamp and no platform hint.+ */+export async function* normaliseGzipHeader(source: ByteSource): ByteSource {+ let seen = 0;+ for await (let chunk of source) {+ if (seen < 10) {+ // Copy first: the buffer belongs to the compressor.+ chunk = chunk.slice();+ for (let index = 0; index < chunk.length; index++) {+ const offset = seen + index;+ if (offset >= 4 && offset < 8) {+ chunk[index] = 0; // MTIME+ } else if (offset === 9) {+ chunk[index] = GZIP_OS_UNKNOWN; // OS+ }+ }+ }+ seen += chunk.length;+ yield chunk;+ }+}++/**+ * Splits the payload into authenticated frames.+ *+ * Full frames are emitted as soon as they fill and the end of the source 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.+ *+ * @param maxCounter highest counter a frame may use. Lowered only by tests, which cannot write+ * 4 PiB.+ */+export async function* encryptFrames(+ backend: ContainerBackend,+ key: unknown,+ noncePrefix: Uint8Array,+ aad: Uint8Array,+ source: ByteSource,+ maxCounter: number = MAX_FRAME_COUNTER+): ByteSource {+ const frame = new Uint8Array(FRAME_SIZE);+ let filled = 0;+ let counter = 0;++ const seal = async (final: boolean): Promise<Uint8Array> => {+ if (counter > maxCounter) {+ throw new BackupContainerError(+ "payload-too-large",+ `Payload needs more than ${maxCounter + 1} frames.`+ );+ }++ const lengthField = new Uint8Array(4);+ writeU32LE(lengthField, 0, final ? (filled | FRAME_FINAL_FLAG) >>> 0 : filled);++ const { ciphertext, tag } = await backend.gcmSeal(+ key,+ nonceFor(noncePrefix, counter),+ concatBytes(aad, lengthField),+ frame.subarray(0, filled)+ );++ counter++;+ filled = 0;++ return concatBytes(lengthField, ciphertext, tag);+ };++ for await (const chunk of source) {+ let offset = 0;+ while (offset < chunk.length) {+ const take = Math.min(FRAME_SIZE - filled, chunk.length - offset);+ frame.set(chunk.subarray(offset, offset + take), filled);+ filled += take;+ offset += take;++ if (filled === FRAME_SIZE) {+ yield await seal(false);+ }+ }+ }++ yield await seal(true);}diff --git a/packages/trilium-backup-container/vite.config.ts b/packages/trilium-backup-container/vite.config.tsindex 0c8ddf0a69..183c74e6f0 100644--- a/packages/trilium-backup-container/vite.config.ts+++ b/packages/trilium-backup-container/vite.config.ts@@ -25,7 +25,13 @@ export default defineConfig(() => ({reportsDirectory: "./test-output/vitest/coverage",provider: "v8" as const,include: [ "src/**/*.ts" ],- exclude: [ "**/*.spec.ts", "**/*.d.ts", "src/index.ts", "src/test-helpers.ts" ],+ exclude: [+ "**/*.spec.ts",+ "**/*.d.ts",+ "src/index.ts",+ "src/web.ts",+ "src/test-helpers.ts"+ ],reporter: [ "text", [ "lcov", { projectRoot: resolve(__dirname, "../..") } ] ]}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0b18881aba..b42aa1b34e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1367,7 +1367,11 @@ 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-backup-container:+ dependencies:+ '@noble/hashes':+ specifier: ^2.2.0+ version: 2.2.0packages/trilium-core:dependencies: