Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core: add API for retrieving the content of deleted notes
Adorian Doran1a6d0283b858
diff --git a/packages/trilium-core/src/routes/api/deleted_notes.spec.ts b/packages/trilium-core/src/routes/api/deleted_notes.spec.tsnew file mode 100644index 0000000000..e401e44822--- /dev/null+++ b/packages/trilium-core/src/routes/api/deleted_notes.spec.ts@@ -0,0 +1,128 @@+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import protectedSessionService from "../../services/protected_session";+import { getSql } from "../../services/sql/index";+import { createTextNote } from "../../test/api_fixtures";+import { CoreApiTester } from "../../test/api_tester";++/**+ * Drives the shared core deleted-notes routes through {@link CoreApiTester} (no Express), so this+ * spec runs under both the node and standalone (WASM) suites. These routes read soft-deleted rows+ * directly via SQL — they must never resolve through Becca (which excludes deleted notes).+ */+interface DeletedNoteMetadata {+ noteId: string;+ title: string;+ type: string;+ mime: string;+ blobId: string;+ isProtected: boolean;+}++interface BlobResponse {+ blobId: string;+ content: string | null;+ contentLength: number;+ isStubbed: boolean;+}++let api: CoreApiTester;++async function createDeletedNote(title: string, content = "<p>deleted body</p>"): Promise<string> {+ const { noteId } = await createTextNote(api, { title, content });+ const del = await api.delete(`/api/notes/${noteId}`, {+ query: { taskId: `deleted-notes-${noteId}`, last: "true" }+ });+ expect(del.status).toBe(204);+ return noteId;+}++describe("Deleted notes API (core)", () => {+ beforeAll(() => {+ api = CoreApiTester.build();+ });++ describe("metadata", () => {+ it("returns metadata for a soft-deleted note", async () => {+ const noteId = await createDeletedNote("Deleted metadata note");++ const res = await api.get<DeletedNoteMetadata>(`/api/deleted-notes/${noteId}/metadata`);++ expect(res.status).toBe(200);+ expect(res.body.noteId).toBe(noteId);+ expect(res.body.title).toBe("Deleted metadata note");+ expect(res.body.type).toBe("text");+ expect(typeof res.body.blobId).toBe("string");+ expect(res.body.isProtected).toBe(false);+ });++ it("returns 404 for a live (non-deleted) note", async () => {+ const { noteId } = await createTextNote(api, { title: "Still alive" });++ const res = await api.get(`/api/deleted-notes/${noteId}/metadata`);++ expect(res.status).toBe(404);+ });++ it("returns 404 for an unknown note", async () => {+ const res = await api.get("/api/deleted-notes/missingNote123/metadata");++ expect(res.status).toBe(404);+ });+ });++ describe("blob", () => {+ it("returns the decoded content of a soft-deleted text note", async () => {+ const noteId = await createDeletedNote("Deleted blob note", "<p>gone but readable</p>");++ const res = await api.get<BlobResponse>(`/api/deleted-notes/${noteId}/blob`);++ expect(res.status).toBe(200);+ expect(res.body.content).toBe("<p>gone but readable</p>");+ expect(typeof res.body.blobId).toBe("string");+ });++ it("returns 404 for a live (non-deleted) note", async () => {+ const { noteId } = await createTextNote(api, { title: "Alive blob" });++ const res = await api.get(`/api/deleted-notes/${noteId}/blob`);++ expect(res.status).toBe(404);+ });+ });++ describe("protected notes", () => {+ let protectedNoteId: string;++ beforeAll(async () => {+ protectedNoteId = await createDeletedNote("Secret deleted note");+ // Flag it protected directly in the DB (avoids needing a real protected session to create it),+ // matching how the deleted note surfaces with current_isProtected set.+ getSql().execute("UPDATE notes SET isProtected = 1 WHERE noteId = ?", [protectedNoteId]);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("masks the title when no protected session is available", async () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(false);++ const res = await api.get<DeletedNoteMetadata>(`/api/deleted-notes/${protectedNoteId}/metadata`);++ expect(res.status).toBe(200);+ expect(res.body.isProtected).toBe(true);+ expect(res.body.title).toBe("[protected]");+ });++ it("decrypts the title when a protected session is available", async () => {+ vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(true);+ vi.spyOn(protectedSessionService, "decryptString").mockReturnValue("Decrypted deleted title");++ const res = await api.get<DeletedNoteMetadata>(`/api/deleted-notes/${protectedNoteId}/metadata`);++ expect(res.status).toBe(200);+ expect(res.body.title).toBe("Decrypted deleted title");+ });+ });+});diff --git a/packages/trilium-core/src/routes/api/deleted_notes.ts b/packages/trilium-core/src/routes/api/deleted_notes.tsnew file mode 100644index 0000000000..c6e33bfb6e--- /dev/null+++ b/packages/trilium-core/src/routes/api/deleted_notes.ts@@ -0,0 +1,69 @@+import type { Request } from "express";+import type { NoteRow, NoteType } from "@triliumnext/commons";++import { NotFoundError } from "../../errors.js";+import blobService from "../../services/blob.js";+import protectedSessionService from "../../services/protected_session.js";+import { getSql } from "../../services/sql/index.js";++/**+ * Read-only metadata for a soft-deleted (not-yet-erased) note. Matches the shape the client's+ * `FNoteRow` expects so a detached, tree-less `DeletedFNote` can be built from it without ever+ * loading the note into Froca/Becca.+ */+interface DeletedNoteMetadata {+ noteId: string;+ title: string;+ type: NoteType;+ mime: string;+ blobId: string;+ isProtected: boolean;+}++/**+ * Returns metadata (title, type, mime, blobId, isProtected) for a single soft-deleted note.+ * Throws `NotFoundError` if the note is live or already erased. Protected note titles are decrypted+ * when a protected session is available, otherwise replaced with a placeholder — mirroring recent-changes.+ */+function getDeletedNoteMetadata(req: Request<{ noteId: string }>): DeletedNoteMetadata {+ const { noteId } = req.params;++ const row = getSql().getRowOrNull<Pick<NoteRow, "noteId" | "title" | "type" | "mime" | "blobId" | "isProtected">>(+ /*sql*/ `SELECT noteId, title, type, mime, blobId, isProtected FROM notes WHERE noteId = ? AND isDeleted = 1`,+ [noteId]+ );++ if (!row || !row.blobId || !row.type) {+ throw new NotFoundError(`Deleted note '${noteId}' was not found.`);+ }++ let title = row.title;+ if (row.isProtected) {+ title = protectedSessionService.isProtectedSessionAvailable()+ ? protectedSessionService.decryptString(title) || "[protected]"+ : "[protected]";+ }++ return {+ noteId: row.noteId,+ title,+ type: row.type,+ mime: row.mime,+ blobId: row.blobId,+ isProtected: !!row.isProtected+ };+}++/**+ * Returns the blob (content) of a single soft-deleted note. Delegates to the SQL-backed,+ * protected-aware reader that bypasses Becca. Throws `NotFoundError` if the note is not+ * soft-deleted or its blob has already been erased.+ */+function getDeletedNoteBlob(req: Request<{ noteId: string }>) {+ return blobService.getDeletedNoteBlobPojo(req.params.noteId);+}++export default {+ getDeletedNoteMetadata,+ getDeletedNoteBlob+};diff --git a/packages/trilium-core/src/routes/api/recent_changes.spec.ts b/packages/trilium-core/src/routes/api/recent_changes.spec.tsindex dbe6d58192..c51e6596fc 100644--- a/packages/trilium-core/src/routes/api/recent_changes.spec.ts+++ b/packages/trilium-core/src/routes/api/recent_changes.spec.ts@@ -87,6 +87,38 @@ describe("Recent changes API (core)", () => {expect(deletedEntries.every((change) => change.canBeUndeleted === true)).toBe(true);});+ describe("deletedOnly filter", () => {+ it("returns only deleted notes when deletedOnly=true", async () => {+ const live = await createTextNote(api, { title: "Live for deletedOnly" });+ const { noteId: deletedId } = await createTextNote(api, { title: "Deleted for deletedOnly" });+ const del = await api.delete(`/api/notes/${deletedId}`, {+ query: { taskId: "recent-changes-deletedOnly", last: "true" }+ });+ expect(del.status).toBe(204);++ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root", {+ query: { deletedOnly: "true" }+ });++ expect(res.status).toBe(200);+ expect(res.body.length).toBeGreaterThan(0);+ // Every returned change is for a deleted note...+ expect(res.body.every((change) => !!change.current_isDeleted)).toBe(true);+ // ...the deleted note is present, and the live one is filtered out.+ expect(res.body.some((change) => change.noteId === deletedId)).toBe(true);+ expect(res.body.some((change) => change.noteId === live.noteId)).toBe(false);+ });++ it("includes live notes when deletedOnly is not set", async () => {+ const { noteId } = await createTextNote(api, { title: "Live by default" });++ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");++ expect(res.status).toBe(200);+ expect(res.body.some((change) => change.noteId === noteId && !change.current_isDeleted)).toBe(true);+ });+ });+it("returns an empty list for a non-existent ancestor", async () => {const res = await api.get<RecentChangeRow[]>("/api/recent-changes/missingAncestor123");diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex b4a818b349..9edf775393 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -16,6 +16,7 @@ import attributesRoute from "./api/attributes";import revisionsApiRoute from "./api/revisions";import relationMapApiRoute from "./api/relation-map";import recentChangesApiRoute from "./api/recent_changes";+import deletedNotesApiRoute from "./api/deleted_notes";import bulkActionRoute from "./api/bulk_action";import searchRoute from "./api/search";import specialNotesRoute from "./api/special_notes";@@ -222,6 +223,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutapiRoute(PST, "/api/relation-map", relationMapApiRoute.getRelationMap);apiRoute(GET, "/api/recent-changes/:ancestorNoteId", recentChangesApiRoute.getRecentChanges);+ apiRoute(GET, "/api/deleted-notes/:noteId/metadata", deletedNotesApiRoute.getDeletedNoteMetadata);+ apiRoute(GET, "/api/deleted-notes/:noteId/blob", deletedNotesApiRoute.getDeletedNoteBlob);+//#region Filesroute(GET, "/api/notes/:noteId/open", [checkApiAuthOrElectron], filesRoute.openFile);route(GET, "/api/notes/:noteId/download", [checkApiAuthOrElectron], filesRoute.downloadFile);diff --git a/packages/trilium-core/src/services/blob.spec.ts b/packages/trilium-core/src/services/blob.spec.tsindex 28bc157228..7d99018b15 100644--- a/packages/trilium-core/src/services/blob.spec.ts+++ b/packages/trilium-core/src/services/blob.spec.ts@@ -228,6 +228,75 @@ describe("blob", () => {});});+ describe("getDeletedNoteBlobPojo", () => {+ function createDeletedNote(overrides: { content?: string | Uint8Array; type?: string; mime?: string } = {}) {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "deleted blob spec note",+ content: overrides.content ?? "<p>deleted note body</p>",+ type: (overrides.type ?? "text") as any,+ mime: overrides.mime+ });+ // Soft-delete only: the row and its blob survive, so the content stays readable.+ getSql().execute("UPDATE notes SET isDeleted = 1 WHERE noteId = ?", [note.noteId]);+ return note;+ }++ it("throws NotFoundError for a live (not soft-deleted) note", () => {+ expect(() => getContext().init(() => {+ const { note } = notesService.createNewNote({+ parentNoteId: "root",+ title: "live note",+ content: "<p>alive</p>",+ type: "text"+ });+ return blob.getDeletedNoteBlobPojo(note.noteId);+ })).toThrow(NotFoundError);+ });++ it("throws NotFoundError for an unknown note", () => {+ expect(() => getContext().init(() => blob.getDeletedNoteBlobPojo("doesNotExist123"))).toThrow(NotFoundError);+ });++ it("returns the decoded string content of a soft-deleted text note", () => {+ const content = getContext().init(() => blob.getDeletedNoteBlobPojo(createDeletedNote().noteId).content);+ expect(content).toBe("<p>deleted note body</p>");+ });++ it("nulls out the content for a soft-deleted binary note", () => {+ const { content, contentLength } = getContext().init(() => {+ const note = createDeletedNote({ content: Uint8Array.from([0, 1, 2, 3]), type: "image", mime: "image/png" });+ const pojo = blob.getDeletedNoteBlobPojo(note.noteId);+ return { content: pojo.content, contentLength: pojo.contentLength };+ });+ expect(content).toBeNull();+ expect(contentLength).toBeGreaterThan(0);+ });++ it("decrypts a soft-deleted protected note's content when a protected session is available, and blanks it otherwise", () => {+ const noteId = getContext().init(() => {+ const note = createDeletedNote();+ // Turn it into a protected note whose blob holds the encrypted content.+ const cipher = dataEncryption.encrypt(PROTECTED_KEY, "<p>secret deleted body</p>");+ getSql().execute("UPDATE notes SET isProtected = 1 WHERE noteId = ?", [note.noteId]);+ getSql().execute("UPDATE blobs SET content = ? WHERE blobId = ?", [cipher, note.blobId]);+ return note.noteId;+ });++ // Without a session the content is blanked, not leaked.+ protectedSessionService.resetDataKey();+ expect(getContext().init(() => blob.getDeletedNoteBlobPojo(noteId).content)).toBe("");++ // With a session it is decrypted.+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ expect(getContext().init(() => blob.getDeletedNoteBlobPojo(noteId).content)).toBe("<p>secret deleted body</p>");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });+ });+describe("EMPTY_BLOB_ID", () => {it("equals hashedBlobId of empty content", () => {// Guards the hard-coded constant in commons (which cannot call hashedBlobId at module load).diff --git a/packages/trilium-core/src/services/blob.ts b/packages/trilium-core/src/services/blob.tsindex 2bf98c89fd..acbface40a 100644--- a/packages/trilium-core/src/services/blob.ts+++ b/packages/trilium-core/src/services/blob.ts@@ -1,9 +1,10 @@-import { BlobRow, EMPTY_BLOB_ID } from "@triliumnext/commons";+import { BlobRow, EMPTY_BLOB_ID, NoteRow } from "@triliumnext/commons";import becca from "../becca/becca.js";import { NotFoundError } from "../errors";import protectedSessionService from "./protected_session.js";+import { getSql } from "./sql/index.js";import { decodeUtf8 } from "./utils/binary.js";-import { hash } from "./utils/index.js";+import { hash, isStringNote } from "./utils/index.js";function getBlobPojo(entityName: string, entityId: string, opts?: { preview: boolean }) {// TODO: Unused opts.@@ -34,6 +35,53 @@ function getBlobPojo(entityName: string, entityId: string, opts?: { preview: booreturn { ...pojo, isStubbed };}+/**+ * Produces a blob POJO for a soft-deleted (not-yet-erased) note. The normal {@link getBlobPojo}+ * path resolves the note through Becca, which never contains deleted notes — so this reads the+ * soft-deleted `notes` row and its blob directly via SQL instead, without ever loading the note+ * into the cache. Gated on `isDeleted = 1`, so it cannot be used to read live notes.+ *+ * Protected content is decrypted exactly like the normal path: via {@link processContent}, which+ * returns the decrypted content when a protected session is available and an empty string otherwise.+ */+function getDeletedNoteBlobPojo(noteId: string) {+ const sql = getSql();++ const noteRow = sql.getRowOrNull<Pick<NoteRow, "isProtected" | "type" | "mime" | "blobId">>(+ /*sql*/ `SELECT isProtected, type, mime, blobId FROM notes WHERE noteId = ? AND isDeleted = 1`,+ [noteId]+ );++ if (!noteRow || !noteRow.blobId) {+ throw new NotFoundError(`Deleted note '${noteId}' was not found.`);+ }++ const blobRow = sql.getRowOrNull<BlobRow>(/*sql*/ `SELECT *, LENGTH(content) AS contentLength FROM blobs WHERE blobId = ?`, [noteRow.blobId]);++ if (!blobRow) {+ // The note is deleted but its blob has already been erased.+ throw new NotFoundError(`Blob '${noteRow.blobId}' for deleted note '${noteId}' was not found.`);+ }++ const pojo = {+ blobId: blobRow.blobId,+ content: blobRow.content as string | Uint8Array | null,+ contentLength: blobRow.contentLength,+ dateModified: blobRow.dateModified,+ utcDateModified: blobRow.utcDateModified+ };++ const isStubbed = pojo.contentLength === 0 && pojo.blobId !== EMPTY_BLOB_ID;++ if (!isStringNote(noteRow.type, noteRow.mime)) {+ pojo.content = null;+ } else {+ pojo.content = processContent(pojo.content, !!noteRow.isProtected, true);+ }++ return { ...pojo, isStubbed };+}+function processContent(content: Uint8Array | string | null, isProtected: boolean, isStringContent: boolean) {if (isProtected) {if (protectedSessionService.isProtectedSessionAvailable()) {@@ -64,6 +112,7 @@ function calculateContentHash({ blobId, content, textRepresentation }: Pick<Blobexport default {getBlobPojo,+ getDeletedNoteBlobPojo,processContent,calculateContentHash};