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
core/backup import: rewrite the DB validation to support standalone mode
Adorian Doranfb10ecc433ca
diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsindex 534f03a913..b4a4bdbfd3 100644--- a/apps/server/src/services/database_restore.ts+++ b/apps/server/src/services/database_restore.ts@@ -8,6 +8,7 @@ import {} from "@triliumnext/backup-container";import {cls,+ type DatabaseRejection,events as eventService,getLog,getSql,@@ -19,7 +20,7 @@ import path from "path";import config from "./config.js";import dataDir from "./data_dir.js";-import { type DatabaseRejection, validateDatabaseFile } from "./database_validation.js";+import { validateDatabaseFile } from "./database_validation.js";/*** Puts a backup in place of this instance's database.diff --git a/apps/server/src/services/database_validation.spec.ts b/apps/server/src/services/database_validation.spec.tsindex 96e33fc619..80710e678d 100644--- a/apps/server/src/services/database_validation.spec.ts+++ b/apps/server/src/services/database_validation.spec.ts@@ -1,11 +1,17 @@-import { app_info as appInfo } from "@triliumnext/core";+import { app_info as appInfo, OLDEST_SUPPORTED_DB_VERSION } from "@triliumnext/core";import Database from "better-sqlite3";import fs from "fs";import os from "os";import path from "path";import { afterAll, describe, expect, it } from "vitest";-import { OLDEST_SUPPORTED_DB_VERSION, validateDatabaseFile } from "./database_validation.js";+import { validateDatabaseFile } from "./database_validation.js";++/*+ * What the checks decide is covered against a stand-in candidate in core, where it belongs and where+ * no file is needed. These cover the opening: that a real database on disk answers those checks+ * correctly through this platform's driver, and that files which are not one are turned away.+ */const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-db-validation-spec-"));let counter = 0;@@ -48,8 +54,8 @@ function fileWith(content: Buffer | string) {const CURRENT = { initialized: "true", dbVersion: String(appInfo.dbVersion) };-describe("validating a database file", () => {- it("accepts a database from this version, and one that only needs migrating", () => {+describe("opening a candidate database on this platform", () => {+ it("reads a real database's integrity, tables and options, and accepts it", () => {expect(validateDatabaseFile(triliumDatabase(CURRENT))).toEqual({valid: true, dbVersion: appInfo.dbVersion, needsMigration: false});@@ -60,6 +66,16 @@ describe("validating a database file", () => {});});+ it("carries a rejection back from the checks, with the driver's own answers behind it", () => {+ const notOurs = databaseWith((db) => db.exec("CREATE TABLE recipes (name TEXT)"));++ expect(validateDatabaseFile(notOurs)).toMatchObject({+ valid: false,+ rejection: "not-a-trilium-database",+ message: expect.stringContaining("options, notes, branches, blobs")+ });+ });+it("refuses a file that is not a SQLite database, whatever it is called", () => {expect(validateDatabaseFile(fileWith("this is a text file, not a database"))).toMatchObject({valid: false, rejection: "not-a-database"@@ -71,45 +87,6 @@ describe("validating a database file", () => {});});- it("refuses a SQLite database that is not one of ours, naming what is missing", () => {- const empty = databaseWith((db) => db.exec("CREATE TABLE recipes (name TEXT)"));- expect(validateDatabaseFile(empty)).toMatchObject({- valid: false, rejection: "not-a-trilium-database", message: expect.stringContaining("options, notes, branches, blobs")- });-- const partial = triliumDatabase(CURRENT, [ "options", "notes" ]);- expect(validateDatabaseFile(partial)).toMatchObject({- valid: false, rejection: "not-a-trilium-database", message: expect.stringContaining("branches, blobs")- });- });-- it("refuses a database left behind by a setup that never finished", () => {- const unfinished = triliumDatabase({ dbVersion: String(appInfo.dbVersion) });-- expect(validateDatabaseFile(unfinished)).toMatchObject({- valid: false, rejection: "database-not-initialized"- });- });-- it("refuses a database from a version this one cannot migrate, in either direction", () => {- const tooOld = triliumDatabase({ initialized: "true", dbVersion: String(OLDEST_SUPPORTED_DB_VERSION - 1) });- expect(validateDatabaseFile(tooOld)).toMatchObject({ valid: false, rejection: "database-too-old" });-- const tooNew = triliumDatabase({ initialized: "true", dbVersion: String(appInfo.dbVersion + 1) });- expect(validateDatabaseFile(tooNew)).toMatchObject({- valid: false, rejection: "database-too-new", message: expect.stringContaining(String(appInfo.dbVersion))- });- });-- it("refuses a database that does not say which version it is from", () => {- expect(validateDatabaseFile(triliumDatabase({ initialized: "true" }))).toMatchObject({- valid: false, rejection: "not-a-trilium-database"- });- expect(validateDatabaseFile(triliumDatabase({ initialized: "true", dbVersion: "recent" }))).toMatchObject({- valid: false, rejection: "not-a-trilium-database"- });- });-it("refuses a database whose pages have been damaged", () => {const filePath = databaseWith((db) => {db.exec("CREATE TABLE notes (noteId TEXT, title TEXT)");diff --git a/apps/server/src/services/database_validation.ts b/apps/server/src/services/database_validation.tsindex 21dce03ef7..4b8179747f 100644--- a/apps/server/src/services/database_validation.ts+++ b/apps/server/src/services/database_validation.ts@@ -1,60 +1,31 @@-import { app_info as appInfo } from "@triliumnext/core";+import {+ type CandidateDatabase,+ type DatabaseValidation,+ looksLikeSqlite,+ validateDatabase+} from "@triliumnext/core";import Database from "better-sqlite3";import fs from "fs";/**- * Decides whether a file is a Trilium database this version can open, before anything is done that- * depends on the answer.+ * Opens a candidate database on this platform and puts it through the shared checks.*- * A restore replaces the document the whole application is about, and the file it replaces it with- * arrived from outside: an upload, a directory listing, a file the user picked. "It has a .db- * extension" says nothing, and finding out later is not an option, because the code that would find- * out is the migration, and a migration that cannot proceed calls `crash()` — which on the server is- * `process.exit(1)`. By then the original database has already been moved aside.- *- * So every reason the database could turn out to be unusable is checked here, on a copy nothing is- * attached to yet, and turned into an answer the user can act on.+ * Only the opening is here. What makes a database ours is decided in core, so that a platform which+ * keeps its databases somewhere other than a filesystem answers the same questions the same way.** @module*/-/** The oldest database the migrations can still take, from `migration.migrate`. */-export const OLDEST_SUPPORTED_DB_VERSION = 214;--const REQUIRED_TABLES = [ "options", "notes", "branches", "blobs" ];-const SQLITE_MAGIC = Buffer.from("SQLite format 3\0", "latin1");--export type DatabaseRejection =- /** Not a SQLite database at all. */- | "not-a-database"- /** SQLite, but corrupt. */- | "damaged-database"- /** A SQLite database, but not one of ours. */- | "not-a-trilium-database"- /** Ours, but from a setup that never finished, so there is nothing to restore. */- | "database-not-initialized"- /** From a version so old the migrations no longer reach back to it. */- | "database-too-old"- /** From a newer version, which this one cannot read. */- | "database-too-new";--export type DatabaseValidation =- | { valid: true; dbVersion: number; needsMigration: boolean }- | { valid: false; rejection: DatabaseRejection; message: string };-/*** Reads `filePath` and reports whether it can become this instance's database.** The file is opened read-only through its own connection, so nothing here touches the database the- * application is currently attached to.- *- * `PRAGMA quick_check` reads the whole file, which for a large database is not instant. It is worth- * it: a restore that succeeds and leaves the user with a corrupt document is worse than one that- * takes another minute to say no.+ * application is currently attached to, and pages are read as they are needed rather than the whole+ * file at once.*/export function validateDatabaseFile(filePath: string): DatabaseValidation {if (!hasSqliteHeader(filePath)) {- return reject("not-a-database", "The file is not a SQLite database.");+ return { valid: false, rejection: "not-a-database", message: "The file is not a SQLite database." };}let db: Database.Database;@@ -65,61 +36,35 @@ export function validateDatabaseFile(filePath: string): DatabaseValidation {nativeBinding: process.env.BETTERSQLITE3_NATIVE_PATH || undefined});} catch (e) {- return reject("not-a-database", `The database could not be opened: ${messageOf(e)}`);+ return {+ valid: false,+ rejection: "not-a-database",+ message: `The database could not be opened: ${messageOf(e)}`+ };}try {- return inspect(db);+ return validateDatabase(candidateOf(db));} catch (e) {- return reject("damaged-database", `The database could not be read: ${messageOf(e)}`);+ // What a database too damaged to query throws is this driver's business, not the checks'.+ return {+ valid: false,+ rejection: "damaged-database",+ message: `The database could not be read: ${messageOf(e)}`+ };} finally {db.close();}}-function inspect(db: Database.Database): DatabaseValidation {- const integrity = db.pragma("quick_check", { simple: true });- if (integrity !== "ok") {- return reject("damaged-database", `The database failed its integrity check: ${integrity}`);- }-- const tables = new Set(- db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").pluck().all() as string[]- );- const missing = REQUIRED_TABLES.filter((table) => !tables.has(table));- if (missing.length > 0) {- return reject(- "not-a-trilium-database",- `The database is missing the ${missing.join(", ")} table${missing.length > 1 ? "s" : ""}.`- );- }-- const readOption = db.prepare("SELECT value FROM options WHERE name = ?").pluck();- if (readOption.get("initialized") !== "true") {- return reject(- "database-not-initialized",- "The database is from a setup that never finished, so it holds nothing to restore."- );- }-- const dbVersion = Number(readOption.get("dbVersion"));- if (!Number.isInteger(dbVersion)) {- return reject("not-a-trilium-database", "The database does not state which version it is from.");- }- if (dbVersion < OLDEST_SUPPORTED_DB_VERSION) {- return reject(- "database-too-old",- `The database is version ${dbVersion}; the oldest that can still be migrated is ${OLDEST_SUPPORTED_DB_VERSION}.`- );- }- if (dbVersion > appInfo.dbVersion) {- return reject(- "database-too-new",- `The database is version ${dbVersion}, which is newer than this application's ${appInfo.dbVersion}.`- );- }-- return { valid: true, dbVersion, needsMigration: dbVersion < appInfo.dbVersion };+/** The three questions the checks ask, answered by a better-sqlite3 connection. */+function candidateOf(db: Database.Database): CandidateDatabase {+ return {+ integrityCheck: () => String(db.pragma("quick_check", { simple: true })),+ tableNames: () => db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").pluck().all() as string[],+ option: (name: string) =>+ db.prepare("SELECT value FROM options WHERE name = ?").pluck().get(name) as string | undefined+ };}/**@@ -127,14 +72,14 @@ function inspect(db: Database.Database): DatabaseValidation {* user an error about a malformed database when what they picked was a photograph.*/function hasSqliteHeader(filePath: string): boolean {- const head = Buffer.alloc(SQLITE_MAGIC.length);+ const head = Buffer.alloc(16);let descriptor: number | undefined;try {descriptor = fs.openSync(filePath, "r");const read = fs.readSync(descriptor, head, 0, head.length, 0);- return read === head.length && head.equals(SQLITE_MAGIC);+ return looksLikeSqlite(head.subarray(0, read));} catch {return false;} finally {@@ -144,10 +89,6 @@ function hasSqliteHeader(filePath: string): boolean {}}-function reject(rejection: DatabaseRejection, message: string): DatabaseValidation {- return { valid: false, rejection, message };-}-function messageOf(e: unknown): string {return e instanceof Error ? e.message : String(e);}diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex b860ffac0d..6ffa5682fb 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -23,6 +23,14 @@ export type * from "./services/sql/types";export * from "./services/sql/index";export { default as sql_init } from "./services/sql_init";export { getRunningSetupOperation, holdSetup, withSetupLock } from "./services/setup_lock";+export {+ type CandidateDatabase,+ type DatabaseRejection,+ type DatabaseValidation,+ looksLikeSqlite,+ OLDEST_SUPPORTED_DB_VERSION,+ validateDatabase+} from "./services/database_validation";export * as protected_session from "./services/protected_session";export { default as data_encryption } from "./services/encryption/data_encryption";export { default as scrypt } from "./services/encryption/scrypt";diff --git a/packages/trilium-core/src/services/database_validation.spec.ts b/packages/trilium-core/src/services/database_validation.spec.tsnew file mode 100644index 0000000000..c084e8dd44--- /dev/null+++ b/packages/trilium-core/src/services/database_validation.spec.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from "vitest";++import appInfo from "./app_info.js";+import {+ type CandidateDatabase,+ looksLikeSqlite,+ OLDEST_SUPPORTED_DB_VERSION,+ validateDatabase+} from "./database_validation.js";++const TRILIUM_TABLES = [ "options", "notes", "branches", "blobs" ];++/** A candidate that answers whatever the test says it does, without a database engine involved. */+function candidate(answers: {+ integrity?: string;+ tables?: string[];+ options?: Record<string, string>;+} = {}): CandidateDatabase {+ const options = answers.options ?? { initialized: "true", dbVersion: String(appInfo.dbVersion) };++ return {+ integrityCheck: () => answers.integrity ?? "ok",+ tableNames: () => answers.tables ?? TRILIUM_TABLES,+ option: (name) => options[name]+ };+}++function bytesOf(text: string): Uint8Array {+ return Uint8Array.from(text, (character) => character.charCodeAt(0));+}++describe("recognising a SQLite database by its first bytes", () => {+ it("accepts the header every SQLite database begins with", () => {+ expect(looksLikeSqlite(bytesOf("SQLite format 3\0"))).toBe(true);+ // Whatever follows it is the database's business, not this check's.+ expect(looksLikeSqlite(bytesOf("SQLite format 3\0and then some"))).toBe(true);+ });++ it("refuses anything else, including too little to tell", () => {+ expect(looksLikeSqlite(bytesOf("this is a text file"))).toBe(false);+ expect(looksLikeSqlite(bytesOf("SQLite"))).toBe(false);+ expect(looksLikeSqlite(new Uint8Array())).toBe(false);+ // Right length, one byte wrong.+ expect(looksLikeSqlite(bytesOf("SQLite format 4\0"))).toBe(false);+ });+});++describe("validating a candidate database", () => {+ it("accepts one from this version, and one that only needs migrating", () => {+ expect(validateDatabase(candidate())).toEqual({+ valid: true, dbVersion: appInfo.dbVersion, needsMigration: false+ });++ const older = candidate({+ options: { initialized: "true", dbVersion: String(OLDEST_SUPPORTED_DB_VERSION) }+ });+ expect(validateDatabase(older)).toEqual({+ valid: true, dbVersion: OLDEST_SUPPORTED_DB_VERSION, needsMigration: true+ });+ });++ it("refuses one that does not pass its own integrity check", () => {+ expect(validateDatabase(candidate({ integrity: "row 3 missing from index sqlite_autoindex_notes_1" })))+ .toMatchObject({ valid: false, rejection: "damaged-database" });+ });++ it("refuses a database that is not one of ours, naming what is missing", () => {+ expect(validateDatabase(candidate({ tables: [ "recipes" ] }))).toMatchObject({+ valid: false,+ rejection: "not-a-trilium-database",+ message: expect.stringContaining("options, notes, branches, blobs")+ });++ expect(validateDatabase(candidate({ tables: [ "options", "notes" ] }))).toMatchObject({+ valid: false, rejection: "not-a-trilium-database", message: expect.stringContaining("branches, blobs")+ });+ });++ it("refuses one left behind by a setup that never finished", () => {+ const unfinished = candidate({ options: { dbVersion: String(appInfo.dbVersion) } });++ expect(validateDatabase(unfinished)).toMatchObject({+ valid: false, rejection: "database-not-initialized"+ });+ });++ it("refuses one from a version this cannot migrate, in either direction", () => {+ const tooOld = candidate({+ options: { initialized: "true", dbVersion: String(OLDEST_SUPPORTED_DB_VERSION - 1) }+ });+ expect(validateDatabase(tooOld)).toMatchObject({ valid: false, rejection: "database-too-old" });++ const tooNew = candidate({+ options: { initialized: "true", dbVersion: String(appInfo.dbVersion + 1) }+ });+ expect(validateDatabase(tooNew)).toMatchObject({+ valid: false, rejection: "database-too-new", message: expect.stringContaining(String(appInfo.dbVersion))+ });+ });++ it("refuses one that does not say which version it is from", () => {+ expect(validateDatabase(candidate({ options: { initialized: "true" } }))).toMatchObject({+ valid: false, rejection: "not-a-trilium-database"+ });++ expect(validateDatabase(candidate({ options: { initialized: "true", dbVersion: "recent" } })))+ .toMatchObject({ valid: false, rejection: "not-a-trilium-database" });+ });++ it("asks the cheapest questions first, so a damaged database is not read for its options", () => {+ const asked: string[] = [];+ const damaged: CandidateDatabase = {+ integrityCheck: () => { asked.push("integrity"); return "malformed database schema"; },+ tableNames: () => { asked.push("tables"); return TRILIUM_TABLES; },+ option: (name) => { asked.push(`option:${name}`); return undefined; }+ };++ expect(validateDatabase(damaged)).toMatchObject({ rejection: "damaged-database" });+ expect(asked).toEqual([ "integrity" ]);+ });+});diff --git a/packages/trilium-core/src/services/database_validation.ts b/packages/trilium-core/src/services/database_validation.tsnew file mode 100644index 0000000000..c672f91acf--- /dev/null+++ b/packages/trilium-core/src/services/database_validation.ts@@ -0,0 +1,136 @@+import appInfo from "./app_info.js";++/**+ * Decides whether a database can become this instance's, before anything depends on the answer.+ *+ * A restore replaces the document the whole application is about, and the file it replaces it with+ * arrived from outside: an upload, a directory listing, a file the user picked. "It has a .db+ * extension" says nothing, and finding out later is not an option, because the code that would find+ * out is the migration, and a migration that cannot proceed calls `crash()`.+ *+ * The checks live here, apart from the opening: what makes a database ours is the same everywhere,+ * while opening one is not. A platform supplies a {@link CandidateDatabase}, which is the whole of+ * what these checks need and is deliberately small enough that any driver can offer it — a second+ * connection on the server, an entry read out of the browser's own storage, page by page in both+ * cases rather than in memory.+ *+ * @module+ */++/** The oldest database the migrations still reach back to; below this one, there is no upgrade path. */+export const OLDEST_SUPPORTED_DB_VERSION = 214;++/** What every SQLite database begins with, in the encoding the bytes are read as. */+const SQLITE_MAGIC = "SQLite format 3\0";++const REQUIRED_TABLES = [ "options", "notes", "branches", "blobs" ];++export type DatabaseRejection =+ /** Not a SQLite database at all. */+ | "not-a-database"+ /** SQLite, but corrupt. */+ | "damaged-database"+ /** A SQLite database, but not one of ours. */+ | "not-a-trilium-database"+ /** Ours, but from a setup that never finished, so there is nothing to restore. */+ | "database-not-initialized"+ /** From a version so old the migrations no longer reach back to it. */+ | "database-too-old"+ /** From a newer version, which this one cannot read. */+ | "database-too-new";++export type DatabaseValidation =+ | { valid: true; dbVersion: number; needsMigration: boolean }+ | { valid: false; rejection: DatabaseRejection; message: string };++/**+ * A candidate database, open and readable, reduced to the three questions validation asks of it.+ *+ * Each is a plain read: nothing here writes, and nothing needs the whole database at once.+ */+export interface CandidateDatabase {+ /** What `PRAGMA quick_check` answers, which is `"ok"` and nothing else when all is well. */+ integrityCheck(): string;+ /** The names of the tables it has. */+ tableNames(): string[];+ /** A value from the `options` table, or `undefined` where there is no such row. */+ option(name: string): string | undefined;+}++/**+ * Reports whether `head` starts the way a SQLite database does.+ *+ * Sixteen bytes, asked before a database engine is involved at all, so that a photograph gets an+ * answer about what it is rather than one about a malformed database.+ *+ * @param head the first bytes of the file; anything shorter than the magic is not one.+ */+export function looksLikeSqlite(head: Uint8Array): boolean {+ if (head.length < SQLITE_MAGIC.length) {+ return false;+ }++ for (let i = 0; i < SQLITE_MAGIC.length; i++) {+ if (head[i] !== SQLITE_MAGIC.charCodeAt(i)) {+ return false;+ }+ }++ return true;+}++/**+ * Puts an open candidate through every check, in the order that answers most cheaply first.+ *+ * `PRAGMA quick_check` reads the whole database, which for a large one is not instant. It is worth+ * it: a restore that succeeds and leaves the user with a corrupt document is worse than one that+ * takes another minute to say no.+ *+ * @throws whatever the driver throws on a database too damaged to query; the caller knows its own+ * driver's failures and turns them into {@link DatabaseRejection}.+ */+export function validateDatabase(db: CandidateDatabase): DatabaseValidation {+ const integrity = db.integrityCheck();+ if (integrity !== "ok") {+ return reject("damaged-database", `The database failed its integrity check: ${integrity}`);+ }++ const tables = new Set(db.tableNames());+ const missing = REQUIRED_TABLES.filter((table) => !tables.has(table));+ if (missing.length > 0) {+ return reject(+ "not-a-trilium-database",+ `The database is missing the ${missing.join(", ")} table${missing.length > 1 ? "s" : ""}.`+ );+ }++ if (db.option("initialized") !== "true") {+ return reject(+ "database-not-initialized",+ "The database is from a setup that never finished, so it holds nothing to restore."+ );+ }++ const dbVersion = Number(db.option("dbVersion"));+ if (!Number.isInteger(dbVersion)) {+ return reject("not-a-trilium-database", "The database does not state which version it is from.");+ }+ if (dbVersion < OLDEST_SUPPORTED_DB_VERSION) {+ return reject(+ "database-too-old",+ `The database is version ${dbVersion}; the oldest that can still be migrated is ${OLDEST_SUPPORTED_DB_VERSION}.`+ );+ }+ if (dbVersion > appInfo.dbVersion) {+ return reject(+ "database-too-new",+ `The database is version ${dbVersion}, which is newer than this application's ${appInfo.dbVersion}.`+ );+ }++ return { valid: true, dbVersion, needsMigration: dbVersion < appInfo.dbVersion };+}++function reject(rejection: DatabaseRejection, message: string): DatabaseValidation {+ return { valid: false, rejection, message };+}diff --git a/packages/trilium-core/src/services/migration.ts b/packages/trilium-core/src/services/migration.tsindex 1731786a08..271410f615 100644--- a/packages/trilium-core/src/services/migration.ts+++ b/packages/trilium-core/src/services/migration.ts@@ -1,4 +1,5 @@import { getBackup } from "./backup.js";+import { OLDEST_SUPPORTED_DB_VERSION } from "./database_validation.js";import { getSql } from "./sql/index.js";import { getLog } from "./log.js";import { getPlatform } from "./platform.js";@@ -20,7 +21,7 @@ interface MigrationInfo {async function migrate() {const currentDbVersion = getDbVersion();- if (currentDbVersion < 214) {+ if (currentDbVersion < OLDEST_SUPPORTED_DB_VERSION) {getPlatform().crash(t("migration.old_version"));}