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(ocr): read back the text extracted from protected notes
Elian Doranae0e46f01345
diff --git a/packages/trilium-core/src/routes/api/ocr.spec.ts b/packages/trilium-core/src/routes/api/ocr.spec.tsindex 4b63231243..2cc389721a 100644--- a/packages/trilium-core/src/routes/api/ocr.spec.ts+++ b/packages/trilium-core/src/routes/api/ocr.spec.ts@@ -2,11 +2,16 @@ import type { TextRepresentationResponse } from "@triliumnext/commons";import { beforeAll, describe, expect, it } from "vitest";import becca from "../../becca/becca.js";+import blobService from "../../services/blob.js";import * as cls from "../../services/context.js";+import protectedSessionService from "../../services/protected_session.js";import { getSql } from "../../services/sql/index.js";+import { encodeUtf8 } from "../../services/utils/binary.js";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";+const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+/*** Drives the shared OCR read routes through {@link CoreApiTester} (no Express), so this spec runs* under both the node and standalone (WASM) suites — the second being the point of sharing them:@@ -56,6 +61,27 @@ describe("OCR text API (core)", () => {expect(res.body).toEqual({ success: true, text: "text on the scan", hasOcr: true });});+ it("decrypts a protected note's text, and withholds it when the session is closed", async () => {+ const { noteId } = await createTextNote(api, { content: "<p>a protected scan</p>" });+ const note = becca.getNoteOrThrow(noteId);+ note.isProtected = true;++ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ // Stored the way the OCR service stores it, so this covers both halves of the round trip.+ storeOcrText(note.blobId, blobService.encryptTextRepresentation("secret scanned text", true));++ const unlocked = await api.get<TextRepresentationResponse>(`/api/ocr/notes/${noteId}/text`);+ expect(unlocked.body).toEqual({ success: true, text: "secret scanned text", hasOcr: true });+ } finally {+ protectedSessionService.resetDataKey();+ }++ // Locked again: the stored ciphertext must not reach the client in place of the text.+ const locked = await api.get<TextRepresentationResponse>(`/api/ocr/notes/${noteId}/text`);+ expect(locked.body).toEqual({ success: true, text: "", hasOcr: false });+ });+it("404s for a missing note or attachment", async () => {const note = await api.get<TextRepresentationResponse>("/api/ocr/notes/missingNote123/text");expect(note.status).toBe(404);diff --git a/packages/trilium-core/src/routes/api/ocr.ts b/packages/trilium-core/src/routes/api/ocr.tsindex bda57c728e..156f675833 100644--- a/packages/trilium-core/src/routes/api/ocr.ts+++ b/packages/trilium-core/src/routes/api/ocr.ts@@ -2,6 +2,7 @@ import type { TextRepresentationResponse } from "@triliumnext/commons";import type { Request } from "express";import becca from "../../becca/becca.js";+import blobService from "../../services/blob.js";import { getSql } from "../../services/sql/index.js";/** The `[status, body]` tuple the result handler turns into a 404. */@@ -20,7 +21,7 @@ function getNoteOCRText(req: Request<{ noteId: string }>): TextRepresentationResreturn [ 404, { success: false, message: "Note not found" } ];}- return getTextRepresentation(note.blobId);+ return getTextRepresentation(note.blobId, !!note.isProtected);}/** The attachment counterpart of {@link getNoteOCRText}. */@@ -30,11 +31,15 @@ function getAttachmentOCRText(req: Request<{ attachmentId: string }>): TextReprereturn [ 404, { success: false, message: "Attachment not found" } ];}- return getTextRepresentation(attachment.blobId);+ return getTextRepresentation(attachment.blobId, !!attachment.isProtected);}-function getTextRepresentation(blobId: string | undefined): TextRepresentationResponse {- let ocrText: string | null = null;+/**+ * A protected entity's text is stored encrypted, so it is reported as absent rather than shown when+ * there is no protected session to read it with — the same answer the note's own content gives.+ */+function getTextRepresentation(blobId: string | undefined, isProtected: boolean): TextRepresentationResponse {+ let storedText: string | null = null;if (blobId) {const result = getSql().getRow<{@@ -46,13 +51,15 @@ function getTextRepresentation(blobId: string | undefined): TextRepresentationRe`, [ blobId ]);if (result) {- ocrText = result.textRepresentation;+ storedText = result.textRepresentation;}}+ const ocrText = blobService.decryptTextRepresentation(storedText, isProtected);+return {success: true,- text: ocrText || "",+ text: ocrText,hasOcr: !!ocrText};}diff --git a/packages/trilium-core/src/services/blob.spec.ts b/packages/trilium-core/src/services/blob.spec.tsindex fd87fc5046..6cce3788e4 100644--- a/packages/trilium-core/src/services/blob.spec.ts+++ b/packages/trilium-core/src/services/blob.spec.ts@@ -153,6 +153,50 @@ describe("blob", () => {});});+ describe("decryptTextRepresentation", () => {+ it("passes unprotected text through and reports absent text as empty", () => {+ protectedSessionService.resetDataKey();++ expect(blob.decryptTextRepresentation("extracted text", false)).toBe("extracted text");+ expect(blob.decryptTextRepresentation(null, false)).toBe("");+ expect(blob.decryptTextRepresentation(undefined, false)).toBe("");+ expect(blob.decryptTextRepresentation("", true)).toBe("");+ });++ it("round-trips protected text through the encrypting counterpart", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ const stored = blob.encryptTextRepresentation("text read out of a protected image", true);+ expect(blob.decryptTextRepresentation(stored, true)).toBe("text read out of a protected image");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });++ it("withholds protected text when no protected session is available", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const stored = blob.encryptTextRepresentation("secret", true);+ protectedSessionService.resetDataKey();++ // The ciphertext must never be handed back in place of the text.+ expect(blob.decryptTextRepresentation(stored, true)).toBe("");+ });++ it("answers with nothing for text encrypted under a different key", () => {+ const otherKey = encodeUtf8("fedcba9876543210"); // exactly 16 bytes+ const foreign = dataEncryption.encrypt(otherKey, "written with another key");++ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ // Deciphers to garbage, so the checksum fails and decryptString throws.+ expect(blob.decryptTextRepresentation(foreign, true)).toBe("");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });++ });+describe("getBlobPojo", () => {it("throws NotFoundError when the entity does not exist", () => {expect(() => getContext().init(() => blob.getBlobPojo("notes", "doesNotExist123"))).toThrow(NotFoundError);diff --git a/packages/trilium-core/src/services/blob.ts b/packages/trilium-core/src/services/blob.tsindex 8e7c5f4700..518cc22d82 100644--- a/packages/trilium-core/src/services/blob.ts+++ b/packages/trilium-core/src/services/blob.ts@@ -1,6 +1,7 @@import { BlobRow, EMPTY_BLOB_ID, NoteRow } from "@triliumnext/commons";import becca from "../becca/becca.js";import { NotFoundError } from "../errors";+import { getLog } from "./log.js";import protectedSessionService from "./protected_session.js";import { getSql } from "./sql/index.js";import { decodeUtf8 } from "./utils/binary.js";@@ -32,6 +33,10 @@ function getBlobPojo(entityName: string, entityId: string, opts?: { preview: boopojo.content = processContent(pojo.content, !!entity.isProtected, true) as string | Uint8Array;}+ // The extracted text travels with the blob and is protected on the same terms as the content it+ // was read out of, so it is decrypted (or withheld) on the same terms too.+ pojo.textRepresentation = decryptTextRepresentation(pojo.textRepresentation, !!entity.isProtected) || null;+return { ...pojo, isStubbed };}@@ -132,6 +137,42 @@ function encryptTextRepresentation(textRepresentation: string, isProtected: boolreturn encrypted;}+/**+ * Reads OCR-extracted text back off a blob, for every consumer of `blobs.textRepresentation`.+ *+ * The counterpart of {@link encryptTextRepresentation}, and it mirrors what {@link processContent}+ * does for `content`: decrypt when a protected session is available, and answer with nothing when it+ * is not — so a locked note reports no extracted text rather than showing the ciphertext it stores.+ * Text that will not decrypt is treated the same way, since no caller has anything better to do with+ * it than a caller that has no key, and one unreadable blob should not fail the request around it.+ *+ * One inherited edge: a stored value whose length rules out ciphertext altogether takes+ * dataEncryptionService's recovery path for zadam/trilium#510, which hands back what it was given —+ * and only under Node, since that path is selected by a Node crypto error message. Nothing writes a+ * value of that shape here ({@link encryptTextRepresentation} is the only writer and always emits real+ * ciphertext), so this is noted rather than defended against.+ */+function decryptTextRepresentation(textRepresentation: string | null | undefined, isProtected: boolean): string {+ if (!textRepresentation) {+ return "";+ }++ if (!isProtected) {+ return textRepresentation;+ }++ if (!protectedSessionService.isProtectedSessionAvailable()) {+ return "";+ }++ try {+ return protectedSessionService.decryptString(textRepresentation) || "";+ } catch {+ getLog().info("Cannot decrypt the text representation of a protected blob.");+ return "";+ }+}+function calculateContentHash({ blobId, content, textRepresentation }: Pick<BlobRow, "blobId" | "content" | "textRepresentation">) {const textRepresentationSegment = textRepresentation ? `|${textRepresentation}` : "";return hash(`${blobId}|${content.toString()}${textRepresentationSegment}`);@@ -142,5 +183,6 @@ export default {getDeletedNoteBlobPojo,processContent,encryptTextRepresentation,+ decryptTextRepresentation,calculateContentHash};diff --git a/packages/trilium-core/src/services/llm/tools/attachment_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/attachment_tools.spec.tsindex ecae0e25f2..4f546d0416 100644--- a/packages/trilium-core/src/services/llm/tools/attachment_tools.spec.ts+++ b/packages/trilium-core/src/services/llm/tools/attachment_tools.spec.ts@@ -12,9 +12,14 @@ vi.mock("../../../becca/becca.js", async (importOriginal) => {return { default: { ...actual.default, getAttachment: getAttachmentMock, getBlob: getBlobMock } };});+import blobService from "../../blob.js";+import protectedSessionService from "../../protected_session.js";+import { encodeUtf8 } from "../../utils/binary.js";import { attachmentTools } from "./attachment_tools.js";import type { ToolDefinition } from "./tool_registry.js";+const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+function getTool(name: string): ToolDefinition {for (const [n, def] of attachmentTools) {if (n === name) return def;@@ -89,6 +94,33 @@ describe("attachment_tools", () => {});});+ it("decrypts a protected attachment's OCR text, and withholds it when locked", () => {+ getAttachmentMock.mockReturnValue(stubAttachment({+ hasStringContent: () => false,+ mime: "image/png",+ blobId: "blob1",+ isProtected: true+ }));++ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ getBlobMock.mockReturnValue({+ textRepresentation: blobService.encryptTextRepresentation("OCR extracted", true)+ });+ expect(getTool("get_attachment_content").execute({ attachmentId: "att1" })).toEqual({+ attachmentId: "att1",+ source: "ocr",+ content: "OCR extracted"+ });+ } finally {+ protectedSessionService.resetDataKey();+ }++ // Locked: reported as unreadable rather than answered with the ciphertext.+ expect(getTool("get_attachment_content").execute({ attachmentId: "att1" }))+ .toEqual({ error: "Attachment has no readable text content" });+ });+it("returns an error for binary attachments with no readable text (no blobId, or empty blob)", () => {// No blobId at all → getBlob is never consulted.getAttachmentMock.mockReturnValue(stubAttachment({diff --git a/packages/trilium-core/src/services/llm/tools/attachment_tools.ts b/packages/trilium-core/src/services/llm/tools/attachment_tools.tsindex e5d57681a1..8414d08860 100644--- a/packages/trilium-core/src/services/llm/tools/attachment_tools.ts+++ b/packages/trilium-core/src/services/llm/tools/attachment_tools.ts@@ -6,6 +6,7 @@ import { unwrapStringOrBuffer } from "../../../services/utils/binary.js";import { z } from "zod";import becca from "../../../becca/becca.js";+import blobService from "../../../services/blob.js";import { defineTools } from "./tool_registry.js";export const attachmentTools = defineTools({@@ -54,11 +55,12 @@ export const attachmentTools = defineTools({// For binary attachments, try OCR/extracted text from the blob.const blob = attachment.blobId ? becca.getBlob({ blobId: attachment.blobId }) : null;- if (blob?.textRepresentation) {+ const extractedText = blobService.decryptTextRepresentation(blob?.textRepresentation, !!attachment.isProtected);+ if (extractedText) {return {attachmentId: attachment.attachmentId,source: "ocr" as const,- content: blob.textRepresentation+ content: extractedText};}diff --git a/packages/trilium-core/src/services/llm/tools/helpers.spec.ts b/packages/trilium-core/src/services/llm/tools/helpers.spec.tsindex 054d7d3c51..8cc67467d6 100644--- a/packages/trilium-core/src/services/llm/tools/helpers.spec.ts+++ b/packages/trilium-core/src/services/llm/tools/helpers.spec.ts@@ -12,6 +12,9 @@ vi.mock("../../../becca/becca.js", async (importOriginal) => {return { default: { ...actual.default, getBlob: getBlobMock } };});+import blobService from "../../blob.js";+import protectedSessionService from "../../protected_session.js";+import { encodeUtf8 } from "../../utils/binary.js";import {applyTextEdits,flag,@@ -58,6 +61,8 @@ function docNoteStub(docName: string | null) {});}+const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes+function attachmentStub(overrides: Partial<Record<string, unknown>> = {}): BAttachment {return {attachmentId: "a1",@@ -99,6 +104,23 @@ describe("getNoteContentForLlm", () => {expect(getNoteContentForLlm(note)).toBe("[extracted text from image]\nscanned words");});+ it("decrypts a protected note's extracted text, and withholds it when locked", () => {+ const note = noteStub({ type: "image", isProtected: true, getContent: () => new Uint8Array([1, 2, 3]) });++ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ getBlobMock.mockReturnValue({+ textRepresentation: blobService.encryptTextRepresentation("scanned secret", true)+ });+ expect(getNoteContentForLlm(note)).toBe("[extracted text from image]\nscanned secret");+ } finally {+ protectedSessionService.resetDataKey();+ }++ // Locked, with the same blob still in hand: the model must not be fed the ciphertext.+ expect(getNoteContentForLlm(note)).toBe("[binary content]");+ });+it("falls back to a binary-content marker when no extracted text exists", () => {const noBlob = noteStub({ type: "image", blobId: "", getContent: () => new Uint8Array([1]) });expect(getNoteContentForLlm(noBlob)).toBe("[binary content]");@@ -205,6 +227,22 @@ describe("getAttachmentContentPreview", () => {expect(getAttachmentContentPreview(att)).toBe("ocr text");});+ it("decrypts a protected attachment's extracted text, and withholds it when locked", () => {+ const att = attachmentStub({ hasStringContent: () => false, mime: "image/png", isProtected: true });++ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ getBlobMock.mockReturnValue({+ textRepresentation: blobService.encryptTextRepresentation("ocr secret", true)+ });+ expect(getAttachmentContentPreview(att)).toBe("ocr secret");+ } finally {+ protectedSessionService.resetDataKey();+ }++ expect(getAttachmentContentPreview(att)).toBeNull();+ });+it("returns null when no readable text exists", () => {// Binary without blob.const noBlob = attachmentStub({ hasStringContent: () => false, blobId: "" });diff --git a/packages/trilium-core/src/services/llm/tools/helpers.ts b/packages/trilium-core/src/services/llm/tools/helpers.tsindex 5bc1fb3bb6..703d01e10e 100644--- a/packages/trilium-core/src/services/llm/tools/helpers.ts+++ b/packages/trilium-core/src/services/llm/tools/helpers.ts@@ -5,6 +5,7 @@import type BAttachment from "../../../becca/entities/battachment.js";import becca from "../../../becca/becca.js";import type BNote from "../../../becca/entities/bnote.js";+import blobService from "../../../services/blob.js";import markdownExport from "../../../services/export/markdown.js";import markdownImport from "../../../services/import/markdown.js";import { unwrapStringOrBuffer } from "../../../services/utils/binary.js";@@ -66,8 +67,9 @@ export function getNoteContentForLlm(note: BNote) {if (typeof content !== "string") {// For binary content (images, files), use extracted text if available.const blob = note.blobId ? becca.getBlob({ blobId: note.blobId }) : null;- if (blob?.textRepresentation) {- return `[extracted text from ${note.type}]\n${blob.textRepresentation}`;+ const extractedText = blobService.decryptTextRepresentation(blob?.textRepresentation, !!note.isProtected);+ if (extractedText) {+ return `[extracted text from ${note.type}]\n${extractedText}`;}return "[binary content]";}@@ -184,7 +186,7 @@ export function getAttachmentContentPreview(att: BAttachment): string | null {text = unwrapStringOrBuffer(content);} else {const blob = att.blobId ? becca.getBlob({ blobId: att.blobId }) : null;- text = blob?.textRepresentation ?? null;+ text = blobService.decryptTextRepresentation(blob?.textRepresentation, !!att.isProtected) || null;}if (!text) {