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): extract text from protected notes and attachments
Elian Doranb1e275857f7e
diff --git a/apps/server/src/services/ocr/ocr_service.spec.ts b/apps/server/src/services/ocr/ocr_service.spec.tsindex af97feae35..791fe861fd 100644--- a/apps/server/src/services/ocr/ocr_service.spec.ts+++ b/apps/server/src/services/ocr/ocr_service.spec.ts@@ -40,7 +40,9 @@ const mockBecca = {};const mockBlobService = {- calculateContentHash: vi.fn().mockReturnValue('hash123')+ calculateContentHash: vi.fn().mockReturnValue('hash123'),+ // Stands in for the real encryption: distinguishable from the plain text, and reversible by eye.+ encryptTextRepresentation: vi.fn((text: string, isProtected: boolean) => (isProtected ? `encrypted(${text})` : text))};const mockEntityChangesService = {@@ -237,15 +239,15 @@ describe('OCRService', () => {});describe('storeOCRResult', () => {- it('should store OCR result in blob successfully', () => {- const ocrResult = {- text: 'Sample text',- confidence: 0.95,- extractedAt: '2025-06-10T10:00:00.000Z',- language: 'eng'- };+ const ocrResult = {+ text: 'Sample text',+ confidence: 0.95,+ extractedAt: '2025-06-10T10:00:00.000Z',+ language: 'eng'+ };- ocrService.storeOCRResult('blob123', ocrResult);+ it('should store OCR result in blob successfully', () => {+ ocrService.storeOCRResult('blob123', ocrResult, false);expect(mockSql.execute).toHaveBeenCalledWith(expect.stringContaining('UPDATE blobs SET textRepresentation = ?'),@@ -253,15 +255,18 @@ describe('OCRService', () => {);});- it('should handle undefined blobId gracefully', () => {- const ocrResult = {- text: 'Sample text',- confidence: 0.95,- extractedAt: '2025-06-10T10:00:00.000Z',- language: 'eng'- };+ it('encrypts the text before storing it on a protected blob', () => {+ ocrService.storeOCRResult('blob123', ocrResult, true);- ocrService.storeOCRResult(undefined, ocrResult);+ expect(mockBlobService.encryptTextRepresentation).toHaveBeenCalledWith('Sample text', true);+ expect(mockSql.execute).toHaveBeenCalledWith(+ expect.stringContaining('UPDATE blobs SET textRepresentation = ?'),+ ['encrypted(Sample text)', 'blob123']+ );+ });++ it('should handle undefined blobId gracefully', () => {+ ocrService.storeOCRResult(undefined, ocrResult, false);expect(mockSql.execute).not.toHaveBeenCalled();expect(mockLog.error).toHaveBeenCalledWith('Cannot store OCR result: blobId is undefined');@@ -273,16 +278,18 @@ describe('OCRService', () => {throw error;});- const ocrResult = {- text: 'Sample text',- confidence: 0.95,- extractedAt: '2025-06-10T10:00:00.000Z',- language: 'eng'- };-- expect(() => ocrService.storeOCRResult('blob123', ocrResult)).toThrow('Database error');+ expect(() => ocrService.storeOCRResult('blob123', ocrResult, false)).toThrow('Database error');expect(mockLog.error).toHaveBeenCalledWith('Failed to store OCR result for blob blob123: Error: Database error');});++ it('propagates an encryption failure instead of storing the text unencrypted', () => {+ mockBlobService.encryptTextRepresentation.mockImplementationOnce(() => {+ throw new Error('Cannot encrypt the text representation since protected session is not available.');+ });++ expect(() => ocrService.storeOCRResult('blob123', ocrResult, true)).toThrow('Cannot encrypt');+ expect(mockSql.execute).not.toHaveBeenCalled();+ });});describe('processNoteOCR', () => {@@ -291,6 +298,8 @@ describe('OCRService', () => {type: 'image',mime: 'image/jpeg',blobId: 'blob123',+ isProtected: false,+ isContentAvailable: vi.fn(),getContent: vi.fn(),getLabelValue: vi.fn().mockReturnValue(null)};@@ -298,6 +307,8 @@ describe('OCRService', () => {beforeEach(() => {mockBecca.getNote.mockReturnValue(mockNote);mockNote.getContent.mockReturnValue(Buffer.from('fake-image-data'));+ mockNote.isContentAvailable.mockReturnValue(true);+ mockNote.isProtected = false;mockNote.mime = 'image/jpeg';});@@ -385,17 +396,55 @@ describe('OCRService', () => {expect(mockLog.info).toHaveBeenCalledWith('OCR already exists for note note123, skipping');});- it('should throw when content is not a Buffer', async () => {- mockNote.getContent.mockReturnValue('not a buffer');+ it('should throw when the content holds no recognisable bytes', async () => {+ // String content has no binary form, and an empty buffer has nothing to recognise.+ for (const content of ['not a buffer', Buffer.alloc(0), new Uint8Array(0)]) {+ mockNote.getContent.mockReturnValue(content);++ await expect(ocrService.processNoteOCR('note123')).rejects.toThrow(+ 'Cannot get content for note note123'+ );+ }- await expect(ocrService.processNoteOCR('note123')).rejects.toThrow(- 'Cannot get content for note note123'- );expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('Failed to process OCR for note note123'));});+ it('recognises a protected note and stores the extracted text encrypted', async () => {+ mockNote.isProtected = true;+ mockSql.getRow.mockReturnValue(null);+ // Decryption hands back a plain Uint8Array rather than a Buffer — the same bytes, and they+ // must reach the processor rather than being rejected as unreadable content.+ mockNote.getContent.mockReturnValue(Uint8Array.from(Buffer.from('decrypted-image-data')));+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'Secret text', confidence: 90, words: [] }+ });++ const result = await ocrService.processNoteOCR('note123');++ expect(result?.text).toBe('Secret text');+ expect(mockBlobService.encryptTextRepresentation).toHaveBeenCalledWith('Secret text', true);+ expect(mockSql.execute).toHaveBeenCalledWith(+ expect.stringContaining('UPDATE blobs SET textRepresentation = ?'),+ ['encrypted(Secret text)', 'blob123']+ );+ });++ it('skips a protected note when no protected session is available', async () => {+ mockNote.isProtected = true;+ mockNote.isContentAvailable.mockReturnValue(false);++ const result = await ocrService.processNoteOCR('note123');++ expect(result).toBeNull();+ expect(mockNote.getContent).not.toHaveBeenCalled();+ expect(mockSql.execute).not.toHaveBeenCalled();+ expect(mockLog.info).toHaveBeenCalledWith(+ 'note note123 is protected and no protected session is available, skipping OCR'+ );+ });+it('processes a note whose blobId is undefined', async () => {(mockNote as any).blobId = undefined;mockSql.getRow.mockReturnValue(null);@@ -431,6 +480,8 @@ describe('OCRService', () => {role: 'image',mime: 'image/png',blobId: 'blob456',+ isProtected: false,+ isContentAvailable: vi.fn(),getContent: vi.fn()};@@ -438,6 +489,8 @@ describe('OCRService', () => {mockBecca.getAttachment.mockReturnValue(mockAttachment);mockBecca.getNote.mockReturnValue({ getLabelValue: vi.fn().mockReturnValue(null) });mockAttachment.getContent.mockReturnValue(Buffer.from('fake-image-data'));+ mockAttachment.isContentAvailable.mockReturnValue(true);+ mockAttachment.isProtected = false;});it('should process attachment OCR successfully', async () => {@@ -467,6 +520,36 @@ describe('OCRService', () => {expect(result).toBe(null);expect(mockLog.error).toHaveBeenCalledWith('Attachment nonexistent not found');});++ it('recognises a protected attachment and stores the extracted text encrypted', async () => {+ mockAttachment.isProtected = true;+ mockSql.getRow.mockReturnValue(null);+ mockAttachment.getContent.mockReturnValue(Uint8Array.from(Buffer.from('decrypted-image-data')));+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'Secret attachment text', confidence: 92, words: [] }+ });++ const result = await ocrService.processAttachmentOCR('attach123');++ expect(result?.text).toBe('Secret attachment text');+ expect(mockSql.execute).toHaveBeenCalledWith(+ expect.stringContaining('UPDATE blobs SET textRepresentation = ?'),+ ['encrypted(Secret attachment text)', 'blob456']+ );+ });++ it('skips a protected attachment when no protected session is available', async () => {+ mockAttachment.isProtected = true;+ mockAttachment.isContentAvailable.mockReturnValue(false);++ const result = await ocrService.processAttachmentOCR('attach123');++ expect(result).toBeNull();+ expect(mockAttachment.getContent).not.toHaveBeenCalled();+ expect(mockLog.info).toHaveBeenCalledWith(+ 'attachment attach123 is protected and no protected session is available, skipping OCR'+ );+ });});describe('Batch Processing', () => {diff --git a/apps/server/src/services/ocr/ocr_service.ts b/apps/server/src/services/ocr/ocr_service.tsindex 8b9364afdd..6a21985f65 100644--- a/apps/server/src/services/ocr/ocr_service.ts+++ b/apps/server/src/services/ocr/ocr_service.ts@@ -1,6 +1,7 @@import { getTesseractCode } from '@triliumnext/commons';import { becca, blob as blobService, entity_changes as entityChangesService, getLog, options } from '@triliumnext/core';+import { asBuffer } from '../image_codec.js';import sql from '../sql.js';import { FileProcessor } from './processors/file_processor.js';import { ImageProcessor } from './processors/image_processor.js';@@ -135,6 +136,8 @@ class OCRService {category: note.type,mime: note.mime,blobId: note.blobId,+ isProtected: !!note.isProtected,+ isContentAvailable: note.isContentAvailable(),languageNoteId: noteId,getContent: () => note.getContent()}, options);@@ -156,6 +159,8 @@ class OCRService {category: attachment.role,mime: attachment.mime,blobId: attachment.blobId,+ isProtected: !!attachment.isProtected,+ isContentAvailable: attachment.isContentAvailable(),languageNoteId: attachment.ownerId,getContent: () => attachment.getContent()}, options);@@ -170,10 +175,12 @@ class OCRService {category: string;mime: string;blobId: string | undefined;+ isProtected: boolean;+ isContentAvailable: boolean;languageNoteId: string;getContent: () => string | Uint8Array;}, options: OCRProcessingOptions = {}): Promise<OCRResult | null> {- const { entityId, entityType, category, mime, blobId, languageNoteId } = entity;+ const { entityId, entityType, category, mime, blobId, isProtected, isContentAvailable, languageNoteId } = entity;if (!['image', 'file'].includes(category)) {getLog().info(`${entityType} ${entityId} is not an image or file, skipping OCR`);@@ -190,16 +197,23 @@ class OCRService {return null;}+ // Without the key the content is not readable, so there is nothing to recognise. This is an+ // ordinary skip rather than a failure: the entity is picked up again once the vault is open.+ if (!isContentAvailable) {+ getLog().info(`${entityType} ${entityId} is protected and no protected session is available, skipping OCR`);+ return null;+ }+try {- const content = entity.getContent();- if (!content || !(content instanceof Buffer)) {+ const content = toBinaryContent(entity.getContent());+ if (!content) {throw new Error(`Cannot get content for ${entityType} ${entityId}`);}const language = this.resolveOcrLanguage(languageNoteId, options.language);const ocrResult = await this.extractTextFromFile(content, mime, { ...options, language });- this.storeOCRResult(blobId, ocrResult);+ this.storeOCRResult(blobId, ocrResult, isProtected);return ocrResult;} catch (error) {@@ -209,19 +223,24 @@ class OCRService {}/**- * Store OCR result in blob+ * Store OCR result in blob.+ *+ * The text is encrypted for a protected entity, since it is a readable rendering of content that+ * is itself only stored encrypted.*/- storeOCRResult(blobId: string | undefined, ocrResult: OCRResult): void {+ storeOCRResult(blobId: string | undefined, ocrResult: OCRResult, isProtected: boolean): void {if (!blobId) {getLog().error('Cannot store OCR result: blobId is undefined');return;}try {+ const textRepresentation = blobService.encryptTextRepresentation(ocrResult.text, isProtected);+sql.execute(`UPDATE blobs SET textRepresentation = ?WHERE blobId = ?- `, [ocrResult.text, blobId]);+ `, [textRepresentation, blobId]);this.putBlobEntityChange(blobId);@@ -463,3 +482,21 @@ class OCRService {}export default new OCRService();++/**+ * Narrows an entity's content to the `Buffer` the processors take, or null when there are no bytes to+ * recognise — a string has no binary form, and neither does an empty buffer.+ *+ * The conversion matters because the two kinds of content arrive differently typed. Unprotected+ * content is already a `Buffer`: better-sqlite3 returns one for a BLOB column and nothing rewraps it+ * on the way through Becca. Protected content is decrypted on the way out, and the decryption builds+ * its result with `new Uint8Array(...)`, which is not a `Buffer` — so testing for one rejected every+ * protected image as unreadable. Same bytes either way, so wrap rather than reject.+ */+function toBinaryContent(content: string | Uint8Array): Buffer | null {+ if (typeof content === "string" || content.byteLength === 0) {+ return null;+ }++ return asBuffer(content);+}diff --git a/packages/trilium-core/src/services/blob.spec.ts b/packages/trilium-core/src/services/blob.spec.tsindex 7d99018b15..fd87fc5046 100644--- a/packages/trilium-core/src/services/blob.spec.ts+++ b/packages/trilium-core/src/services/blob.spec.ts@@ -125,6 +125,34 @@ describe("blob", () => {});});+ describe("encryptTextRepresentation", () => {+ it("passes unprotected text through untouched", () => {+ protectedSessionService.resetDataKey();+ expect(blob.encryptTextRepresentation("extracted text", false)).toBe("extracted text");+ });++ it("encrypts protected text with the data key", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ const encrypted = blob.encryptTextRepresentation("text read out of a protected image", true);++ // The stored value must not contain the readable text...+ expect(encrypted).not.toContain("protected image");+ // ...and must decrypt back to it with the data key.+ const decrypted = dataEncryption.decrypt(PROTECTED_KEY, encrypted);+ expect(decrypted).toBeInstanceOf(Uint8Array);+ expect(decodeUtf8(decrypted as Uint8Array)).toBe("text read out of a protected image");+ } finally {+ protectedSessionService.resetDataKey();+ }+ });++ it("throws rather than storing protected text when no protected session is available", () => {+ protectedSessionService.resetDataKey();+ expect(() => blob.encryptTextRepresentation("secret", true)).toThrow(/protected session is not available/);+ });+ });+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 acbface40a..8e7c5f4700 100644--- a/packages/trilium-core/src/services/blob.ts+++ b/packages/trilium-core/src/services/blob.ts@@ -105,6 +105,33 @@ function processContent(content: Uint8Array | string | null, isProtected: booleareturn content;}+/**+ * Prepares OCR-extracted text for storage on a blob.+ *+ * The text is a readable copy of what the blob holds, so for a protected entity it has to be encrypted+ * at rest exactly like the content it was derived from — otherwise protecting a note would hide the+ * image while leaving everything written in it in the clear. The counterpart on the way out is+ * {@link processContent}'s handling of `content`: decrypt when a session is available, blank otherwise.+ *+ * A blob's protection state is unambiguous even though the `blobs` table does not record it: a+ * protected entity's blobId is hashed with an `_ENCRYPTED_` prefix (see+ * `AbstractBeccaEntity.getUnencryptedContentForHashCalculation`), so a blob is never shared between a+ * protected and an unprotected entity. Any one of its referencing entities therefore answers for all.+ */+function encryptTextRepresentation(textRepresentation: string, isProtected: boolean): string {+ if (!isProtected) {+ return textRepresentation;+ }++ const encrypted = protectedSessionService.encrypt(textRepresentation);++ if (!encrypted) {+ throw new Error("Cannot encrypt the text representation since protected session is not available.");+ }++ return encrypted;+}+function calculateContentHash({ blobId, content, textRepresentation }: Pick<BlobRow, "blobId" | "content" | "textRepresentation">) {const textRepresentationSegment = textRepresentation ? `|${textRepresentation}` : "";return hash(`${blobId}|${content.toString()}${textRepresentationSegment}`);@@ -114,5 +141,6 @@ export default {getBlobPojo,getDeletedNoteBlobPojo,processContent,+ encryptTextRepresentation,calculateContentHash};