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
feat(search): find protected notes by the text OCR pulled out of them
Elian Doran48a2beb34e86
diff --git a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.tsindex c0999c1543..0e01a26057 100644--- a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts@@ -1,14 +1,19 @@-import { describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it } from "vitest";import becca from "../../../becca/becca.js";import type BNote from "../../../becca/entities/bnote.js";+import blobService from "../../blob.js";import { getContext } from "../../context.js";import noteService from "../../notes.js";+import protectedSessionService from "../../protected_session.js";import { getSql } from "../../sql/index.js";+import { encodeUtf8 } from "../../utils/binary.js";import NoteSet from "../note_set.js";import SearchContext from "../search_context.js";import OCRContentExpression from "./ocr_content.js";+const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+let counter = 0;/**@@ -64,6 +69,28 @@ function createNoteWithOcrAttachment(ocrText: string): BNote {return note;}+/**+ * As {@link createNoteWithOcrText}, for a note the query has to decrypt: the row is flagged protected+ * and the text is stored encrypted, the way the OCR service stores it. Needs an open session.+ */+function createProtectedNoteWithOcrText(ocrText: string): BNote {+ const note = createNoteWithOcrText(blobService.encryptTextRepresentation(ocrText, true));++ getSql().execute("UPDATE notes SET isProtected = 1 WHERE noteId = ?", [note.noteId]);+ note.isProtected = true;++ return note;+}++/** The attachment counterpart: only the attachment row is flagged, which is what the query reads. */+function createProtectedNoteWithOcrAttachment(ocrText: string): BNote {+ const note = createNoteWithOcrAttachment(blobService.encryptTextRepresentation(ocrText, true));++ getSql().execute("UPDATE attachments SET isProtected = 1 WHERE ownerId = ?", [note.noteId]);++ return note;+}+function setTextRepresentationForBlob(blobId: string, textRepresentation: string) {getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", [textRepresentation,@@ -199,4 +226,46 @@ describe("OCRContentExpression (real DB)", () => {const exp = new OCRContentExpression(["foo", "bar"]);expect(exp.toString()).toBe("OCRContent('foo', 'bar')");});++ describe("protected notes", () => {+ beforeEach(() => protectedSessionService.setDataKey(PROTECTED_KEY));+ afterEach(() => protectedSessionService.resetDataKey());++ it("matches encrypted text on a note and on an attachment, with the same semantics as the query", () => {+ const note = createProtectedNoteWithOcrText("Protected invoice total");+ const viaAttachment = createProtectedNoteWithOcrAttachment("Protected scanned receipt");++ expect(execute(new OCRContentExpression(["invoice"])).hasNote(note)).toBe(true);+ expect(execute(new OCRContentExpression(["receipt"])).hasNote(viaAttachment)).toBe(true);++ // Case-insensitive, as SQLite's LIKE is for the unprotected ones.+ expect(execute(new OCRContentExpression(["INVOICE"])).hasNote(note)).toBe(true);++ // And every token still has to be there.+ expect(execute(new OCRContentExpression(["invoice", "receipt"])).hasNote(note)).toBe(false);+ });++ it("finds protected and unprotected notes in one search", () => {+ const openly = createNoteWithOcrText("shared marker openly stored");+ const encrypted = createProtectedNoteWithOcrText("shared marker under lock");++ const result = execute(new OCRContentExpression(["marker"]));++ expect(result.hasNote(openly)).toBe(true);+ expect(result.hasNote(encrypted)).toBe(true);+ });++ it("cannot match a protected note once the session is closed", () => {+ const note = createProtectedNoteWithOcrText("Protected passport number");++ protectedSessionService.resetDataKey();++ // Neither by the text it was made from, nor by anything in the stored ciphertext.+ expect(execute(new OCRContentExpression(["passport"])).hasNote(note)).toBe(false);++ const stored = getSql().getValue<string>(+ "SELECT textRepresentation FROM blobs WHERE blobId = ?", [note.blobId ?? ""]);+ expect(execute(new OCRContentExpression([stored.slice(0, 12)])).hasNote(note)).toBe(false);+ });+ });});diff --git a/packages/trilium-core/src/services/search/expressions/ocr_content.ts b/packages/trilium-core/src/services/search/expressions/ocr_content.tsindex 324297c0a4..de826d7696 100644--- a/packages/trilium-core/src/services/search/expressions/ocr_content.ts+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.ts@@ -1,4 +1,6 @@import becca from "../../../becca/becca.js";+import blobService from "../../blob.js";+import protectedSessionService from "../../protected_session.js";import { getSql } from "../../sql/index.js";import NoteSet from "../note_set.js";import type SearchContext from "../search_context.js";@@ -8,8 +10,10 @@ import Expression from "./expression.js";* Search expression for finding text within OCR-extracted content (textRepresentation)* from image notes and their attachments.*- * Uses a single SQL query to find all noteIds whose own blob or attachment blobs- * contain matching text, then intersects with the input note set.+ * Unprotected text is matched by the database, which is what it is for. A protected note's text is+ * stored encrypted and there is nothing in it for SQL to compare against, so those are read out and+ * matched here instead — and only while a protected session is open, since otherwise they cannot be+ * read at all.*/export default class OCRContentExpression extends Expression {private tokens: string[];@@ -41,38 +45,107 @@ export default class OCRContentExpression extends Expression {}/**- * Find all noteIds that have OCR text matching all tokens, in a single query.+ * Find all noteIds that have OCR text matching all tokens.* Checks both the note's own blob and its attachment blobs.*/private findNoteIdsWithMatchingOCR(): Set<string> {if (this.tokens.length === 0) return new Set();- // Build WHERE conditions: all tokens must appear in textRepresentation+ const matchingNoteIds = new Set<string>();++ this.collectUnprotectedMatches(matchingNoteIds);+ this.collectProtectedMatches(matchingNoteIds);++ return matchingNoteIds;+ }++ /** The stored text is the readable text, so all tokens must appear in it. */+ private collectUnprotectedMatches(matchingNoteIds: Set<string>) {const likeConditions = this.tokens.map(() => `b.textRepresentation LIKE ?`).join(' AND ');const params = this.tokens.map(token => `%${token}%`);-- // Find notes whose own blob matchesconst sql = getSql();++ // Notes whose own blob matches.const noteIds = sql.getColumn<string>(`SELECT n.noteIdFROM notes nJOIN blobs b ON n.blobId = b.blobIdWHERE b.textRepresentation IS NOT NULLAND n.isDeleted = 0+ AND n.isProtected = 0AND ${likeConditions}`, params);- // Find notes that own attachments whose blob matches+ // Notes that own an attachment whose blob matches.const attachmentOwnerIds = sql.getColumn<string>(`SELECT a.ownerIdFROM attachments aJOIN blobs b ON a.blobId = b.blobIdWHERE b.textRepresentation IS NOT NULLAND a.isDeleted = 0+ AND a.isProtected = 0AND ${likeConditions}`, params);- return new Set([...noteIds, ...attachmentOwnerIds]);+ for (const noteId of [...noteIds, ...attachmentOwnerIds]) {+ matchingNoteIds.add(noteId);+ }+ }++ /**+ * The same search over blobs whose text is encrypted, decrypting each one to compare it.+ *+ * Only rows that are protected are read, and their text is what OCR pulled out of one file+ * rather than the file itself, so this stays far smaller than the note-content search that+ * already works this way.+ */+ private collectProtectedMatches(matchingNoteIds: Set<string>) {+ if (!protectedSessionService.isProtectedSessionAvailable()) {+ return;+ }++ const sql = getSql();+ const queries = [+ /*sql*/`+ SELECT n.noteId AS noteId, b.textRepresentation AS textRepresentation+ FROM notes n+ JOIN blobs b ON n.blobId = b.blobId+ WHERE b.textRepresentation IS NOT NULL+ AND n.isDeleted = 0+ AND n.isProtected = 1`,+ /*sql*/`+ SELECT a.ownerId AS noteId, b.textRepresentation AS textRepresentation+ FROM attachments a+ JOIN blobs b ON a.blobId = b.blobId+ WHERE b.textRepresentation IS NOT NULL+ AND a.isDeleted = 0+ AND a.isProtected = 1`+ ];++ for (const query of queries) {+ for (const row of sql.iterateRows<{ noteId: string; textRepresentation: string }>(query)) {+ if (matchingNoteIds.has(row.noteId)) {+ continue;+ }++ const text = blobService.decryptTextRepresentation(row.textRepresentation, true);++ if (text && this.matchesAllTokens(text)) {+ matchingNoteIds.add(row.noteId);+ }+ }+ }+ }++ /**+ * The in-memory equivalent of the LIKE conditions above: every token must appear, ignoring case.+ * Case folding is done on both sides, so unlike SQLite's LIKE this also holds outside ASCII. A+ * token is compared literally, where LIKE would read `%` or `_` in one as a wildcard.+ */+ private matchesAllTokens(text: string): boolean {+ const haystack = text.toLowerCase();++ return this.tokens.every(token => haystack.includes(token.toLowerCase()));}toString(): string {diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.tsindex 890bf76e29..b2bfd9e575 100644--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@ -5,8 +5,12 @@ import BBranch from "../../../becca/entities/bbranch.js";import SearchContext from "../search_context.js";import dateUtils from "../../utils/date.js";import becca from "../../../becca/becca.js";+import protectedSessionService from "../../protected_session.js";+import { encodeUtf8 } from "../../utils/binary.js";import { findNoteByTitle, note, NoteBuilder } from "../../../test/becca_mocking.js";+const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+describe("Search", () => {let rootNote: any;@@ -872,6 +876,33 @@ describe("Search", () => {expect(snippet).toBe("if a < b && b > c, then done");});+ it("takes a protected note's content as given, having already been decrypted on the way out", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ const noteBuilder = note("Protected note");+ noteBuilder.note.isProtected = true;+ // What a real note hands back with a session open. Decrypting it a second time here would+ // put it through the cipher as though it were still encrypted.+ noteBuilder.note.getContent = () => "<p>secret body text</p>";+ rootNote.child(noteBuilder);++ expect(searchService.extractContentSnippet(noteBuilder.note.noteId, [ "secret" ]))+ .toBe("secret body text");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });++ it("shows nothing of a protected note whose content the closed session withheld", () => {+ const noteBuilder = note("Locked note");+ noteBuilder.note.isProtected = true;+ // A real note answers with nothing at all when it cannot be read.+ noteBuilder.note.getContent = () => "";+ rootNote.child(noteBuilder);++ expect(searchService.extractContentSnippet(noteBuilder.note.noteId, [ "secret" ])).toBe("");+ });+// FIXME: test what happens when we order without any filter criteria// it("comparison between labels", () => {diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 0a12b5ff9d..2f713294cb 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -5,9 +5,9 @@ import striptags from "striptags";import becca from "../../../becca/becca.js";import becca_service from "../../../becca/becca_service.js";import type BNote from "../../../becca/entities/bnote.js";+import blobService from "../../blob.js";import hoistedNoteService from "../../hoisted_note.js";import { getLog } from "../../log.js";-import protectedSessionService from "../../protected_session.js";import scriptService from "../../script.js";import { isScriptingEnabled } from "../../scripting_guard.js";import { escapeHtml, escapeRegExp, unescapeHtml } from "../../utils/index.js";@@ -472,30 +472,22 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLengthlet content: string | undefined;if (["text", "code", "mermaid", "canvas", "mindMap", "llmChat"].includes(note.type)) {+ // Protection is already accounted for: a note hands back its content decrypted, and hands+ // back nothing at all when there is no session to decrypt it with.const raw = note.getContent();if (raw && typeof raw === "string") {content = raw;}} else {- // For non-text notes (image, file), use OCR text representation- content = getTextRepresentationForNote(note) || undefined;+ // For non-text notes (image, file), use OCR text representation. That one is stored as it+ // sits on the blob, so it is the reader's job to decrypt it — or to withhold it.+ content = blobService.decryptTextRepresentation(getTextRepresentationForNote(note), !!note.isProtected) || undefined;}if (!content) {return "";}- // Handle protected notes- if (note.isProtected && protectedSessionService.isProtectedSessionAvailable()) {- try {- content = protectedSessionService.decryptString(content) || "";- } catch (e) {- return ""; // Can't decrypt, don't show content- }- } else if (note.isProtected) {- return ""; // Protected but no session available- }-// Strip HTML tags for text notesif (note.type === "text") {// A collapsible's summary and body must not run into surrounding text: striptags