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
backup import: initial implementation
Adorian Dorande749736cfc6
diff --git a/apps/client/src/services/chunked_upload.spec.ts b/apps/client/src/services/chunked_upload.spec.tsnew file mode 100644index 0000000000..7c805bc1e3--- /dev/null+++ b/apps/client/src/services/chunked_upload.spec.ts@@ -0,0 +1,190 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { CHUNK_CONTENT_TYPE, ChunkedUploadError, uploadInChunks } from "./chunked_upload.js";++vi.mock("./server.js", () => ({+ default: {+ // A null header must not reach fetch, which would send it as the string "null".+ getHeaders: async () => ({ "x-csrf-token": "token", "trilium-hoisted-note-id": null })+ }+}));++const CHUNK_SIZE = 4;++/** Stands in for the endpoint: accumulates what it is sent and answers the way the server does. */+class FakeEndpoint {+ received = "";+ totalBytes = 0;+ aborted = false;+ finished = false;+ readonly calls: { method: string; url: string; headers: Record<string, string> }[] = [];+ /** Queued failures, applied to chunk requests in order. `null` sends the chunk through. */+ private readonly failures: (Failure | null)[] = [];++ failNextChunks(...failures: (Failure | null)[]) {+ this.failures.push(...failures);+ }++ fetch = async (url: string, init: RequestInit = {}): Promise<Response> => {+ const method = init.method ?? "GET";+ this.calls.push({ method, url, headers: init.headers as Record<string, string> });++ if (url.endsWith("/begin")) {+ const body = JSON.parse(String(init.body)) as { totalBytes: number };+ this.totalBytes = body.totalBytes;+ return json({ uploadId: "upload1", fileName: "backup.db", totalBytes: body.totalBytes, receivedBytes: 0, chunkSize: CHUNK_SIZE, expiresAt: 0 });+ }++ if (url.includes("/chunk?offset=")) {+ const failure = this.failures.shift();+ if (failure) {+ return failure.status ? error(failure.status, failure.message) : Promise.reject(new TypeError("Failed to fetch"));+ }++ const offset = Number(url.split("offset=")[1]);+ if (offset !== this.received.length) {+ return error(409, `Chunk starts at ${offset}, but ${this.received.length} bytes have been received.`);+ }++ this.received += await (init.body as Blob).text();+ return json(this.status());+ }++ if (url.endsWith("/finish")) {+ this.finished = true;+ return json({ restored: this.received });+ }++ if (method === "DELETE") {+ this.aborted = true;+ return new Response(null, { status: 204 });+ }++ return json(this.status());+ };++ private status() {+ return { uploadId: "upload1", fileName: "backup.db", totalBytes: this.totalBytes, receivedBytes: this.received.length, chunkSize: CHUNK_SIZE, expiresAt: 0 };+ }+}++interface Failure {+ /** Omitted for a connection that never answered at all. */+ status?: number;+ message?: string;+}++function json(body: unknown) {+ return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });+}++function error(status: number, message = "failed") {+ return new Response(JSON.stringify({ message }), { status, headers: { "content-type": "application/json" } });+}++function upload(endpoint: FakeEndpoint, content: string, overrides = {}) {+ return uploadInChunks<{ restored: string }>({+ endpoint: "setup/restore/upload",+ blob: new Blob([ content ]),+ fileName: "backup.db",+ retryDelayMs: 0,+ ...overrides+ });+}++let endpoint: FakeEndpoint;++beforeEach(() => {+ endpoint = new FakeEndpoint();+ window.glob = { ...window.glob, baseApiUrl: "api/" } as typeof window.glob;+ vi.stubGlobal("fetch", endpoint.fetch);+});++afterEach(() => vi.unstubAllGlobals());++describe("chunked upload", () => {+ it("sends the file a slice at a time and returns what the endpoint answers", async () => {+ const content = "restore me please";++ const result = await upload(endpoint, content);++ expect(result).toEqual({ restored: content });+ expect(endpoint.received).toBe(content);+ expect(endpoint.finished).toBe(true);++ const offsets = endpoint.calls.filter((call) => call.url.includes("/chunk?")).map((call) => Number(call.url.split("offset=")[1]));+ expect(offsets).toEqual([ 0, 4, 8, 12, 16 ]);+ });++ it("sends the headers the API expects, dropping the ones with nothing in them", async () => {+ await upload(endpoint, "abcd");++ const chunkCall = endpoint.calls.find((call) => call.url.includes("/chunk?"));+ expect(chunkCall?.headers).toEqual({ "x-csrf-token": "token", "content-type": CHUNK_CONTENT_TYPE });+ expect(endpoint.calls[0].headers).toMatchObject({ "content-type": "application/json" });+ });++ it("reports progress that climbs to the whole file", async () => {+ const onProgress = vi.fn();++ await upload(endpoint, "12345678", { onProgress });++ const fractions = onProgress.mock.calls.map(([ progress ]) => progress.fraction);+ expect(fractions[0]).toBe(0);+ expect(fractions.at(-1)).toBe(1);+ expect(onProgress).toHaveBeenLastCalledWith(expect.objectContaining({ sentBytes: 8, totalBytes: 8 }));+ });++ it("asks the endpoint where the file got to before retrying, so nothing is sent twice", async () => {+ // The first chunk lands but its response is lost, and the second connection simply fails.+ endpoint.failNextChunks({ status: 409, message: "offset moved" }, {});++ const result = await upload(endpoint, "abcdefgh");++ expect(result).toEqual({ restored: "abcdefgh" });+ expect(endpoint.received).toBe("abcdefgh");+ expect(endpoint.calls.filter((call) => call.method === "GET")).toHaveLength(2);+ });++ it("gives up on a failure retrying cannot fix, and tells the endpoint to forget the upload", async () => {+ endpoint.failNextChunks({ status: 400, message: "the offset must be stated as an integer" });++ await expect(upload(endpoint, "abcd")).rejects.toThrow("the offset must be stated as an integer");+ expect(endpoint.aborted).toBe(true);+ expect(endpoint.calls.filter((call) => call.url.includes("/chunk?"))).toHaveLength(1);+ });++ it("gives up once the retries are spent", async () => {+ endpoint.failNextChunks({}, {}, {}, {});++ await expect(upload(endpoint, "abcd", { maxRetriesPerChunk: 2 })).rejects.toBeInstanceOf(TypeError);+ expect(endpoint.calls.filter((call) => call.url.includes("/chunk?"))).toHaveLength(3);+ expect(endpoint.aborted).toBe(true);+ });++ it("raises the endpoint's own words, with the status it refused on", async () => {+ endpoint.failNextChunks({ status: 507, message: "the disk is full" });++ const failure = await upload(endpoint, "abcd", { maxRetriesPerChunk: 0 }).catch((e) => e);++ expect(failure).toBeInstanceOf(ChunkedUploadError);+ expect(failure).toMatchObject({ message: "the disk is full", status: 507 });+ });++ it("stops when the caller cancels, and leaves nothing behind on the endpoint", async () => {+ const controller = new AbortController();+ endpoint.failNextChunks({ status: 500 });+ controller.abort();++ await expect(upload(endpoint, "abcdefgh", { signal: controller.signal })).rejects.toThrow();+ expect(endpoint.aborted).toBe(true);+ expect(endpoint.finished).toBe(false);+ });++ it("does not try to abort a session that was never started", async () => {+ vi.stubGlobal("fetch", async () => error(409, "Another upload is already in progress."));++ await expect(upload(endpoint, "abcd")).rejects.toThrow("Another upload is already in progress.");+ expect(endpoint.aborted).toBe(false);+ });+});diff --git a/apps/client/src/services/chunked_upload.ts b/apps/client/src/services/chunked_upload.tsnew file mode 100644index 0000000000..7e93997b77--- /dev/null+++ b/apps/client/src/services/chunked_upload.ts@@ -0,0 +1,253 @@+import server from "./server.js";++/**+ * Uploads a file to a chunked upload endpoint, a slice at a time.+ *+ * A single request cannot carry a file measured in gigabytes with any confidence: a reverse proxy+ * caps the body, a timeout ends it, a dropped connection loses all of it, and there is no progress to+ * show along the way. Sending it in slices answers all four, because each slice is an ordinary small+ * request that can be retried on its own.+ *+ * The server is the authority on how far the file has got. Every failure is followed by asking it+ * where to continue from, so a slice whose response was lost is never sent twice and a slice that+ * broke partway resumes at the byte it stopped at.+ *+ * Nothing here knows what the file is for: the endpoint decides that, and `metadata` reaches it+ * untouched.+ *+ * @example+ * ```ts+ * const result = await uploadInChunks<RestoreStarted>({+ * endpoint: "setup/restore/upload",+ * blob: file,+ * fileName: file.name,+ * onProgress: ({ fraction, etaMs }) => setProgress({ fraction, etaMs }),+ * signal: abortController.signal+ * });+ * ```+ *+ * @module+ */++/** Content type of a chunk. Deliberately not `application/octet-stream`, which the server's own body+ * parser would swallow into memory before the route ever saw it. */+export const CHUNK_CONTENT_TYPE = "application/vnd.trilium.chunk";++export interface ChunkedUploadProgress {+ sentBytes: number;+ totalBytes: number;+ /** Between 0 and 1. */+ fraction: number;+ /** Averaged over the transfer so far; 0 until the first chunk lands. */+ bytesPerSecond: number;+ /** Milliseconds left at the current rate, or `null` while there is nothing to work that out from. */+ etaMs: number | null;+}++export interface ChunkedUploadOptions {+ /** Base path of the endpoint, relative to the API root, e.g. `"setup/restore/upload"`. */+ endpoint: string;+ blob: Blob;+ /** The name to give the file at the other end. */+ fileName: string;+ /** Passed to the endpoint as-is when the upload starts. */+ metadata?: Record<string, unknown>;+ onProgress?: (progress: ChunkedUploadProgress) => void;+ /** Cancels the upload and tells the server to forget it. */+ signal?: AbortSignal;+ /** Attempts per chunk before the upload gives up. Defaults to 5. */+ maxRetriesPerChunk?: number;+ /** Delay before the first retry, doubling with each further one. Defaults to 500ms. */+ retryDelayMs?: number;+}++/** What the endpoint says about a session, whether it is being started or asked after. */+export interface ChunkedUploadStatus {+ uploadId: string;+ fileName: string;+ totalBytes: number;+ receivedBytes: number;+ chunkSize: number;+ expiresAt: number;+}++/**+ * Sends `blob` to `endpoint` and returns whatever that endpoint answers once the file is complete.+ *+ * @throws the server's own message for a failure it will not recover from, or `"Upload cancelled"`+ * when the caller's signal aborts.+ */+export async function uploadInChunks<T>(options: ChunkedUploadOptions): Promise<T> {+ const { endpoint, blob, fileName, metadata, onProgress, signal } = options;+ const maxRetries = options.maxRetriesPerChunk ?? 5;+ const retryDelayMs = options.retryDelayMs ?? 500;+ const totalBytes = blob.size;++ const session = await request<ChunkedUploadStatus>("POST", `${endpoint}/begin`, {+ signal,+ body: JSON.stringify({ fileName, totalBytes, metadata }),+ contentType: "application/json"+ });++ const startedAt = Date.now();+ let sentBytes = session.receivedBytes;+ report(0);++ try {+ while (sentBytes < totalBytes) {+ // The slice and the offset are both taken when the attempt runs, not when it is written:+ // a retry that follows a resync has to send what the server is actually waiting for.+ const sent = await withRetries(+ () => request<ChunkedUploadStatus>(+ "POST",+ `${endpoint}/${session.uploadId}/chunk?offset=${sentBytes}`,+ {+ signal,+ body: blob.slice(sentBytes, sentBytes + session.chunkSize),+ contentType: CHUNK_CONTENT_TYPE+ }+ ),+ // Whatever went wrong, the server knows what it holds and this side does not: a lost+ // response means the chunk did land, a broken connection means part of it did.+ async () => {+ const status = await request<ChunkedUploadStatus>("GET", `${endpoint}/${session.uploadId}`, { signal });+ sentBytes = status.receivedBytes;+ },+ maxRetries,+ retryDelayMs,+ signal+ );++ sentBytes = sent.receivedBytes;+ report(sentBytes);+ }++ return await request<T>("POST", `${endpoint}/${session.uploadId}/finish`, { signal });+ } catch (e) {+ // The session would expire on its own, but not before holding the whole file on the server's+ // disk for an hour and, where only one upload is allowed at a time, the next attempt with it.+ await request("DELETE", `${endpoint}/${session.uploadId}`).catch(() => {});+ throw e;+ }++ function report(sent: number) {+ if (!onProgress) {+ return;+ }++ const elapsedMs = Date.now() - startedAt;+ const bytesPerSecond = sent > 0 && elapsedMs > 0 ? (sent / elapsedMs) * 1000 : 0;++ onProgress({+ sentBytes: sent,+ totalBytes,+ fraction: totalBytes > 0 ? sent / totalBytes : 0,+ bytesPerSecond,+ etaMs: bytesPerSecond > 0 ? ((totalBytes - sent) / bytesPerSecond) * 1000 : null+ });+ }+}++/**+ * Retries `attempt` while the failure is one that retrying can fix: the connection, or the server+ * having moved on from the offset the chunk was for. A rejection the request itself earned, e.g. a+ * malformed one or a session that is gone, is raised immediately rather than repeated.+ */+async function withRetries<T>(+ attempt: () => Promise<T>,+ resync: () => Promise<void>,+ maxRetries: number,+ retryDelayMs: number,+ signal?: AbortSignal+): Promise<T> {+ for (let retriesLeft = maxRetries; ; retriesLeft--) {+ try {+ return await attempt();+ } catch (e) {+ if (retriesLeft <= 0 || !isWorthRetrying(e) || signal?.aborted) {+ throw e;+ }+ }++ await delay(retryDelayMs * 2 ** (maxRetries - retriesLeft), signal);+ await resync();+ }+}++function isWorthRetrying(e: unknown): boolean {+ if (e instanceof ChunkedUploadError) {+ // A conflict means the offset has moved, which the resync then corrects; anything else in the+ // 4xx range is this side's mistake and would fail again identically.+ return e.status === 409 || e.status >= 500;+ }++ // No status at all: the request never completed, which is exactly what a retry is for.+ return !(e instanceof DOMException && e.name === "AbortError");+}++/** A response the server refused, carrying the status so the retry rules can tell the cases apart. */+export class ChunkedUploadError extends Error {+ constructor(message: string, readonly status: number) {+ super(message);+ this.name = "ChunkedUploadError";+ }+}++interface RequestOptions {+ body?: BodyInit;+ contentType?: string;+ signal?: AbortSignal;+}++async function request<T>(method: string, url: string, options: RequestOptions = {}): Promise<T> {+ const headers: Record<string, string> = {};+ for (const [ name, value ] of Object.entries(await server.getHeaders())) {+ if (value) {+ headers[name] = value;+ }+ }+ if (options.contentType) {+ headers["content-type"] = options.contentType;+ }++ const response = await fetch(`${window.glob.baseApiUrl}${url}`, {+ method,+ headers,+ body: options.body,+ signal: options.signal+ });++ if (!response.ok) {+ throw new ChunkedUploadError(await messageOf(response), response.status);+ }++ return response.status === 204 ? (undefined as T) : await response.json() as T;+}++/** The server's own words where it gave any, since they are what the user is shown. */+async function messageOf(response: Response): Promise<string> {+ try {+ const body = await response.text();+ const parsed = body.startsWith("{") ? JSON.parse(body) as { message?: string } : null;++ return parsed?.message || body || response.statusText;+ } catch {+ return response.statusText;+ }+}++function delay(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ signal?.removeEventListener("abort", onAbort);+ resolve();+ }, ms);++ function onAbort() {+ clearTimeout(timer);+ reject(new DOMException("Upload cancelled", "AbortError"));+ }++ signal?.addEventListener("abort", onAbort, { once: true });+ });+}diff --git a/apps/client/src/services/database_files.ts b/apps/client/src/services/database_files.tsnew file mode 100644index 0000000000..440d76009b--- /dev/null+++ b/apps/client/src/services/database_files.ts@@ -0,0 +1,38 @@+import { formatDateTime } from "../utils/formatters.js";+import { t } from "./i18n.js";+import { formatSize } from "./utils.js";++/** A file holding a database: a backup, or an anonymized copy. */+export interface DatabaseFile {+ fileName: string;+ filePath: string;+ mtime: Date;+ /** Size of the file, in bytes. */+ fileSize: number;+ /**+ * Size of the database the file was made from, in bytes, where that differs from the file's own+ * size — a compressed backup, say. Both are then shown, so the saving is visible.+ */+ plaintextSize?: number;+}++/**+ * When the file was written, and how big it is.+ *+ * A file made from a database larger than itself states both, so what compressing it saved is+ * visible rather than having to be worked out.+ *+ * Shared by every list of these files — the backups in the options, the backups the setup screen+ * offers to restore from — so that one line reads the same wherever it appears.+ */+export function describeDatabaseFile(file: DatabaseFile): string {+ const parts = [ file.mtime ? formatDateTime(file.mtime) : "-" ];++ if (file.plaintextSize && file.plaintextSize !== file.fileSize) {+ parts.push(formatSize(file.plaintextSize), t("database_file_list.size_on_disk", { size: formatSize(file.fileSize) }));+ } else {+ parts.push(formatSize(file.fileSize));+ }++ return parts.join(" • ");+}diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex 4ca3760913..cdd55ce95c 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -10,6 +10,7 @@ import logo from "./assets/icon-color.svg?url";import { getCurrentLanguage, initLocale, t } from "./services/i18n";import server from "./services/server";import { isElectron, isMobileApp } from "./services/utils";+import RestoreFromBackup from "./setup_restore";import Admonition, { ExtendedAdmonition } from "./widgets/react/Admonition";import Button from "./widgets/react/Button";import { Card, CardFrame, CardSection } from "./widgets/react/Card";@@ -38,9 +39,9 @@ async function main() {document.body.replaceChildren(bodyWrapper);}-type State = "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";+type State = "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";-const STATE_ORDER: State[] = ["selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];+const STATE_ORDER: State[] = ["selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];export function renderState(state: State, setState: (state: State) => void) {switch (state) {@@ -49,6 +50,7 @@ export function renderState(state: State, setState: (state: State) => void) {case "createNewDocumentOptions": return <CreateNewDocumentOptions setState={setState} />;case "createNewDocumentWithDemo": return <CreateNewDocumentInProgress withDemo />;case "createNewDocumentEmpty": return <CreateNewDocumentInProgress />;+ case "restoreFromBackup": return <RestoreFromBackup onBack={() => setState("firstOptions")} onRestored={onSetupFinished} />;case "syncFromServer": return <SyncFromServer setState={setState} />;case "syncFromDesktop": return <SyncFromDesktop setState={setState} />;case "syncFromServerInProgress": return <SyncInProgress device="server" setState={setState} />;@@ -162,6 +164,16 @@ function SetupOptions({ setState }: { setState: (state: State) => void }) {onClick={() => setState("createNewDocumentOptions")}/>+ <SetupOptionCard+ icon="bx bx-archive-in"+ title={t("setup.restore-from-backup")}+ description={t("setup.restore-from-backup-description")}+ // The backup has to be unwrapped and opened by a real database engine, which the+ // standalone build does not have: its database lives in the browser's own storage.+ disabled={glob.isStandalone}+ onClick={() => setState("restoreFromBackup")}+ />+<SetupOptionCardicon="bx bx-server"title={t("setup.sync-from-server")}diff --git a/apps/client/src/setup_restore.css b/apps/client/src/setup_restore.cssnew file mode 100644index 0000000000..b608359ec3--- /dev/null+++ b/apps/client/src/setup_restore.css@@ -0,0 +1,96 @@+.page.restore-from-backup {+ .restore-backup-row {+ display: flex;+ align-items: center;+ gap: 0.75em;+ cursor: pointer;++ > .bx-chevron-right {+ margin-left: auto;+ opacity: 0.5;+ }+ }++ .restore-backup-details {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ .restore-backup-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .restore-backup-description {+ font-size: 0.85em;+ opacity: 0.7;+ }++ .restore-loading {+ display: flex;+ align-items: center;+ gap: 0.5em;+ opacity: 0.7;+ }++ .restore-file-section {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 0.75em;++ p {+ margin: 0;+ opacity: 0.7;+ }+ }++ /* Driven by the button next to it, which is the only thing the user should be aiming at. */+ .restore-file-input {+ display: none;+ }++ .restore-passphrase-actions {+ display: flex;+ justify-content: flex-end;+ margin-top: 1em;+ }++ .restore-progress {+ .restore-progress-label {+ display: flex;+ align-items: center;+ gap: 0.5em;+ }++ progress {+ width: 100%;+ margin-top: 0.75em;+ }++ .restore-progress-detail {+ margin-top: 0.35em;+ font-size: 0.85em;+ opacity: 0.7;+ }+ }++ .restore-stages .tn-card-section {+ display: flex;+ align-items: center;+ gap: 0.5em;+ opacity: 0.5;+ transition: opacity 150ms ease;++ &.active,+ &.completed {+ opacity: 1;+ }+ }++ .restore-banner {+ margin-top: 1em;+ }+}diff --git a/apps/client/src/setup_restore.spec.tsx b/apps/client/src/setup_restore.spec.tsxnew file mode 100644index 0000000000..bc05d15f38--- /dev/null+++ b/apps/client/src/setup_restore.spec.tsx@@ -0,0 +1,239 @@+import { render } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// t() returns the key so assertions are deterministic and not tied to English text.+vi.mock("./services/i18n", () => ({ t: (key: string) => key }));++const serverMock = vi.hoisted(() => ({+ // The default serves what transitively imported modules ask for as they load (keyboard_actions+ // fetches its shortcut list on import); the routing installed in beforeEach overrides it.+ get: vi.fn(async (url: string): Promise<unknown> => (url === "keyboard-actions" ? [] : {})),+ post: vi.fn(async (): Promise<unknown> => ({}))+}));+vi.mock("./services/server", () => ({ default: serverMock }));++const uploadMock = vi.hoisted(() => ({ uploadInChunks: vi.fn() }));+vi.mock("./services/chunked_upload", () => uploadMock);++import RestoreFromBackup from "./setup_restore";++const BACKUPS = [+ { fileName: "backup-daily.db", filePath: "/data/backup/backup-daily.db", mtime: "2026-08-01T10:00:00Z", fileSize: 2048, encrypted: false },+ { fileName: "backup-weekly.tnbackup", filePath: "/data/backup/backup-weekly.tnbackup", mtime: "2026-08-05T10:00:00Z", fileSize: 1024, encrypted: true }+];++let container: HTMLDivElement;+let restore: { stage: string; error?: string; reason?: string } | null;++function renderRestore(props: Partial<{ onBack: () => void; onRestored: () => void }> = {}) {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(<RestoreFromBackup onBack={props.onBack ?? vi.fn()} onRestored={props.onRestored ?? vi.fn()} />, container);++ return container;+}++const flushEffects = () => vi.advanceTimersByTimeAsync(50);+const nextPoll = () => vi.advanceTimersByTimeAsync(1000);++/** The row for a backup, which is the whole clickable section rather than a button inside it. */+function backupRow(name: string) {+ return [ ...container.querySelectorAll<HTMLElement>(".restore-backup-row") ]+ .find((row) => row.textContent?.includes(name));+}++beforeEach(() => {+ vi.useFakeTimers();+ restore = null;+ serverMock.get.mockImplementation(async (url: string) => {+ if (url === "database/backups") {+ return { backups: BACKUPS, backupFolderPath: "/data/backup" };+ }+ if (url === "keyboard-actions") {+ return [];+ }+ return { restore };+ });+ serverMock.post.mockResolvedValue({ started: true });+});++afterEach(() => {+ render(null, container);+ container.remove();+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe("picking a backup", () => {+ it("lists what is on the device, newest first, and starts restoring the one that is picked", async () => {+ renderRestore();+ await flushEffects();++ const names = [ ...container.querySelectorAll(".restore-backup-name") ].map((row) => row.textContent);+ expect(names).toEqual([ "backup-weekly.tnbackup", "backup-daily.db" ]);++ backupRow("backup-daily.db")?.click();+ await flushEffects();++ expect(serverMock.post).toHaveBeenCalledWith("setup/restore/start", {+ source: "existing",+ filePath: "/data/backup/backup-daily.db",+ passphrase: undefined+ });+ expect(container.querySelector(".restore-stages")).toBeTruthy();+ });++ it("asks for the password first when the backup is encrypted, and sends it with the restore", async () => {+ renderRestore();+ await flushEffects();++ backupRow("backup-weekly.tnbackup")?.click();+ await flushEffects();++ expect(serverMock.post).not.toHaveBeenCalled();+ const input = container.querySelector<HTMLInputElement>("input[type=password]");+ expect(input).toBeTruthy();++ if (input) {+ input.value = "hunter2";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ }+ await flushEffects();+ container.querySelector("form")?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ await flushEffects();++ expect(serverMock.post).toHaveBeenCalledWith("setup/restore/start", {+ source: "existing",+ filePath: "/data/backup/backup-weekly.tnbackup",+ passphrase: "hunter2"+ });+ });++ it("still offers a file when the backups cannot be listed", async () => {+ serverMock.get.mockRejectedValueOnce(new Error("no backup directory"));++ renderRestore();+ await flushEffects();++ expect(container.querySelector(".restore-file-input")).toBeTruthy();+ expect(container.textContent).toContain("setup.restore-no-backups");+ });+});++describe("uploading a backup", () => {+ /** Drives the file input the "choose a file" button opens. */+ async function chooseFile(file: File) {+ const input = container.querySelector<HTMLInputElement>(".restore-file-input");+ Object.defineProperty(input, "files", { value: [ file ], configurable: true });+ input?.dispatchEvent(new Event("change", { bubbles: true }));+ await flushEffects();+ }++ it("sends the file in chunks, shows how far it has got, and restores it once it is there", async () => {+ uploadMock.uploadInChunks.mockImplementation(async ({ onProgress }: { onProgress: (p: unknown) => void }) => {+ onProgress({ sentBytes: 512, totalBytes: 1024, fraction: 0.5 });+ return { fileName: "backup.db", encrypted: false };+ });+ renderRestore();+ await flushEffects();++ await chooseFile(new File([ "database bytes" ], "backup.db"));++ expect(uploadMock.uploadInChunks).toHaveBeenCalledWith(expect.objectContaining({+ endpoint: "setup/restore/upload",+ fileName: "backup.db"+ }));+ expect(serverMock.post).toHaveBeenCalledWith("setup/restore/start", {+ source: "uploaded",+ filePath: undefined,+ passphrase: undefined+ });+ });++ it("asks for the password when what arrived turns out to be encrypted", async () => {+ uploadMock.uploadInChunks.mockResolvedValue({ fileName: "backup.tnbackup", encrypted: true });+ renderRestore();+ await flushEffects();++ await chooseFile(new File([ "container bytes" ], "backup.tnbackup"));++ expect(serverMock.post).not.toHaveBeenCalled();+ expect(container.querySelector("input[type=password]")).toBeTruthy();+ });++ it("goes back to the picker with the reason when the upload fails", async () => {+ uploadMock.uploadInChunks.mockRejectedValue(new Error("the disk is full"));+ renderRestore();+ await flushEffects();++ await chooseFile(new File([ "database bytes" ], "backup.db"));++ expect(container.textContent).toContain("setup.restore-upload-failed");+ expect(container.querySelector(".restore-file-input")).toBeTruthy();+ });+});++describe("following the restore", () => {+ async function startRestore() {+ renderRestore({ onRestored });+ await flushEffects();+ backupRow("backup-daily.db")?.click();+ await flushEffects();+ }++ let onRestored: () => void;++ beforeEach(() => { onRestored = vi.fn(); });++ it("moves through the stages the server reports", async () => {+ await startRestore();++ restore = { stage: "validating" };+ await nextPoll();++ const active = container.querySelector(".restore-stages .active");+ expect(active?.textContent).toContain("setup.restore-stage-validating");+ });++ it("finishes setup once the restore is done", async () => {+ await startRestore();++ restore = { stage: "done" };+ await nextPoll();++ expect(onRestored).toHaveBeenCalled();+ });++ it("survives the moment the database is detached and no request can be answered", async () => {+ await startRestore();++ serverMock.get.mockRejectedValueOnce(new Error("DB not open."));+ await nextPoll();++ expect(container.querySelector(".restore-stages")).toBeTruthy();++ restore = { stage: "done" };+ await nextPoll();+ expect(onRestored).toHaveBeenCalled();+ });++ it("goes back to the password when that is what was wrong, rather than to the start", async () => {+ await startRestore();++ restore = { stage: "failed", reason: "wrong-passphrase-or-damaged-header", error: "Verifier tag did not match." };+ await nextPoll();++ expect(container.querySelector("input[type=password]")).toBeTruthy();+ expect(container.textContent).toContain("setup.restore-wrong-passphrase");+ });++ it("reports a failure nothing can be done about, back at the picker", async () => {+ await startRestore();++ restore = { stage: "failed", reason: "database-too-new", error: "The database is version 999." };+ await nextPoll();++ expect(container.textContent).toContain("The database is version 999.");+ expect(container.querySelector(".restore-file-input")).toBeTruthy();+ });+});diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxnew file mode 100644index 0000000000..150fc63286--- /dev/null+++ b/apps/client/src/setup_restore.tsx@@ -0,0 +1,341 @@+import "./setup_restore.css";++import type { DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commons";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import { uploadInChunks } from "./services/chunked_upload";+import { describeDatabaseFile } from "./services/database_files";+import { t } from "./services/i18n";+import server from "./services/server";+import { formatSize } from "./services/utils";+import Admonition from "./widgets/react/Admonition";+import Button from "./widgets/react/Button";+import { Card, CardSection } from "./widgets/react/Card";+import FormGroup from "./widgets/react/FormGroup";+import FormTextBox from "./widgets/react/FormTextBox";+import Icon from "./widgets/react/Icon";+import NoItems from "./widgets/react/NoItems";+import SetupPage from "./widgets/react/SetupPage";++/**+ * The setup screen's "restore from backup" path, from picking a backup to the restored database+ * being open.+ *+ * One component rather than three wizard states, because the steps are one decision followed by its+ * consequences: which backup, the passphrase it turns out to need, and then waiting. Going back from+ * the passphrase means picking again, which is what the wizard's own back button already means.+ *+ * @module+ */++/** What the restore is waiting on, as far as this screen is concerned. */+type Step = "picking" | "uploading" | "passphrase" | "restoring";++/** Failures the same backup can still get past, which send the user back to the passphrase rather than to the start. */+const PASSPHRASE_FAILURES = new Set([ "passphrase-required", "wrong-passphrase-or-damaged-header" ]);++export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () => void; onRestored: () => void }) {+ const [ step, setStep ] = useState<Step>("picking");+ const [ selection, setSelection ] = useState<Selection | null>(null);+ const [ upload, setUpload ] = useState<UploadState | null>(null);+ const [ error, setError ] = useState<string | null>(null);+ const [ errorId, setErrorId ] = useState(0);+ const [ wrongPassphrase, setWrongPassphrase ] = useState(false);++ const raiseError = useCallback((message: string) => {+ setError(message);+ setErrorId((id) => id + 1);+ }, []);++ /** Sends the restore on its way, or asks for the passphrase first where the backup needs one. */+ const restore = useCallback(async (picked: Selection, passphrase?: string) => {+ setSelection(picked);++ if (picked.encrypted && !passphrase) {+ setStep("passphrase");+ return;+ }++ try {+ await server.post("setup/restore/start", {+ source: picked.source,+ filePath: picked.filePath,+ passphrase+ });+ setStep("restoring");+ } catch (e) {+ setStep("picking");+ raiseError(e instanceof Error ? e.message : String(e));+ }+ }, [ raiseError ]);++ async function uploadAndRestore(file: File) {+ setStep("uploading");+ setUpload({ sentBytes: 0, totalBytes: file.size, fraction: 0 });++ try {+ const uploaded = await uploadInChunks<{ fileName: string; encrypted: boolean }>({+ endpoint: "setup/restore/upload",+ blob: file,+ fileName: file.name,+ onProgress: ({ sentBytes, totalBytes, fraction }) => setUpload({ sentBytes, totalBytes, fraction })+ });++ await restore({ source: "uploaded", fileName: uploaded.fileName, encrypted: uploaded.encrypted });+ } catch (e) {+ setStep("picking");+ raiseError(t("setup.restore-upload-failed", { message: e instanceof Error ? e.message : String(e) }));+ }+ }++ function onRestoreFailed(failure: { error?: string; reason?: string }) {+ if (failure.reason && PASSPHRASE_FAILURES.has(failure.reason)) {+ // The backup is still on the server, so only the passphrase has to be given again.+ setWrongPassphrase(true);+ setStep("passphrase");+ return;+ }++ setStep("picking");+ raiseError(failure.error ?? t("setup.restore-failed-generic"));+ }++ return (+ <SetupPage+ className="restore-from-backup top-aligned"+ title={t("setup.restore-from-backup")}+ description={step === "picking" ? t("setup.restore-from-backup-page-description") : undefined}+ illustration={<Icon icon="bx bx-archive-in" className="illustration-icon" />}+ error={error}+ errorId={errorId}+ onBack={step === "restoring" ? undefined : onBack}+ >+ {step === "picking" && <PickBackup onPick={restore} onUpload={uploadAndRestore} />}+ {step === "uploading" && upload && <UploadProgress upload={upload} />}+ {step === "passphrase" && selection && (+ <AskPassphrase+ fileName={selection.fileName}+ wrong={wrongPassphrase}+ onSubmit={(passphrase) => {+ setWrongPassphrase(false);+ void restore(selection, passphrase);+ }}+ />+ )}+ {step === "restoring" && (+ <RestoreProgress onRestored={onRestored} onFailed={onRestoreFailed} />+ )}+ </SetupPage>+ );+}++/** Which backup is being restored, and where it is. */+interface Selection {+ source: "uploaded" | "existing";+ fileName: string;+ /** Only for a backup already on the server. */+ filePath?: string;+ encrypted?: boolean;+}++interface UploadState {+ sentBytes: number;+ totalBytes: number;+ fraction: number;+}++/** The backups already on this device, and the way to a file that is not. */+function PickBackup({ onPick, onUpload }: { onPick: (selection: Selection) => void; onUpload: (file: File) => void }) {+ const [ backups, setBackups ] = useState<DatabaseBackup[] | null>(null);+ const fileInput = useRef<HTMLInputElement>(null);++ useEffect(() => {+ server.get<ExistingBackupsResponse>("database/backups")+ .then((response) => setBackups(response.backups))+ // An unreadable backup directory is not a reason to lose the "choose a file" path.+ .catch(() => setBackups([]));+ }, []);++ const sorted = [ ...(backups ?? []) ].sort((a, b) => (a.mtime < b.mtime ? 1 : -1));++ return (+ <>+ <Card heading={t("setup.restore-existing-backups")}>+ {backups === null ? (+ <CardSection className="restore-loading">+ <Icon icon="bx bx-loader-circle bx-spin" /> {t("setup.restore-looking-for-backups")}+ </CardSection>+ ) : sorted.length > 0 ? (+ sorted.map((backup) => (+ <CardSection+ key={backup.filePath}+ className="restore-backup-row"+ onAction={() => onPick({+ source: "existing",+ fileName: backup.fileName,+ filePath: backup.filePath,+ encrypted: backup.encrypted+ })}+ >+ <Icon icon={backup.encrypted ? "bx bx-lock-alt" : "bx bx-data"} />++ <div class="restore-backup-details">+ <div class="restore-backup-name">{backup.fileName}</div>+ <div class="restore-backup-description">{describeDatabaseFile(backup)}</div>+ </div>++ <Icon icon="bx bx-chevron-right" />+ </CardSection>+ ))+ ) : (+ <CardSection>+ <NoItems icon="bx bx-archive" text={t("setup.restore-no-backups")} />+ </CardSection>+ )}+ </Card>++ <Card heading={t("setup.restore-from-a-file")}>+ <CardSection className="restore-file-section">+ <p>{t("setup.restore-from-a-file-description")}</p>++ <input+ ref={fileInput}+ type="file"+ accept=".db,.tnbackup"+ class="restore-file-input"+ onChange={(e) => {+ const file = (e.target as HTMLInputElement).files?.[0];+ if (file) {+ onUpload(file);+ }+ }}+ />++ <Button+ kind="primary"+ icon="bx bx-folder-open"+ text={t("setup.restore-choose-file")}+ onClick={() => fileInput.current?.click()}+ />+ </CardSection>+ </Card>+ </>+ );+}++function UploadProgress({ upload }: { upload: UploadState }) {+ return (+ <Card className="restore-progress">+ <CardSection>+ <div class="restore-progress-label">+ <Icon icon="bx bx-loader-circle bx-spin" /> {t("setup.restore-uploading")}+ </div>++ <progress value={upload.sentBytes} max={upload.totalBytes} />++ <div class="restore-progress-detail">+ {t("setup.restore-uploaded-so-far", {+ sent: formatSize(upload.sentBytes),+ total: formatSize(upload.totalBytes)+ })}+ </div>+ </CardSection>+ </Card>+ );+}++function AskPassphrase({ fileName, wrong, onSubmit }: { fileName: string; wrong: boolean; onSubmit: (passphrase: string) => void }) {+ const [ passphrase, setPassphrase ] = useState("");+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => inputRef.current?.focus(), []);++ return (+ <form onSubmit={(e) => {+ e.preventDefault();+ if (passphrase) {+ onSubmit(passphrase);+ }+ }}>+ <Card heading={fileName}>+ <CardSection>+ <FormGroup+ name="backupPassphrase"+ label={t("setup.restore-passphrase")}+ description={t("setup.restore-passphrase-description")}+ error={wrong ? t("setup.restore-wrong-passphrase") : undefined}+ >+ <FormTextBox+ inputRef={inputRef}+ type="password"+ currentValue={passphrase}+ onChange={setPassphrase}+ autocomplete="off"+ />+ </FormGroup>+ </CardSection>+ </Card>++ <div class="restore-passphrase-actions">+ <Button kind="primary" text={t("setup.restore-continue")} disabled={!passphrase} />+ </div>+ </form>+ );+}++/** The stages the server works through, and which one it is on. */+const STAGES = [ "staging", "validating", "swapping", "migrating" ] as const;++function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onFailed: (failure: { error?: string; reason?: string }) => void }) {+ const [ stage, setStage ] = useState<string>("staging");++ useEffect(() => {+ const interval = setInterval(async () => {+ let restore;+ try {+ ({ restore } = await server.get<{ restore: { stage: string; error?: string; reason?: string } | null }>("setup/restore/status"));+ } catch {+ // The database is detached for the moment it takes to exchange the files, which any+ // request landing in that moment cannot be answered through. The next one can.+ return;+ }++ if (!restore) {+ return;+ }+ if (restore.stage === "done") {+ clearInterval(interval);+ onRestored();+ return;+ }+ if (restore.stage === "failed") {+ clearInterval(interval);+ onFailed(restore);+ return;+ }++ setStage(restore.stage);+ }, 1000);++ return () => clearInterval(interval);+ }, [ onRestored, onFailed ]);++ const currentIndex = STAGES.indexOf(stage as typeof STAGES[number]);++ return (+ <>+ <Card className="restore-stages">+ {STAGES.map((name, index) => (+ <CardSection key={name} className={index < currentIndex ? "completed" : index === currentIndex ? "active" : ""}>+ <Icon icon={index < currentIndex ? "bx bx-check-circle" : index === currentIndex ? "bx bx-loader-circle bx-spin" : "bx bx-circle"} />{" "}+ {t(`setup.restore-stage-${name}`)}+ </CardSection>+ ))}+ </Card>++ <Admonition type="warning" className="restore-banner">+ {t("setup.restore-do-not-close")}+ </Admonition>+ </>+ );+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 54c7ce081c..89f1563e32 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3681,7 +3681,29 @@"wrong-password": "Incorrect password. Please try again.","language": "Language","continue": "Continue",- "your-ip-addresses": "Addresses for this device"+ "your-ip-addresses": "Addresses for this device",+ "restore-from-backup": "Restore from backup",+ "restore-from-backup-description": "You have a backup of a Trilium database. This device will start from the contents of that backup.",+ "restore-from-backup-page-description": "Pick one of the backups found on this device, or open a backup file from elsewhere.",+ "restore-existing-backups": "Backups on this device",+ "restore-looking-for-backups": "Looking for backups...",+ "restore-no-backups": "No backups were found on this device.",+ "restore-from-a-file": "From a file",+ "restore-from-a-file-description": "Choose a .db or .tnbackup file. Large backups are sent in pieces, so an interrupted transfer carries on rather than starting again.",+ "restore-choose-file": "Choose a backup file",+ "restore-uploading": "Sending the backup...",+ "restore-uploaded-so-far": "{{sent}} of {{total}}",+ "restore-upload-failed": "The backup could not be sent: {{- message}}",+ "restore-failed-generic": "The backup could not be restored.",+ "restore-passphrase": "Backup password",+ "restore-passphrase-description": "This backup is encrypted. Enter the password it was created with.",+ "restore-wrong-passphrase": "That password does not open this backup. Please try again.",+ "restore-continue": "Restore",+ "restore-stage-staging": "Preparing the backup",+ "restore-stage-validating": "Checking the database",+ "restore-stage-swapping": "Putting it in place",+ "restore-stage-migrating": "Opening the database",+ "restore-do-not-close": "Don't close this window until the restore has finished. On a server, you will sign in with the password that the backup was made with."},"mind-map": {"addChild": "Add child",diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsxindex e4e5e04488..1675e14f7d 100644--- a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx@@ -3,28 +3,15 @@ import "./DatabaseFileList.css";import { ComponentChildren } from "preact";import { useMemo } from "preact/hooks";-import { t } from "../../../../services/i18n";+import { type DatabaseFile, describeDatabaseFile } from "../../../../services/database_files";import open from "../../../../services/open";-import { formatSize } from "../../../../services/utils";-import { formatDateTime } from "../../../../utils/formatters";import ActionButton from "../../../react/ActionButton";import { Badge } from "../../../react/Badge";import NoItems from "../../../react/NoItems";import OptionsRow from "./OptionsRow";import OptionsSection from "./OptionsSection";-export interface DatabaseFile {- fileName: string;- filePath: string;- mtime: Date;- /** Size of the file, in bytes. */- fileSize: number;- /**- * Size of the database the file was made from, in bytes, where that differs from the file's own- * size — a compressed backup, say. Both are then shown, so the saving is visible.- */- plaintextSize?: number;-}+export type { DatabaseFile };interface DatabaseFileListProps<T extends DatabaseFile> {title: string;@@ -71,7 +58,7 @@ export default function DatabaseFileList<T extends DatabaseFile>({ title, locati))}</span>}- description={describeFile(file)}+ description={describeDatabaseFile(file)}><ActionButtonicon="bx bx-download"@@ -88,19 +75,3 @@ export default function DatabaseFileList<T extends DatabaseFile>({ title, locati</OptionsSection>);}--/**- * When the file was written, and how big it is. A file made from a database larger than itself states- * both, so what compressing it saved is visible rather than having to be worked out.- */-function describeFile(file: DatabaseFile): string {- const parts = [file.mtime ? formatDateTime(file.mtime) : "-"];-- if (file.plaintextSize && file.plaintextSize !== file.fileSize) {- parts.push(formatSize(file.plaintextSize), t("database_file_list.size_on_disk", { size: formatSize(file.fileSize) }));- } else {- parts.push(formatSize(file.fileSize));- }-- return parts.join(" • ");-}diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 6703fe648b..b31d801048 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -6,6 +6,7 @@ import NodejsCryptoProvider from "@triliumnext/server/src/crypto_provider.js";import NodejsInAppHelpProvider from "@triliumnext/server/src/in_app_help_provider.js";import ServerLogService from "@triliumnext/server/src/log_provider.js";import config from "@triliumnext/server/src/services/config.js";+import { recoverInterruptedRestore } from "@triliumnext/server/src/services/database_restore.js";import dataDirs from "@triliumnext/server/src/services/data_dir.js";import port from "@triliumnext/server/src/services/port.js";import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";@@ -192,6 +193,10 @@ export async function main() {config.Security.allowLanAccess = securitySettings.allowLanAccess;}+ // Before the database is opened: undoes a restore that was interrupted partway through+ // exchanging the files, so the app starts on a whole database rather than on neither.+ recoverInterruptedRestore();+const dbProvider = new BetterSqlite3Provider();dbProvider.loadFromFile(dataDirs.DOCUMENT_PATH, config.General.readOnly);markStartupMetric("database-opened");diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.tsindex d4eb87e1dc..1a9936533a 100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@ -104,18 +104,27 @@ export default class ServerBackupService extends BackupService {}override async getBackupContent(filePath: string): Promise<Uint8Array | null> {+ const resolvedPath = this.resolveBackupPath(filePath);++ return resolvedPath ? fs.readFileSync(resolvedPath) : null;+ }++ /**+ * The absolute path of an existing backup, or `null` for anything that is not one.+ *+ * A path arriving from a client is a request to name a file, not permission to reach it: without+ * this, an endpoint taking one would read any file the process can. Callers that only need the+ * path use this directly rather than {@link getBackupContent}, which reads the whole file into+ * memory — no use at all for a backup measured in gigabytes.+ */+ resolveBackupPath(filePath: string): string | null {const resolvedPath = path.resolve(filePath);- // Security check: ensure the path is within one of the backup directoriesif (!this.getBackupDirectories().some((dir) => isInsideDirectory(dir, resolvedPath))) {return null;}- if (!fs.existsSync(resolvedPath)) {- return null;- }-- return fs.readFileSync(resolvedPath);+ return fs.existsSync(resolvedPath) ? resolvedPath : null;}/**diff --git a/apps/server/src/main.ts b/apps/server/src/main.tsindex ae405abbac..4e98d14538 100644--- a/apps/server/src/main.ts+++ b/apps/server/src/main.ts@@ -27,6 +27,11 @@ async function startApplication() {const config = (await import("./services/config.js")).default;const { DOCUMENT_PATH } = (await import("./services/data_dir.js")).default;+ // Before anything opens the database: a restore that was interrupted between moving the old+ // document aside and opening the new one is undone here, so the instance starts on a database+ // that is whole rather than on whichever half the interruption left behind.+ (await import("./services/database_restore.js")).recoverInterruptedRestore();+const dbProvider = new BetterSqlite3Provider();if (process.env.TRILIUM_INTEGRATION_TEST === "memory") {// Load the database file into memory so mutations don't persist todiff --git a/apps/server/src/routes/api/setup_restore.ts b/apps/server/src/routes/api/setup_restore.tsnew file mode 100644index 0000000000..990bde43ac--- /dev/null+++ b/apps/server/src/routes/api/setup_restore.ts@@ -0,0 +1,209 @@+import { getBackup, getLog, holdSetup, NotFoundError, ValidationError, withSetupLock } from "@triliumnext/core";+import type { Request } from "express";+import fs from "fs";+import path from "path";++import type ServerBackupService from "../../backup_provider.js";+import { createChunkedUpload } from "../../services/chunked_upload.js";+import dataDir from "../../services/data_dir.js";+import {+ getRestoreProgress,+ readBackupFormat,+ restoreDatabase,+ RestoreFailure,+ type RestoreFailureReason,+ type RestoreProgress+} from "../../services/database_restore.js";++/**+ * The setup screen's way back from a backup: list what is already on disk, take a file that is not,+ * and restore whichever the user picks.+ *+ * Every endpoint here is reachable without authentication, because before the database exists there+ * is nobody to authenticate — the same footing the rest of the setup wizard stands on. What that+ * costs is bounded deliberately: one upload at a time, a ceiling on its size, a session that expires,+ * and a path from the listing that is checked against the backup directories rather than taken at+ * its word.+ *+ * @module+ */++/** No database is worth more than this, and an upload claiming to be is refused before it starts. */+const MAX_BACKUP_BYTES = 64 * 1024 * 1024 * 1024;++/** Failures another passphrase could still get past, which is the only reason to keep the file. */+const RETRYABLE_WITH_ANOTHER_PASSPHRASE = new Set<RestoreFailureReason>([+ "passphrase-required",+ "wrong-passphrase-or-damaged-header"+]);++/**+ * Where a finished upload waits between arriving and being restored.+ *+ * Deliberately outside the restore's own working directory, which is emptied whenever a restore+ * ends: a wrong passphrase would otherwise take the uploaded backup with it, and the user would have+ * to send the whole file again to try another one.+ */+const PENDING_UPLOAD_PATH = path.join(dataDir.TMP_DIR, "uploads", "pending-backup");++/** What an upload turned out to be, which decides whether the user is asked for a passphrase. */+interface PendingUpload {+ fileName: string;+ encrypted: boolean;+}++let pendingUpload: PendingUpload | null = null;+let releaseSetupHold: (() => void) | null = null;++const upload = createChunkedUpload<PendingUpload>({+ name: "restore",+ directory: path.join(dataDir.TMP_DIR, "uploads"),+ maxTotalBytes: MAX_BACKUP_BYTES,+ requireFreeSpace: true,+ onComplete: async ({ path: uploadedPath, fileName }) => {+ fs.mkdirSync(path.dirname(PENDING_UPLOAD_PATH), { recursive: true });+ fs.rmSync(PENDING_UPLOAD_PATH, { force: true });+ // A move rather than a copy: the file is the size of a database, and both ends are in the+ // same temporary directory.+ fs.renameSync(uploadedPath, PENDING_UPLOAD_PATH);++ pendingUpload = {+ fileName,+ // Stated in the clear in a container's header, so the setup screen knows to ask for a+ // passphrase without having to try the restore and fail first.+ encrypted: readBackupFormat(PENDING_UPLOAD_PATH)?.encrypted ?? false+ };+ getLog().info(`A backup was uploaded for restoring (${fileName}).`);++ return pendingUpload;+ }+});++/**+ * Starts an upload, and reserves setup for it: what arrives is going to replace the database, and an+ * hour of uploading must not end with another tab having created a document in the meantime.+ */+async function beginUpload(req: Request) {+ const status = await upload.begin(req);++ // Taken after the upload is accepted, so a refused one does not leave setup reserved. Released+ // when the restore ends, when the upload is abandoned, or when its session expires.+ releaseSetupHold ??= holdSetup("restore-backup");++ return status;+}++async function uploadChunk(req: Request) {+ return await upload.chunk(req);+}++async function uploadStatus(req: Request) {+ return await upload.status(req);+}++async function finishUpload(req: Request) {+ return await upload.finish(req);+}++async function abortUpload(req: Request) {+ await upload.abort(req);+ discardPendingUpload();+}++/**+ * Restores the backup the user picked: the one just uploaded, or one from the backup directory.+ *+ * Answers as soon as the restore is under way rather than when it is over, since unwrapping,+ * checking and migrating a large database outlast any sensible request. The client follows the rest+ * through {@link status}.+ */+async function start(req: Request) {+ const { source, filePath, passphrase } = (req.body ?? {}) as StartBody;+ const request = source === "existing"+ ? existingBackup(filePath)+ : uploadedBackup();++ // Deliberately not awaited: the restore runs on past this response, holding the setup lock for+ // as long as it takes, and reports itself through the status endpoint.+ void withSetupLock("restore-backup", async () => {+ try {+ await restoreDatabase({ ...request, passphrase });+ discardPendingUpload();+ } catch (e) {+ // A passphrase that was wrong or missing is the one failure the same file can still+ // recover from, so the upload is kept for the next attempt. Anything else is a file that+ // will fail the same way however often it is tried.+ if (!(e instanceof RestoreFailure) || !RETRYABLE_WITH_ANOTHER_PASSPHRASE.has(e.reason)) {+ discardPendingUpload();+ }++ throw e;+ }+ }).catch(() => {+ // Already recorded in the progress the client is polling, and logged where it happened.+ });++ return { started: true };+}++function status(): { restore: RestoreProgress | null } {+ return { restore: getRestoreProgress() };+}++/** Drops the sweeper's timer. Only the tests have any use for a shutdown this tidy. */+function stop() {+ upload.stop();+}++export default {+ beginUpload,+ uploadChunk,+ uploadStatus,+ finishUpload,+ abortUpload,+ start,+ status,+ stop+};++interface StartBody {+ source?: "uploaded" | "existing";+ /** Only for `existing`: which backup, from the listing. */+ filePath?: string;+ passphrase?: string;+}++function uploadedBackup() {+ if (!pendingUpload) {+ throw new NotFoundError("No uploaded backup is waiting to be restored.");+ }++ return { path: PENDING_UPLOAD_PATH, fileName: pendingUpload.fileName, consumable: true };+}++/**+ * A backup from the listing, resolved through the backup service rather than trusted: the path+ * arrives from a client, on an endpoint that needs no authentication.+ */+function existingBackup(filePath: string | undefined) {+ if (!filePath) {+ throw new ValidationError("No backup was named.");+ }++ const backup = getBackup() as ServerBackupService;+ const resolvedPath = backup.resolveBackupPath(filePath);+ if (!resolvedPath) {+ throw new NotFoundError("No such backup.");+ }++ return { path: resolvedPath, fileName: path.basename(resolvedPath), consumable: false };+}++/** Frees setup and the disk once an upload is restored, abandoned, or found to be unusable. */+function discardPendingUpload() {+ pendingUpload = null;+ fs.rmSync(PENDING_UPLOAD_PATH, { force: true });++ releaseSetupHold?.();+ releaseSetupHold = null;+}diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.tsindex 4cfa809423..38cdbe4614 100644--- a/apps/server/src/routes/route_api.ts+++ b/apps/server/src/routes/route_api.ts@@ -1,4 +1,4 @@-import { entity_changes as entityChangesService, NotFoundError, routes, utils as coreUtils, ValidationError } from "@triliumnext/core";+import { entity_changes as entityChangesService, HttpError, routes, utils as coreUtils } from "@triliumnext/core";import express, { type RequestHandler } from "express";import type { ParamsDictionary } from "express-serve-static-core";import { mkdirSync } from "fs";@@ -137,7 +137,9 @@ function handleException(e: unknown | Error, method: HttpMethod, path: string, rreturn;}- const resStatusCode = (e instanceof ValidationError || e instanceof NotFoundError) ? e.statusCode : 500;+ // Any HttpError states its own code — 400 and 404 as before, plus 403 and 409, which used to be+ // flattened into a 500 that told the client nothing about what to do differently.+ const resStatusCode = e instanceof HttpError ? e.statusCode : 500;res.status(resStatusCode).json({message: errMessagediff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 2e2f5ed64b..0db575877a 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -33,6 +33,7 @@ import ocrRoute from "./api/ocr.js";import onenoteImportRoute from "./api/onenote_import.js";import recoveryCodes from './api/recovery_codes.js';import senderRoute from "./api/sender.js";+import setupRestoreRoute from "./api/setup_restore.js";import systemInfoRoute from "./api/system_info.js";import totp from './api/totp.js';import { doubleCsrfProtection as csrfMiddleware } from "./csrf_protection.js";@@ -64,6 +65,21 @@ function register(app: express.Application) {asyncRoute(PST, "/set-password", [auth.checkAppInitialized, auth.checkPasswordNotSet], loginRoute.setPassword, null);route(GET, "/setup", [], setupRoute.setupPage);+ // Restoring a backup, which only the setup screen offers: `checkAppNotInitialized` is what keeps+ // it from ever running against a live database, since before the database exists there is no+ // session to authenticate against and the whole wizard stands unauthenticated. None of these may+ // be transactional — the swap detaches the database, which a wrapping transaction would be in the+ // middle of.+ asyncRoute(PST, "/api/setup/restore/upload/begin", [auth.checkAppNotInitialized], setupRestoreRoute.beginUpload, apiResultHandler);+ asyncRoute(PST, "/api/setup/restore/upload/:uploadId/chunk", [auth.checkAppNotInitialized], setupRestoreRoute.uploadChunk, apiResultHandler);+ asyncRoute(GET, "/api/setup/restore/upload/:uploadId", [auth.checkAppNotInitialized], setupRestoreRoute.uploadStatus, apiResultHandler);+ asyncRoute(PST, "/api/setup/restore/upload/:uploadId/finish", [auth.checkAppNotInitialized], setupRestoreRoute.finishUpload, apiResultHandler);+ asyncRoute(DEL, "/api/setup/restore/upload/:uploadId", [auth.checkAppNotInitialized], setupRestoreRoute.abortUpload, apiResultHandler);+ asyncRoute(PST, "/api/setup/restore/start", [auth.checkAppNotInitialized], setupRestoreRoute.start, apiResultHandler);+ // Readable throughout, including once the restore has succeeded: that is how the screen learns it+ // is over and the application can be opened.+ asyncRoute(GET, "/api/setup/restore/status", [], setupRestoreRoute.status, apiResultHandler);+apiRoute(GET, '/api/totp/generate', totp.generateSecret);apiRoute(PST, '/api/totp/verify', totp.verifySecret);diff --git a/apps/server/src/services/chunked_upload.spec.ts b/apps/server/src/services/chunked_upload.spec.tsnew file mode 100644index 0000000000..1c26595537--- /dev/null+++ b/apps/server/src/services/chunked_upload.spec.ts@@ -0,0 +1,270 @@+import type { Request } from "express";+import fs from "fs";+import os from "os";+import path from "path";+import { Readable } from "stream";+import { afterEach, describe, expect, it, vi } from "vitest";++import { type ChunkedUpload, type ChunkedUploadConfig, createChunkedUpload } from "./chunked_upload.js";++const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-chunked-upload-spec-"));+const opened: ChunkedUpload<unknown>[] = [];++afterEach(() => {+ opened.splice(0).forEach((upload) => upload.stop());+ fs.rmSync(tempRoot, { recursive: true, force: true });+ fs.mkdirSync(tempRoot, { recursive: true });+ vi.restoreAllMocks();+});++/** An upload whose completed files are kept, so a test can assert on what was assembled. */+function uploadService(overrides: Partial<ChunkedUploadConfig<string>> = {}) {+ const completed: { path: string; fileName: string; totalBytes: number; metadata: unknown }[] = [];+ const upload = createChunkedUpload<string>({+ name: "spec",+ directory: path.join(tempRoot, "uploads"),+ maxTotalBytes: 1024,+ chunkSize: 4,+ onComplete: async (file) => {+ completed.push({ ...file });+ return file.path;+ },+ ...overrides+ });++ opened.push(upload);+ return { upload, completed };+}++function beginRequest(totalBytes: unknown, fileName = "backup.db", metadata?: unknown) {+ return { body: { fileName, totalBytes, metadata } } as unknown as Request;+}++/** A chunk request is both a readable body and a request: `pipeline` reads it, the handler routes it. */+function chunkRequest(uploadId: string, offset: unknown, body: Buffer | Readable) {+ const stream = Buffer.isBuffer(body) ? Readable.from([ body ]) : body;++ return Object.assign(stream, {+ params: { uploadId },+ query: { offset: String(offset) }+ }) as unknown as Request;+}++function sessionRequest(uploadId: string) {+ return { params: { uploadId } } as unknown as Request;+}++/** Sends `content` in fixed-size chunks, exactly as the client does. */+async function sendAll(upload: ChunkedUpload<unknown>, uploadId: string, content: Buffer, chunkSize: number) {+ for (let offset = 0; offset < content.length; offset += chunkSize) {+ await upload.chunk(chunkRequest(uploadId, offset, content.subarray(offset, offset + chunkSize)));+ }+}++describe("chunked upload: assembling a file", () => {+ it("reassembles the chunks in order and hands the finished file to the consumer", async () => {+ const { upload, completed } = uploadService();+ const content = Buffer.from("the quick brown fox jumps over the lazy dog");++ const started = await upload.begin(beginRequest(content.length, "backup.db", { source: "web" }));+ expect(started).toMatchObject({ receivedBytes: 0, totalBytes: content.length, chunkSize: 4 });++ await sendAll(upload, started.uploadId, content, 4);++ const status = await upload.status(sessionRequest(started.uploadId));+ expect(status.receivedBytes).toBe(content.length);++ const assembledPath = await upload.finish(sessionRequest(started.uploadId));+ expect(fs.readFileSync(String(assembledPath))).toEqual(content);+ expect(completed).toEqual([+ { path: assembledPath, fileName: "backup.db", totalBytes: content.length, metadata: { source: "web" } }+ ]);+ });++ it("reports how far it has got, so a client that lost a response can carry on", async () => {+ const { upload } = uploadService();+ const content = Buffer.alloc(12, 7);++ const { uploadId } = await upload.begin(beginRequest(content.length));+ await upload.chunk(chunkRequest(uploadId, 0, content.subarray(0, 4)));++ // The response to this one never reaches the client, which asks where the file got to instead.+ await upload.chunk(chunkRequest(uploadId, 4, content.subarray(4, 8)));++ const { receivedBytes } = await upload.status(sessionRequest(uploadId));+ expect(receivedBytes).toBe(8);++ await upload.chunk(chunkRequest(uploadId, receivedBytes, content.subarray(receivedBytes)));+ const assembledPath = await upload.finish(sessionRequest(uploadId));+ expect(fs.readFileSync(String(assembledPath))).toEqual(content);+ });++ it("leaves the file to the consumer, which may move it without a copy", async () => {+ const destination = path.join(tempRoot, "moved.db");+ const { upload } = uploadService({+ onComplete: async ({ path: uploadedPath }) => {+ fs.renameSync(uploadedPath, destination);+ return destination;+ }+ });+ const content = Buffer.from("payload");++ const { uploadId } = await upload.begin(beginRequest(content.length));+ await sendAll(upload, uploadId, content, 4);+ await upload.finish(sessionRequest(uploadId));++ expect(fs.readFileSync(destination)).toEqual(content);+ // The move is not undone by the sweep that follows it.+ await upload.sweep();+ expect(fs.existsSync(destination)).toBe(true);+ });+});++describe("chunked upload: the offset rule", () => {+ it("refuses a chunk that does not continue where the file left off, and keeps what it has", async () => {+ const { upload } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(12));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4, 1)));++ // A gap, a chunk already written, and an offset that is not a number at all.+ await expect(upload.chunk(chunkRequest(uploadId, 8, Buffer.alloc(4, 2)))).rejects.toThrow(/4 bytes have been received/);+ await expect(upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4, 2)))).rejects.toThrow(/4 bytes have been received/);+ await expect(upload.chunk(chunkRequest(uploadId, "soon", Buffer.alloc(4)))).rejects.toThrow(/must be stated as an integer/);++ const { receivedBytes } = await upload.status(sessionRequest(uploadId));+ expect(receivedBytes).toBe(4);+ });++ it("drops an upload that sends more than it declared", async () => {+ const { upload } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(4));++ await expect(upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(8)))).rejects.toThrow(/more bytes than it declared/);+ await expect(upload.status(sessionRequest(uploadId))).rejects.toThrow(/No such upload/);+ });++ it("counts what reached the disk when a chunk breaks partway, and resumes from there", async () => {+ const { upload } = uploadService({ maxTotalBytes: 4096 });+ const content = Buffer.alloc(2048, 3);+ const { uploadId } = await upload.begin(beginRequest(content.length));++ const broken = new Readable({+ read() {+ this.push(content.subarray(0, 1024));+ this.destroy(new Error("connection reset"));+ }+ });+ await expect(upload.chunk(chunkRequest(uploadId, 0, broken))).rejects.toThrow("connection reset");++ // Whatever landed, the count matches the file: that is what makes the next offset the right one.+ const { receivedBytes } = await upload.status(sessionRequest(uploadId));+ expect(receivedBytes).toBe(fs.statSync(partialPath(tempRoot, uploadId)).size);++ await upload.chunk(chunkRequest(uploadId, receivedBytes, content.subarray(receivedBytes)));+ const assembledPath = await upload.finish(sessionRequest(uploadId));+ expect(fs.readFileSync(String(assembledPath))).toEqual(content);+ });+});++describe("chunked upload: starting and ending a session", () => {+ it("refuses a size that is missing, not a whole number, or above the limit", async () => {+ const { upload } = uploadService({ maxTotalBytes: 100 });++ await expect(upload.begin(beginRequest(undefined))).rejects.toThrow(/positive integer/);+ await expect(upload.begin(beginRequest(4.5))).rejects.toThrow(/positive integer/);+ await expect(upload.begin(beginRequest(0))).rejects.toThrow(/positive integer/);+ await expect(upload.begin(beginRequest(101))).rejects.toThrow(/above the limit of 100/);+ });++ it("allows only as many sessions at once as it is configured for", async () => {+ const { upload } = uploadService();+ await upload.begin(beginRequest(8));++ await expect(upload.begin(beginRequest(8))).rejects.toThrow(/already in progress/);+ });++ it("reduces the stated name to a base name, so it cannot point outside the upload directory", async () => {+ const { upload, completed } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(4, "../../etc/passwd"));++ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));+ await upload.finish(sessionRequest(uploadId));++ expect(completed[0].fileName).toBe("passwd");+ expect(path.dirname(completed[0].path)).toBe(path.join(tempRoot, "uploads", "spec"));+ });++ it("refuses to finish an upload that is not all there", async () => {+ const { upload, completed } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(8));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ await expect(upload.finish(sessionRequest(uploadId))).rejects.toThrow(/has 4 of 8 bytes/);+ expect(completed).toHaveLength(0);+ // Still open, so the client can send the rest rather than start again.+ expect((await upload.status(sessionRequest(uploadId))).receivedBytes).toBe(4);+ });++ it("removes the file when the consumer fails to take it", async () => {+ const { upload } = uploadService({+ onComplete: async () => { throw new Error("not a database"); }+ });+ const { uploadId } = await upload.begin(beginRequest(4));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ await expect(upload.finish(sessionRequest(uploadId))).rejects.toThrow("not a database");+ expect(fs.existsSync(partialPath(tempRoot, uploadId))).toBe(false);+ });++ it("forgets an aborted upload and deletes what it had received", async () => {+ const { upload } = uploadService();+ const { uploadId } = await upload.begin(beginRequest(8));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ await upload.abort(sessionRequest(uploadId));++ expect(fs.existsSync(partialPath(tempRoot, uploadId))).toBe(false);+ await expect(upload.status(sessionRequest(uploadId))).rejects.toThrow(/No such upload/);+ // The slot is free again.+ await expect(upload.begin(beginRequest(8))).resolves.toBeTruthy();+ });++ it("answers for an upload it has never heard of", async () => {+ const { upload } = uploadService();++ await expect(upload.status(sessionRequest("nosuchupload"))).rejects.toThrow(/No such upload/);+ });+});++describe("chunked upload: sweeping", () => {+ it("drops a session that has gone quiet for too long, and frees its slot", async () => {+ const { upload } = uploadService({ sessionTtlMs: 1 });+ const { uploadId } = await upload.begin(beginRequest(8));+ await upload.chunk(chunkRequest(uploadId, 0, Buffer.alloc(4)));++ await new Promise((resolve) => setTimeout(resolve, 5));+ await upload.sweep();++ expect(fs.existsSync(partialPath(tempRoot, uploadId))).toBe(false);+ await expect(upload.chunk(chunkRequest(uploadId, 4, Buffer.alloc(4)))).rejects.toThrow(/No such upload/);+ await expect(upload.begin(beginRequest(8))).resolves.toBeTruthy();+ });++ it("deletes a partial file no session claims, which after a restart is every one of them", async () => {+ const { upload } = uploadService();+ const directory = path.join(tempRoot, "uploads", "spec");+ fs.mkdirSync(directory, { recursive: true });+ fs.writeFileSync(path.join(directory, "abandoned.part"), "left behind");++ const { uploadId } = await upload.begin(beginRequest(8));+ await upload.sweep();++ expect(fs.existsSync(path.join(directory, "abandoned.part"))).toBe(false);+ // The live session is not swept along with it.+ expect(fs.existsSync(partialPath(tempRoot, uploadId))).toBe(true);+ });+});++function partialPath(root: string, uploadId: string) {+ return path.join(root, "uploads", "spec", `${uploadId}.part`);+}diff --git a/apps/server/src/services/chunked_upload.ts b/apps/server/src/services/chunked_upload.tsnew file mode 100644index 0000000000..c68d560fbd--- /dev/null+++ b/apps/server/src/services/chunked_upload.ts@@ -0,0 +1,343 @@+import { ConflictError, NotFoundError, utils as coreUtils, ValidationError } from "@triliumnext/core";+import { Mutex } from "async-mutex";+import type { Request } from "express";+import { createWriteStream } from "fs";+import fsp from "fs/promises";+import path from "path";+import { pipeline } from "stream/promises";++/**+ * Receives a large file as a sequence of appended chunks, so that an upload measured in gigabytes+ * survives what a single request would not: a proxy's body limit, a request timeout, a dropped+ * connection, and a progress bar that has nothing to report until the very end.+ *+ * The protocol is one rule: a chunk states the offset it belongs at, and that offset must equal how+ * much the server has already received. Sparse writes, duplicated chunks and two clients writing to+ * one session all fail that check, and a client that lost a response only has to ask where the file+ * got to and carry on from there.+ *+ * Nothing here knows what the file is for. A consumer supplies {@link ChunkedUploadConfig.onComplete},+ * which is handed the assembled file and takes ownership of it.+ *+ * @example Mounting an upload endpoint+ * ```ts+ * const upload = createChunkedUpload({+ * name: "restore",+ * directory: path.join(dataDirs.TMP_DIR, "uploads"),+ * maxTotalBytes: 64 * 1024 * 1024 * 1024,+ * onComplete: async ({ path: uploadedPath }) => restoreService.stage(uploadedPath)+ * });+ *+ * asyncRoute(PST, "/api/setup/restore/upload/begin", [guard], upload.begin, apiResultHandler);+ * ```+ *+ * @module+ */++/** Chunk size advertised to clients, chosen to stay under the body limit of a typical reverse proxy. */+export const DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024;++const DEFAULT_SESSION_TTL_MS = 60 * 60 * 1000;+const SWEEP_INTERVAL_MS = 5 * 60 * 1000;++/** The assembled file, handed to the consumer once every byte is in. */+export interface CompletedUpload {+ /**+ * Where the file is. The consumer **takes ownership**: it may rename the file into place, read+ * it, or delete it, and the upload no longer tracks it. Renaming within the same filesystem is+ * what keeps a multi-gigabyte upload from being copied a second time.+ */+ path: string;+ /** The name the client gave the file, reduced to a base name. */+ fileName: string;+ totalBytes: number;+ /** Whatever the client sent to `begin`, passed through untouched. */+ metadata: Record<string, unknown>;+}++export interface ChunkedUploadConfig<T> {+ /** Identifies this upload's files and log lines; also its subdirectory. */+ name: string;+ /** Where partial uploads are kept. Created if missing. */+ directory: string;+ /** Refuses anything larger, before a byte is written. */+ maxTotalBytes: number;+ /** Advertised to the client by `begin`; defaults to {@link DEFAULT_CHUNK_SIZE}. */+ chunkSize?: number;+ /** How long a session survives without activity. Defaults to an hour. */+ sessionTtlMs?: number;+ /** Sessions that may be open at once. Defaults to one. */+ maxConcurrentSessions?: number;+ /**+ * Checks the filesystem has room for the whole file before accepting it, so an upload that+ * cannot possibly fit fails at the start rather than after hours.+ */+ requireFreeSpace?: boolean;+ /** Called once the file is complete. See {@link CompletedUpload} on ownership. */+ onComplete(upload: CompletedUpload): Promise<T>;+}++/** What a client is told about a session, whether it is starting one or resuming one. */+export interface ChunkedUploadStatus {+ uploadId: string;+ fileName: string;+ totalBytes: number;+ receivedBytes: number;+ /** Size of the chunks the client should send. */+ chunkSize: number;+ /** When the session is dropped if nothing more arrives, as a Unix timestamp in milliseconds. */+ expiresAt: number;+}++export interface ChunkedUpload<T> {+ begin(req: Request): Promise<ChunkedUploadStatus>;+ chunk(req: Request): Promise<ChunkedUploadStatus>;+ status(req: Request): Promise<ChunkedUploadStatus>;+ finish(req: Request): Promise<T>;+ abort(req: Request): Promise<void>;+ /** Drops expired sessions and any partial file left behind by an earlier run. */+ sweep(): Promise<void>;+ /** Stops the sweep timer. For tests, and for a shutdown that wants to be tidy. */+ stop(): void;+}++/**+ * Builds a set of request handlers implementing the chunked upload protocol.+ *+ * The handlers are plain route handlers returning their result, so they slot into `asyncRoute` with+ * `apiResultHandler` like any other endpoint. Failures are thrown as {@link HttpError} subclasses,+ * which the route layer turns into the matching status code.+ */+export function createChunkedUpload<T>(config: ChunkedUploadConfig<T>): ChunkedUpload<T> {+ const chunkSize = config.chunkSize ?? DEFAULT_CHUNK_SIZE;+ const sessionTtlMs = config.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;+ const maxConcurrentSessions = config.maxConcurrentSessions ?? 1;+ const directory = path.resolve(config.directory, config.name);+ const sessions = new Map<string, Session>();++ // Unreferenced so neither a test nor a shutdown waits on it.+ const timer = setInterval(() => void sweep(), SWEEP_INTERVAL_MS);+ timer.unref?.();++ async function begin(req: Request): Promise<ChunkedUploadStatus> {+ const { fileName, totalBytes, metadata } = (req.body ?? {}) as BeginBody;++ // Before the count is checked, so an abandoned session never blocks the next one.+ await sweep();++ if (sessions.size >= maxConcurrentSessions) {+ throw new ConflictError("Another upload is already in progress.");+ }+ if (typeof totalBytes !== "number" || !Number.isSafeInteger(totalBytes) || totalBytes <= 0) {+ throw new ValidationError("The size of the upload must be stated as a positive integer.");+ }+ if (totalBytes > config.maxTotalBytes) {+ throw new ValidationError(+ `The upload is ${totalBytes} bytes, above the limit of ${config.maxTotalBytes}.`+ );+ }+ if (config.requireFreeSpace) {+ await requireRoomFor(directory, totalBytes);+ }++ await fsp.mkdir(directory, { recursive: true });++ const uploadId = coreUtils.randomString(20);+ const session: Session = {+ uploadId,+ // A base name, so a crafted name cannot reach outside the upload directory. Only ever+ // handed back to the consumer; the file on disk is named after the session.+ fileName: path.basename(String(fileName ?? "upload")),+ totalBytes,+ receivedBytes: 0,+ metadata: (metadata ?? {}) as Record<string, unknown>,+ path: path.join(directory, `${uploadId}.part`),+ expiresAt: Date.now() + sessionTtlMs,+ writing: new Mutex()+ };++ // Truncates any file left at this path, so a session always starts from nothing.+ await fsp.writeFile(session.path, "");+ sessions.set(uploadId, session);++ return describe(session);+ }++ /**+ * Appends one chunk. The request body is streamed straight to the file: buffering it would put a+ * chunk of every concurrent upload in memory, which is the thing this protocol exists to avoid.+ */+ async function chunk(req: Request): Promise<ChunkedUploadStatus> {+ const session = sessionFor(req);+ const offset = Number(req.query.offset);++ return session.writing.runExclusive(async () => {+ if (!Number.isSafeInteger(offset) || offset < 0) {+ throw new ValidationError("The offset of a chunk must be stated as an integer.");+ }+ if (offset !== session.receivedBytes) {+ throw new ConflictError(+ `Chunk starts at ${offset}, but ${session.receivedBytes} bytes have been received.`+ );+ }++ const destination = createWriteStream(session.path, { flags: "a" });+ try {+ await pipeline(req, destination);+ } finally {+ // Whether the chunk arrived whole or the connection dropped partway, what counts is+ // what reached the disk. Reading it back is what lets a broken chunk be resumed from+ // the exact byte it stopped at rather than being re-sent or, worse, double-written.+ session.receivedBytes = (await fsp.stat(session.path)).size;+ session.expiresAt = Date.now() + sessionTtlMs;+ }++ if (session.receivedBytes > session.totalBytes) {+ await drop(session);+ throw new ValidationError("The upload sent more bytes than it declared.");+ }++ return describe(session);+ });+ }++ async function status(req: Request): Promise<ChunkedUploadStatus> {+ return describe(sessionFor(req));+ }++ async function finish(req: Request): Promise<T> {+ const session = sessionFor(req);++ return session.writing.runExclusive(async () => {+ if (session.receivedBytes !== session.totalBytes) {+ throw new ConflictError(+ `The upload has ${session.receivedBytes} of ${session.totalBytes} bytes.`+ );+ }++ // Ownership passes with the call, so the session goes first: the consumer is free to+ // rename the file, and a sweep must not delete what is no longer ours.+ sessions.delete(session.uploadId);++ try {+ return await config.onComplete({+ path: session.path,+ fileName: session.fileName,+ totalBytes: session.totalBytes,+ metadata: session.metadata+ });+ } catch (e) {+ // The consumer may have taken the file or may have failed before touching it; either+ // way nothing else will come back for it.+ await fsp.rm(session.path, { force: true }).catch(() => {});+ throw e;+ }+ });+ }++ async function abort(req: Request): Promise<void> {+ await drop(sessionFor(req));+ }++ /**+ * Drops what has expired, then anything in the directory no live session claims — which after a+ * restart is everything, since sessions live only in memory while their files do not.+ */+ async function sweep(): Promise<void> {+ const now = Date.now();+ for (const session of [...sessions.values()]) {+ if (session.expiresAt <= now) {+ await drop(session);+ }+ }++ let fileNames: string[];+ try {+ fileNames = await fsp.readdir(directory);+ } catch {+ return;+ }++ const live = new Set([...sessions.values()].map((session) => session.path));+ for (const fileName of fileNames) {+ const filePath = path.join(directory, fileName);+ if (!live.has(filePath)) {+ await fsp.rm(filePath, { force: true }).catch(() => {});+ }+ }+ }++ function sessionFor(req: Request): Session {+ const session = sessions.get(String(req.params.uploadId));+ if (!session) {+ throw new NotFoundError("No such upload. It may have expired.");+ }+ return session;+ }++ async function drop(session: Session): Promise<void> {+ sessions.delete(session.uploadId);+ await fsp.rm(session.path, { force: true }).catch(() => {});+ }++ function describe(session: Session): ChunkedUploadStatus {+ return {+ uploadId: session.uploadId,+ fileName: session.fileName,+ totalBytes: session.totalBytes,+ receivedBytes: session.receivedBytes,+ chunkSize,+ expiresAt: session.expiresAt+ };+ }++ return {+ begin,+ chunk,+ status,+ finish,+ abort,+ sweep,+ stop: () => clearInterval(timer)+ };+}++interface Session {+ uploadId: string;+ fileName: string;+ totalBytes: number;+ receivedBytes: number;+ metadata: Record<string, unknown>;+ path: string;+ expiresAt: number;+ /** Serialises writes, so the offset a chunk is checked against is the one it is written at. */+ writing: Mutex;+}++interface BeginBody {+ fileName?: string;+ totalBytes?: number;+ metadata?: Record<string, unknown>;+}++/**+ * Refuses an upload the filesystem cannot hold, which is worth knowing at the start of an hour-long+ * transfer rather than at the end of one. A filesystem that cannot be measured is taken as roomy:+ * the check is there to give a clear answer, not to become a new way to fail.+ */+async function requireRoomFor(directory: string, totalBytes: number): Promise<void> {+ let available: number;+ try {+ const parent = path.dirname(directory);+ const stats = await fsp.statfs(parent);+ available = stats.bavail * stats.bsize;+ } catch {+ return;+ }++ if (available < totalBytes) {+ throw new ValidationError(+ `The upload needs ${totalBytes} bytes and only ${available} are free.`+ );+ }+}diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.tsnew file mode 100644index 0000000000..cde77dba83--- /dev/null+++ b/apps/server/src/services/database_restore.spec.ts@@ -0,0 +1,261 @@+import { writeBackupContainer } from "@triliumnext/backup-container";+import { app_info as appInfo, getSql } from "@triliumnext/core";+import Database from "better-sqlite3";+import fs from "fs";+import fsp from "fs/promises";+import os from "os";+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ exchangeDatabaseFiles,+ getRestoreProgress,+ readBackupFormat,+ restoreDatabase,+ RestoreFailure,+ stageBackup+} from "./database_restore.js";++const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-restore-spec-"));+let counter = 0;++beforeEach(() => {+ fs.rmSync(tempRoot, { recursive: true, force: true });+ fs.mkdirSync(tempRoot, { recursive: true });+});++afterEach(() => vi.restoreAllMocks());++/** A database that would pass validation, so a test can tell a rejected file from a rejected step. */+function validDatabase(name = `db-${counter++}.db`) {+ const filePath = path.join(tempRoot, name);+ const db = new Database(filePath);+ try {+ for (const table of [ "options", "notes", "branches", "blobs" ]) {+ db.exec(`CREATE TABLE ${table} (name TEXT, value TEXT)`);+ }+ const insert = db.prepare("INSERT INTO options (name, value) VALUES (?, ?)");+ insert.run("initialized", "true");+ insert.run("dbVersion", String(appInfo.dbVersion));+ } finally {+ db.close();+ }++ return filePath;+}++/** Wraps `source` the way a backup does, with the same writer the backup service uses. */+async function containerOf(source: string, passphrase?: string, compress = false) {+ const filePath = path.join(tempRoot, `backup-${counter++}.tnbackup`);++ await writeBackupContainer(fs.createReadStream(source), fs.createWriteStream(filePath), {+ compress,+ passphrase,+ plaintextSize: fs.statSync(source).size,+ patchHeader: async (offset, data) => {+ const handle = await fsp.open(filePath, "r+");+ try {+ await handle.write(data, 0, data.length, offset);+ } finally {+ await handle.close();+ }+ }+ });++ return filePath;+}++function fileWith(content: string, name = `file-${counter++}.bin`) {+ const filePath = path.join(tempRoot, name);+ fs.writeFileSync(filePath, content);++ return filePath;+}++describe("reading what a backup file is", () => {+ it("tells a container from a plain database, going by the header rather than the name", async () => {+ const database = validDatabase("looks-like-a-backup.tnbackup");+ expect(readBackupFormat(database)).toEqual({ container: false, encrypted: false });++ const plain = await containerOf(validDatabase());+ expect(readBackupFormat(plain)).toEqual({ container: true, encrypted: false });++ const encrypted = await containerOf(validDatabase(), "hunter2");+ expect(readBackupFormat(encrypted)).toEqual({ container: true, encrypted: true });+ });++ it("answers for a file it cannot read at all", () => {+ expect(readBackupFormat(path.join(tempRoot, "not-here.db"))).toBe(null);+ expect(readBackupFormat(fileWith("short"))).toEqual({ container: false, encrypted: false });+ });+});++describe("staging a backup", () => {+ it("takes an uploaded database where it lies rather than copying gigabytes for no reason", async () => {+ const uploaded = validDatabase();++ const candidate = await stageBackup({ path: uploaded, fileName: "backup.db", consumable: true });++ expect(candidate).toBe(uploaded);+ });++ it("copies a backup that has to stay where it is, leaving the original untouched", async () => {+ const existing = validDatabase();++ const candidate = await stageBackup({ path: existing, fileName: "backup.db", consumable: false });++ expect(candidate).not.toBe(existing);+ expect(fs.existsSync(existing)).toBe(true);+ expect(fs.readFileSync(candidate)).toEqual(fs.readFileSync(existing));+ });++ it("unwraps a container back into the database it was made from", async () => {+ const source = validDatabase();+ const backup = await containerOf(source, undefined, true);++ const candidate = await stageBackup({ path: backup, fileName: "backup.tnbackup", consumable: true });++ expect(fs.readFileSync(candidate)).toEqual(fs.readFileSync(source));+ // Consumable: the container has served its purpose and the unwrapped copy is what matters now.+ expect(fs.existsSync(backup)).toBe(false);+ });++ it("asks for a passphrase before reading an encrypted container, not after", async () => {+ const backup = await containerOf(validDatabase(), "hunter2");+ const readStream = vi.spyOn(fs, "createReadStream");++ await expect(stageBackup({ path: backup, fileName: "backup.tnbackup", consumable: false }))+ .rejects.toMatchObject({ reason: "passphrase-required" });++ expect(readStream).not.toHaveBeenCalled();+ // Nothing was consumed, so the same file can be tried again once the passphrase is known.+ expect(fs.existsSync(backup)).toBe(true);+ });++ it("tells a wrong passphrase apart from a file that is damaged beyond it", async () => {+ const backup = await containerOf(validDatabase(), "hunter2");++ await expect(stageBackup({ path: backup, fileName: "b.tnbackup", consumable: true, passphrase: "wrong" }))+ .rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });++ // Kept, because another passphrase is exactly what could still make it work.+ expect(fs.existsSync(backup)).toBe(true);+ });++ it("refuses a file it cannot even open", async () => {+ await expect(stageBackup({ path: path.join(tempRoot, "gone.db"), fileName: "gone.db", consumable: false }))+ .rejects.toMatchObject({ reason: "not-a-database" });+ });+});++describe("exchanging the database files", () => {+ it("puts the candidate in place, keeps the old database aside, and drops its sidecars", () => {+ const document = path.join(tempRoot, "document.db");+ fs.writeFileSync(document, "the old database");+ fs.writeFileSync(`${document}-wal`, "old write-ahead log");+ fs.writeFileSync(`${document}-shm`, "old shared memory");+ const candidate = fileWith("the restored database");++ exchangeDatabaseFiles(candidate, document);++ expect(fs.readFileSync(document, "utf-8")).toBe("the restored database");+ expect(fs.readFileSync(`${document}.pre-restore`, "utf-8")).toBe("the old database");+ expect(fs.existsSync(`${document}-wal`)).toBe(false);+ expect(fs.existsSync(`${document}-shm`)).toBe(false);+ expect(fs.existsSync(candidate)).toBe(false);+ });++ it("works where there is no database yet, which is the usual case during setup", () => {+ const document = path.join(tempRoot, "document.db");++ exchangeDatabaseFiles(fileWith("the restored database"), document);++ expect(fs.readFileSync(document, "utf-8")).toBe("the restored database");+ expect(fs.existsSync(`${document}.pre-restore`)).toBe(false);+ });++ it("replaces what an earlier restore had set aside rather than refusing to start", () => {+ const document = path.join(tempRoot, "document.db");+ fs.writeFileSync(document, "the current database");+ fs.writeFileSync(`${document}.pre-restore`, "from an earlier attempt");++ exchangeDatabaseFiles(fileWith("the restored database"), document);++ expect(fs.readFileSync(`${document}.pre-restore`, "utf-8")).toBe("the current database");+ });+});++describe("recovering from an interrupted restore", () => {+ /** Imported lazily so the default path is bound per call rather than at module load. */+ async function recover(document: string) {+ const { recoverInterruptedRestore } = await import("./database_restore.js");+ vi.spyOn(console, "info").mockImplementation(() => {});+ recoverInterruptedRestore(document);+ }++ it("does nothing when no restore was under way", async () => {+ const document = path.join(tempRoot, "document.db");+ fs.writeFileSync(document, "the database");++ await recover(document);++ expect(fs.readFileSync(document, "utf-8")).toBe("the database");+ });++ it("puts the previous database back when one was set aside", async () => {+ const document = path.join(tempRoot, "document.db");+ fs.writeFileSync(document, "half a restored database");+ fs.writeFileSync(`${document}-wal`, "a log belonging to neither");+ fs.writeFileSync(`${document}.pre-restore`, "the database it had");+ fs.writeFileSync(`${document}.restore-in-progress`, "");++ await recover(document);++ expect(fs.readFileSync(document, "utf-8")).toBe("the database it had");+ expect(fs.existsSync(`${document}-wal`)).toBe(false);+ expect(fs.existsSync(`${document}.pre-restore`)).toBe(false);+ expect(fs.existsSync(`${document}.restore-in-progress`)).toBe(false);+ });++ it("keeps the database in place when nothing was set aside, and clears the marker", async () => {+ const document = path.join(tempRoot, "document.db");+ fs.writeFileSync(document, "a whole database");+ fs.writeFileSync(`${document}.restore-in-progress`, "");++ await recover(document);++ expect(fs.readFileSync(document, "utf-8")).toBe("a whole database");+ expect(fs.existsSync(`${document}.restore-in-progress`)).toBe(false);+ });+});++describe("restoring a database", () => {+ it("stops before touching the live database when the backup is not one", async () => {+ const detach = vi.spyOn(getSql(), "detachConnection").mockImplementation(() => {});++ await expect(restoreDatabase({+ path: fileWith("a photograph, renamed"),+ fileName: "holiday.db",+ consumable: false+ })).rejects.toBeInstanceOf(RestoreFailure);++ expect(detach).not.toHaveBeenCalled();+ expect(getRestoreProgress()).toMatchObject({+ stage: "failed", fileName: "holiday.db", reason: "not-a-database"+ });+ });++ it("stops before touching the live database when the backup is from a newer version", async () => {+ const detach = vi.spyOn(getSql(), "detachConnection").mockImplementation(() => {});+ const database = validDatabase();+ const db = new Database(database);+ db.prepare("UPDATE options SET value = ? WHERE name = 'dbVersion'").run(String(appInfo.dbVersion + 1));+ db.close();++ await expect(restoreDatabase({ path: database, fileName: "newer.db", consumable: false }))+ .rejects.toMatchObject({ reason: "database-too-new" });++ expect(detach).not.toHaveBeenCalled();+ expect(getRestoreProgress()).toMatchObject({ stage: "failed", reason: "database-too-new" });+ });+});diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsnew file mode 100644index 0000000000..74f7fa5e6d--- /dev/null+++ b/apps/server/src/services/database_restore.ts@@ -0,0 +1,428 @@+import {+ type BackupContainerErrorReason,+ FIXED_HEADER_BYTES,+ isBackupContainerError,+ peekBackupContainer,+ readBackupContainer+} from "@triliumnext/backup-container";+import { cls, events as eventService, getLog, getSql, sql_init as sqlInit } from "@triliumnext/core";+import fs from "fs";+import path from "path";++import config from "./config.js";+import dataDir from "./data_dir.js";+import { type DatabaseRejection, validateDatabaseFile } from "./database_validation.js";++/**+ * Puts a backup in place of this instance's database.+ *+ * The database is open before the restore starts and has to be open after it, so the file cannot+ * simply be written over: the connection is detached, the file is exchanged, and a new connection is+ * attached to what is now there. On Windows that order is not a preference — an open handle prevents+ * the file from being renamed at all.+ *+ * Everything that can be checked is checked before the exchange, on a copy nothing is attached to,+ * because the alternative is finding out afterwards: the migration is what would otherwise notice an+ * unusable database, and a migration that cannot proceed ends the process outright.+ *+ * The database being replaced is kept aside until the restored one has migrated and opened. Until+ * then a marker sits next to it, so an interruption in the middle — a power cut, a killed process —+ * is recognised at the next start and undone, rather than leaving an instance that cannot open its+ * own document.+ *+ * Only ever run during setup, where nothing else holds the database: the share connection is opened+ * on `dbReady`, which has not resolved, and sessions are not persisted until the database is+ * initialized.+ *+ * @module+ */++/** What the restore is doing, in the order it does it. */+export type RestoreStage =+ /** Getting the backup into a plain database file: unwrapping a container, or taking the upload. */+ | "staging"+ /** Reading that file to see whether it can be this instance's database. */+ | "validating"+ /** Detaching, exchanging the files, and attaching again. Over in moments. */+ | "swapping"+ /** Opening the restored database, which for an older one includes migrating it. */+ | "migrating"+ | "done"+ | "failed";++/** Why a restore stopped, in terms the setup screen turns into something the user can act on. */+export type RestoreFailureReason =+ | DatabaseRejection+ | BackupContainerErrorReason+ /** The files could not be exchanged; the original database is back in place. */+ | "swap-failed"+ /** The restored database is in place but would not open. */+ | "migration-failed";++export interface RestoreProgress {+ stage: RestoreStage;+ /** The name of the backup being restored, so a reloaded page can say what is going on. */+ fileName: string;+ /** Set when `stage` is `failed`. */+ error?: string;+ /** Set when `stage` is `failed`. */+ reason?: RestoreFailureReason;+}++export interface RestoreRequest {+ /** Where the backup is now. */+ path: string;+ /** What to call it when reporting on it. */+ fileName: string;+ /**+ * Whether the restore may take the file rather than copy it. True for an upload's temporary file,+ * whose only purpose is this; false for a backup in the backup directory, which must survive.+ */+ consumable: boolean;+ /** Required for an encrypted backup. */+ passphrase?: string;+}++let progress: RestoreProgress | null = null;++/** How the running or last restore is getting on, or `null` if none has been started. */+export function getRestoreProgress(): RestoreProgress | null {+ return progress;+}++/**+ * Restores `request` over this instance's database, reporting its way through+ * {@link getRestoreProgress}.+ *+ * Callers hold the setup lock for the whole call: a second setup operation starting midway through+ * would build a database over the one being restored, and neither would report anything wrong.+ *+ * @throws RestoreFailure carrying the reason, which is also left in the progress for the client that+ * is polling rather than waiting.+ */+export async function restoreDatabase(request: RestoreRequest): Promise<void> {+ const log = getLog();+ log.info(`Restoring the database from a backup (${request.fileName}).`);+ progress = { stage: "staging", fileName: request.fileName };++ try {+ // The whole restore runs in one execution context: what follows the swap writes to the+ // database, and the request that started this is long since answered.+ await cls.init(async () => {+ const candidate = await stageBackup(request);++ report("validating");+ const validation = validateDatabaseFile(candidate);+ if (!validation.valid) {+ throw new RestoreFailure(validation.rejection, validation.message);+ }++ report("swapping");+ swapInDatabase(candidate);++ report("migrating");+ await openRestoredDatabase();+ });++ report("done");+ log.info("The database was restored.");+ } catch (e) {+ const failure = asFailure(e);+ progress = {+ stage: "failed",+ fileName: request.fileName,+ error: failure.message,+ reason: failure.reason+ };+ log.error(`The database could not be restored (${failure.reason}): ${failure.message}`);++ throw failure;+ } finally {+ // Whatever happened, the temporary files are of no further use.+ fs.rmSync(stagingDirectory(), { recursive: true, force: true });+ }+}++/**+ * Undoes a restore that was interrupted between the database being moved aside and the restored one+ * opening.+ *+ * Runs at startup, before the database is opened, and before core is initialized — so it says what it+ * did through the console rather than the log, which does not exist yet.+ */+export function recoverInterruptedRestore(document: string = dataDir.DOCUMENT_PATH): void {+ if (!fs.existsSync(markerFor(document))) {+ return;+ }++ const setAside = setAsideFor(document);+ if (fs.existsSync(setAside)) {+ console.info("A restore was interrupted; putting the previous database back.");+ removeDatabaseFiles(document);+ fs.renameSync(setAside, document);+ } else {+ // Nothing was set aside, so either the exchange had not started or it had finished: the+ // database in place is the one to open either way.+ console.info("A restore was interrupted; the database in place is intact.");+ }++ fs.rmSync(markerFor(document), { force: true });+}++/**+ * Moves `document` aside and puts `candidate` in its place, which is the whole of the exchange as far+ * as the filesystem is concerned.+ *+ * Separate from the detaching and attaching around it so that what happens to the files can be+ * exercised on its own, and so the order is stated in one place: aside first, sidecars after it,+ * candidate last.+ */+export function exchangeDatabaseFiles(candidate: string, document: string): void {+ const setAside = setAsideFor(document);++ fs.rmSync(setAside, { force: true });+ if (fs.existsSync(document)) {+ fs.renameSync(document, setAside);+ }++ // The sidecars belong to the database that was just moved away; left behind, SQLite would read+ // them as this one's.+ removeSidecars(document);++ moveInto(candidate, document);+}++/** A failure with a reason attached, so the setup screen can tell the cases apart. */+export class RestoreFailure extends Error {+ constructor(readonly reason: RestoreFailureReason, message: string) {+ super(message);+ this.name = "RestoreFailure";+ }+}++/** What a backup file is, read from its header rather than from what it is called. */+export interface BackupFormat {+ /** Whether it is a container rather than a plain copy of a database. */+ container: boolean;+ /** Whether a passphrase is needed to unwrap it. */+ encrypted: boolean;+}++/**+ * Identifies a backup file from its first few dozen bytes, which is where a container states what it+ * is, in the clear and without the passphrase.+ *+ * Goes by the header rather than the extension: a container renamed to `.db` is still a container,+ * and a database renamed to `.tnbackup` is still a database.+ *+ * @returns what the file is, or `null` when it cannot be read at all.+ */+export function readBackupFormat(filePath: string): BackupFormat | null {+ const head = Buffer.alloc(FIXED_HEADER_BYTES);+ let descriptor: number | undefined;++ try {+ descriptor = fs.openSync(filePath, "r");+ fs.readSync(descriptor, head, 0, head.length, 0);+ } catch {+ return null;+ } finally {+ if (descriptor !== undefined) {+ fs.closeSync(descriptor);+ }+ }++ const container = peekBackupContainer(head);++ return { container: !!container, encrypted: container?.encrypted ?? false };+}++/**+ * Produces the plain database file the rest of the restore works on.+ *+ * An uploaded database is used where it lies: it exists only to be restored, and copying it would+ * mean writing gigabytes a second time to no purpose. A container is unwrapped, and a backup from the+ * backup directory is copied, since that one has to stay where it is.+ */+export async function stageBackup(request: RestoreRequest): Promise<string> {+ const format = readBackupFormat(request.path);+ if (!format) {+ throw new RestoreFailure("not-a-database", "The backup could not be read.");+ }++ if (!format.container) {+ if (request.consumable) {+ return request.path;+ }++ const candidate = freshCandidatePath();+ await fs.promises.copyFile(request.path, candidate);+ return candidate;+ }++ // Asked before the file is read rather than after: an encrypted container without a passphrase+ // fails the same way either way, but only one of them takes minutes to get there.+ if (format.encrypted && !request.passphrase) {+ throw new RestoreFailure("passphrase-required", "The backup is encrypted.");+ }++ const candidate = freshCandidatePath();+ await readBackupContainer(+ fs.createReadStream(request.path),+ fs.createWriteStream(candidate),+ { passphrase: request.passphrase }+ );++ if (request.consumable) {+ await fs.promises.rm(request.path, { force: true });+ }++ return candidate;+}++/**+ * Exchanges the database file for `candidate`, leaving the old one aside under a marker until the+ * restored one has opened.+ *+ * Detaching, moving and attaching are one step as far as anything outside is concerned: either the+ * instance ends up on the restored database or back on the one it had.+ */+function swapInDatabase(candidate: string): void {+ const document = dataDir.DOCUMENT_PATH;++ // Written before anything moves: from here until the restored database opens, an interruption+ // leaves files that only this marker explains.+ fs.writeFileSync(markerFor(document), "");+ getSql().detachConnection();++ try {+ exchangeDatabaseFiles(candidate, document);+ getSql().attachFromFile(document, config.General.readOnly);+ } catch (e) {+ putBack(setAsideFor(document), document);+ attachQuietly(document);++ throw new RestoreFailure("swap-failed", messageOf(e));+ }+}++/**+ * Brings the restored database up: migrates it where it is older than this version, opens it, and+ * announces it, which is what starts everything that waits on a database being there.+ *+ * Announced here rather than through `setDbAsInitialized`, which does nothing when the database says+ * it is already initialized — and a restored one does, since it was initialized before it was backed+ * up. Mirrors what the "create new document" path does for the same reason.+ */+async function openRestoredDatabase(): Promise<void> {+ const document = dataDir.DOCUMENT_PATH;++ try {+ await sqlInit.initDbConnection();+ } catch (e) {+ putBack(setAsideFor(document), document);+ attachQuietly(document);++ throw new RestoreFailure("migration-failed", messageOf(e));+ }++ eventService.emit(eventService.DB_INITIALIZED);++ // The restore is over, so neither the previous database nor the marker has anything left to say.+ fs.rmSync(setAsideFor(document), { force: true });+ fs.rmSync(markerFor(document), { force: true });+}++/** Where the database being replaced waits until the restored one has opened. */+function setAsideFor(document: string): string {+ return `${document}.pre-restore`;+}++/** Says that an exchange is under way, for a start that finds the pieces of an interrupted one. */+function markerFor(document: string): string {+ return `${document}.restore-in-progress`;+}++function report(stage: RestoreStage): void {+ if (progress) {+ progress = { ...progress, stage };+ }+}++function stagingDirectory(): string {+ return path.join(dataDir.TMP_DIR, "restore");+}++function freshCandidatePath(): string {+ const directory = stagingDirectory();+ fs.mkdirSync(directory, { recursive: true });++ return path.join(directory, "candidate.db");+}++/**+ * Moves a file to where it is wanted, falling back to a copy across filesystem boundaries — which is+ * where a relocated temporary directory can put it.+ */+function moveInto(source: string, destination: string): void {+ try {+ fs.renameSync(source, destination);+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== "EXDEV") {+ throw e;+ }++ fs.copyFileSync(source, destination);+ fs.rmSync(source, { force: true });+ }+}++/** Puts the database that was set aside back, for a restore that got no further. */+function putBack(setAside: string, document: string): void {+ if (!fs.existsSync(setAside)) {+ return;+ }++ try {+ removeDatabaseFiles(document);+ fs.renameSync(setAside, document);+ } catch (e) {+ // Nothing else can be done from here, and the marker is still in place: the next start+ // finds it and puts the database back before anything opens it.+ getLog().error(`The previous database could not be put back: ${messageOf(e)}`);+ }+}++/** Re-attaches after a rollback. A failure here is reported, not raised: the caller is already failing. */+function attachQuietly(document: string): void {+ try {+ getSql().attachFromFile(document, config.General.readOnly);+ } catch (e) {+ getLog().error(`The database could not be re-opened after a failed restore: ${messageOf(e)}`);+ }+}++function removeDatabaseFiles(document: string): void {+ fs.rmSync(document, { force: true });+ removeSidecars(document);+}++function removeSidecars(document: string): void {+ fs.rmSync(`${document}-wal`, { force: true });+ fs.rmSync(`${document}-shm`, { force: true });+}++function asFailure(e: unknown): RestoreFailure {+ if (e instanceof RestoreFailure) {+ return e;+ }+ if (isBackupContainerError(e)) {+ return new RestoreFailure(e.reason, e.message);+ }++ return new RestoreFailure("swap-failed", messageOf(e));+}++function messageOf(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}diff --git a/apps/server/src/services/database_validation.spec.ts b/apps/server/src/services/database_validation.spec.tsnew file mode 100644index 0000000000..96e33fc619--- /dev/null+++ b/apps/server/src/services/database_validation.spec.ts@@ -0,0 +1,129 @@+import { app_info as appInfo } 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";++const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-db-validation-spec-"));+let counter = 0;++afterAll(() => fs.rmSync(tempRoot, { recursive: true, force: true }));++/** A database with the tables and options a Trilium document has, and nothing else. */+function triliumDatabase(options: Record<string, string>, tables = [ "options", "notes", "branches", "blobs" ]) {+ return databaseWith((db) => {+ for (const table of tables) {+ db.exec(`CREATE TABLE ${table} (name TEXT, value TEXT)`);+ }+ if (tables.includes("options")) {+ const insert = db.prepare("INSERT INTO options (name, value) VALUES (?, ?)");+ for (const [ name, value ] of Object.entries(options)) {+ insert.run(name, value);+ }+ }+ });+}++function databaseWith(build: (db: Database.Database) => void) {+ const filePath = path.join(tempRoot, `case-${counter++}.db`);+ const db = new Database(filePath);+ try {+ build(db);+ } finally {+ db.close();+ }++ return filePath;+}++function fileWith(content: Buffer | string) {+ const filePath = path.join(tempRoot, `case-${counter++}.bin`);+ fs.writeFileSync(filePath, content);++ return filePath;+}++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", () => {+ expect(validateDatabaseFile(triliumDatabase(CURRENT))).toEqual({+ valid: true, dbVersion: appInfo.dbVersion, needsMigration: false+ });++ const older = triliumDatabase({ initialized: "true", dbVersion: String(OLDEST_SUPPORTED_DB_VERSION) });+ expect(validateDatabaseFile(older)).toEqual({+ valid: true, dbVersion: OLDEST_SUPPORTED_DB_VERSION, needsMigration: true+ });+ });++ 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"+ });+ // Shorter than the header it would have to start with.+ expect(validateDatabaseFile(fileWith("SQLite"))).toMatchObject({ valid: false, rejection: "not-a-database" });+ expect(validateDatabaseFile(path.join(tempRoot, "nothing-here.db"))).toMatchObject({+ valid: false, rejection: "not-a-database"+ });+ });++ 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)");+ const insert = db.prepare("INSERT INTO notes VALUES (?, ?)");+ for (let i = 0; i < 500; i++) {+ insert.run(`note${i}`, `title ${i}`.repeat(20));+ }+ });++ // Somewhere past the first page, so the file still opens and the damage is found by reading it.+ const damaged = fs.readFileSync(filePath);+ damaged.fill(0xff, 4096 + 24, 4096 + 200);+ fs.writeFileSync(filePath, damaged);++ expect(validateDatabaseFile(filePath)).toMatchObject({ valid: false, rejection: "damaged-database" });+ });+});diff --git a/apps/server/src/services/database_validation.ts b/apps/server/src/services/database_validation.tsnew file mode 100644index 0000000000..21dce03ef7--- /dev/null+++ b/apps/server/src/services/database_validation.ts@@ -0,0 +1,153 @@+import { app_info as appInfo } 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.+ *+ * 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.+ *+ * @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.+ */+export function validateDatabaseFile(filePath: string): DatabaseValidation {+ if (!hasSqliteHeader(filePath)) {+ return reject("not-a-database", "The file is not a SQLite database.");+ }++ let db: Database.Database;+ try {+ db = new Database(filePath, {+ readonly: true,+ fileMustExist: true,+ nativeBinding: process.env.BETTERSQLITE3_NATIVE_PATH || undefined+ });+ } catch (e) {+ return reject("not-a-database", `The database could not be opened: ${messageOf(e)}`);+ }++ try {+ return inspect(db);+ } catch (e) {+ return reject("damaged-database", `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 };+}++/**+ * Checks the file starts the way a SQLite database does, which costs sixteen bytes and spares the+ * 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);+ 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);+ } catch {+ return false;+ } finally {+ if (descriptor !== undefined) {+ fs.closeSync(descriptor);+ }+ }+}++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/apps/server/src/sql_provider.ts b/apps/server/src/sql_provider.tsindex b47631d0bd..5495c2ffad 100644--- a/apps/server/src/sql_provider.ts+++ b/apps/server/src/sql_provider.ts@@ -45,6 +45,13 @@ export default class BetterSqlite3Provider implements DatabaseProvider {this.dbConnection = new Database(buffer, dbOpts);}+ detach() {+ // Closing is what folds the -wal file back into the database and lets the file be replaced;+ // on Windows it cannot even be renamed while a handle is open.+ this.dbConnection?.close();+ this.dbConnection = undefined;+ }+async backup(destinationFile: string) {try {unlinkSync(destinationFile);diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex bdb8938c45..4a9027b6a1 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -935,12 +935,27 @@ export type BootstrapDefinition = {oauthConnectionFailed?: string;};+/**+ * What the setup screen may be busy with. Each of these builds the database from nothing, so only+ * one of them may run at a time.+ */+export type SetupOperation = "new-document" | "sync-from-server" | "sync-seed" | "restore-backup";+/*** Response for /api/setup/status.+ *+ * Also parsed from a remote sync server, which may be running an older version than this one, so+ * anything added after the two original fields is optional.*/export interface SetupStatusResponse {syncVersion: number;schemaExists: boolean;+ isInitialized?: boolean;+ /** The operation setup is busy with, or `null` when it is free. */+ setupOperation?: SetupOperation | null;+ /** Kept from a failed sync attempt so the wizard can prefill the form; pre-initialization only. */+ syncServerHost?: string;+ syncProxy?: string;}/**diff --git a/packages/trilium-core/src/errors.ts b/packages/trilium-core/src/errors.tsindex f2127f280c..68dc39a51f 100644--- a/packages/trilium-core/src/errors.ts+++ b/packages/trilium-core/src/errors.ts@@ -28,6 +28,16 @@ export class ForbiddenError extends HttpError {}+/** The request is well-formed but conflicts with the state it would act on, e.g. an offset that has moved on. */+export class ConflictError extends HttpError {++ constructor(message: string) {+ super(message, 409);+ this.name = "ConflictError";+ }++}+export class OpenIdError {message: string;diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex ae67bb9d25..b860ffac0d 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -22,6 +22,7 @@ export { default as BackupService, getBackup, initBackup, type BackupOptionsServexport 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 * 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/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex 7c924f05c2..f59b49765d 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -1,5 +1,6 @@import sqlInit from "../../services/sql_init.js";import setupService from "../../services/setup.js";+import { getRunningSetupOperation, withSetupLock } from "../../services/setup_lock.js";import { getLog } from "../../services/log.js";import appInfo from "../../services/app_info.js";import optionService from "../../services/options.js";@@ -14,6 +15,9 @@ function getStatus() {isInitialized,schemaExists,syncVersion: appInfo.syncVersion,+ // What another tab, or this one after a reload, has already started. Lets the wizard say so+ // rather than only finding out by being refused.+ setupOperation: getRunningSetupOperation(),// After a FAILED sync-from-server attempt the sync options are already stored in// the partial DB; expose them so the wizard can prefill the form when the user// goes back to correct it (#10548). Pre-initialization only: this endpoint is@@ -30,15 +34,22 @@ function getStatus() {async function setupNewDocument(req: Request) {const { skipDemoDb } = req.query;const locale = req.body?.locale;- await sqlInit.createInitialDatabase(skipDemoDb !== undefined, locale);++ await withSetupLock("new-document", () => sqlInit.createInitialDatabase(skipDemoDb !== undefined, locale));}+/**+ * The lock covers fetching the seed and creating the schema, not the sync that follows: an+ * interrupted sync is resumed and retried across later requests, and a failed one has to leave the+ * user free to take another path instead.+ */function setupSyncFromServer(req: Request): Promise<SetupSyncFromServerResponse> {const { syncServerHost, syncProxy, password, syncMaxBlobContentSize } = req.body;const maxBlobContentSize = Number.isFinite(syncMaxBlobContentSize) && syncMaxBlobContentSize > 0 ? syncMaxBlobContentSize : 0;- return setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password, maxBlobContentSize);+ return withSetupLock("sync-from-server", () =>+ setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password, maxBlobContentSize));}async function saveSyncSeed(req: Request) {@@ -62,7 +73,7 @@ async function saveSyncSeed(req: Request) {// Awaited so a failure surfaces as an error response to the pushing desktop// instead of an unhandled rejection with a 2xx already sent.- await sqlInit.createDatabaseForSync(options);+ await withSetupLock("sync-seed", () => sqlInit.createDatabaseForSync(options));}/**diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 57a7d60f47..9f2374fa6d 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -143,7 +143,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutasyncRoute(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);// group of the services below are meant to be executed from the outside- route(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);+ // Not transactional: a status read needs no transaction, and one is unopenable during the moment+ // a restore has the database detached — which is exactly when the wizard is polling hardest.+ asyncRoute(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);asyncRoute(PST, "/api/setup/new-document", [checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler);asyncRoute(PST, "/api/setup/sync-from-server", [checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler);route(GET, "/api/setup/sync-seed", [loginRateLimiter, checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);diff --git a/packages/trilium-core/src/services/setup_lock.spec.ts b/packages/trilium-core/src/services/setup_lock.spec.tsnew file mode 100644index 0000000000..ea8249c039--- /dev/null+++ b/packages/trilium-core/src/services/setup_lock.spec.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";++import { getRunningSetupOperation, holdSetup, withSetupLock } from "./setup_lock.js";++/** A piece of work that only finishes when the test says so. */+function pending<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });++ return { promise, resolve, reject };+}++describe("setup lock", () => {+ it("refuses a second operation while one is running, rather than queuing it behind it", async () => {+ const first = pending<string>();+ const running = withSetupLock("restore-backup", () => first.promise);++ expect(getRunningSetupOperation()).toBe("restore-backup");+ await expect(withSetupLock("new-document", async () => "wiped")).rejects.toThrow(+ "Cannot start 'new-document': setup is already busy with 'restore-backup'."+ );++ first.resolve("restored");+ expect(await running).toBe("restored");+ expect(getRunningSetupOperation()).toBe(null);+ });++ it("frees setup when the operation fails, so the user can try something else", async () => {+ await expect(withSetupLock("sync-from-server", async () => { throw new Error("no such host"); }))+ .rejects.toThrow("no such host");++ expect(getRunningSetupOperation()).toBe(null);+ await expect(withSetupLock("new-document", async () => "created")).resolves.toBe("created");+ });++ it("reserves setup for an operation that has not started yet, until the hold is released", async () => {+ const release = holdSetup("restore-backup");++ expect(getRunningSetupOperation()).toBe("restore-backup");+ await expect(withSetupLock("new-document", async () => "wiped")).rejects.toThrow(/already busy/);+ expect(() => holdSetup("restore-backup")).toThrow(/already busy/);++ release();++ expect(getRunningSetupOperation()).toBe(null);+ await expect(withSetupLock("new-document", async () => "created")).resolves.toBe("created");+ });++ it("refuses a hold while an operation is running", async () => {+ const first = pending<void>();+ const running = withSetupLock("new-document", () => first.promise);++ expect(() => holdSetup("restore-backup")).toThrow(/already busy with 'new-document'/);++ first.resolve();+ await running;+ });+});diff --git a/packages/trilium-core/src/services/setup_lock.ts b/packages/trilium-core/src/services/setup_lock.tsnew file mode 100644index 0000000000..4ec426b8b9--- /dev/null+++ b/packages/trilium-core/src/services/setup_lock.ts@@ -0,0 +1,77 @@+import type { SetupOperation } from "@triliumnext/commons";++import { ConflictError } from "../errors.js";+import { getLog } from "./log.js";++/**+ * Lets one setup operation at a time create the database.+ *+ * The setup screen is reachable by anyone who can reach an uninitialized instance, and nothing stops+ * a second browser tab, a second phone, or an impatient double click from starting a second one. The+ * operations all end in the same place: creating a document, pulling one from a sync server, or+ * restoring one from a backup, each of which builds the database from nothing.+ *+ * Running two of those at once is not slow, it is destructive: a restore that spent an hour receiving+ * a file would be overwritten by a "create new document" started in another tab a moment before it+ * finished, and neither side would report anything wrong.+ *+ * So the second one is refused rather than queued. Queuing would run it *after* the first, which for+ * operations that each wipe what came before is the same accident with extra waiting.+ *+ * @module+ */++let running: SetupOperation | null = null;+const holds = new Set<SetupOperation>();++/**+ * Runs `work` as the one setup operation, refusing to start while another is under way.+ *+ * The lock is held for as long as `work` runs, which for a restore is the whole of it: the request+ * that started it returns long before, and the client follows the rest by polling.+ *+ * @throws ConflictError when another operation, or a hold taken by {@link holdSetup}, has the lock.+ */+export async function withSetupLock<T>(operation: SetupOperation, work: () => Promise<T>): Promise<T> {+ requireIdle(operation);+ running = operation;+ getLog().info(`Setup operation '${operation}' started.`);++ try {+ return await work();+ } finally {+ running = null;+ getLog().info(`Setup operation '${operation}' finished.`);+ }+}++/**+ * Reserves setup for an operation that has not started yet, e.g. a backup being uploaded before it+ * can be restored. Refuses for the same reason {@link withSetupLock} does, and is released by the+ * returned function however the operation ends.+ */+export function holdSetup(operation: SetupOperation): () => void {+ requireIdle(operation);+ holds.add(operation);++ return () => holds.delete(operation);+}++/** What setup is busy with, or `null` when it is not. For reporting, never for deciding. */+export function getRunningSetupOperation(): SetupOperation | null {+ return running ?? [ ...holds ][0] ?? null;+}++/**+ * Deciding and taking must not be separated: two requests that both looked first and took second+ * would both proceed, which is the whole thing this exists to prevent.+ */+function requireIdle(operation: SetupOperation): void {+ const current = getRunningSetupOperation();++ if (current) {+ throw new ConflictError(+ `Cannot start '${operation}': setup is already busy with '${current}'.`+ );+ }+}diff --git a/packages/trilium-core/src/services/sql/sql.ts b/packages/trilium-core/src/services/sql/sql.tsindex de7ee6e03c..11c2e9579b 100644--- a/packages/trilium-core/src/services/sql/sql.ts+++ b/packages/trilium-core/src/services/sql/sql.ts@@ -41,6 +41,37 @@ export class SqlService {this.dbConnection.loadFromBuffer(buffer);}+ /**+ * Releases the database file so it can be replaced, and refuses every query until+ * {@link attachFromFile} puts one back.+ *+ * The pair exists for restoring a backup, which cannot be done through the connection it is+ * replacing: on Windows the file cannot even be renamed while it is open. Only sound while+ * nothing is using the database, which on the setup screen is the case by construction.+ *+ * @throws Error inside a transaction, which detaching would abandon halfway.+ */+ detachConnection() {+ if (!this.dbConnection.detach) {+ throw new Error("Database provider does not support detaching.");+ }+ if (this.dbConnection.inTransaction) {+ throw new Error("Cannot detach the database in the middle of a transaction.");+ }++ this.statementCache = {};+ this.dbConnection.detach();+ }++ /**+ * Attaches to the database file at `path`, clearing the prepared-statement cache: cached+ * statements belong to the connection that prepared them and mean nothing to a new one.+ */+ attachFromFile(path: string, isReadOnly = this.params.isReadOnly) {+ this.statementCache = {};+ this.dbConnection.loadFromFile(path, isReadOnly);+ }+insert<T extends {}>(tableName: string, rec: T, replace = false) {const keys = Object.keys(rec || {});if (keys.length === 0) {diff --git a/packages/trilium-core/src/services/sql/types.ts b/packages/trilium-core/src/services/sql/types.tsindex 2750312d15..7927696bb5 100644--- a/packages/trilium-core/src/services/sql/types.ts+++ b/packages/trilium-core/src/services/sql/types.ts@@ -29,6 +29,14 @@ export interface DatabaseProvider {* Optional - only implemented by browser-based providers.*/serialize?(): Uint8Array;+ /**+ * Releases the database file, leaving the provider with no connection until a `loadFrom*` call+ * gives it one again. Every later query fails until then, deliberately: it is the caller's job to+ * re-attach, and a silent reconnection would hide a swap that went wrong.+ *+ * Optional - only implemented where the database is a file that can be replaced underneath.+ */+ detach?(): void;prepare(query: string): Statement;transaction<T>(func: (statement: Statement) => T): Transaction;get inTransaction(): boolean;