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
chore(server): integrate data_encryption, and protected_session
Elian Doranc1548b0f5467
diff --git a/apps/server/src/becca/entities/abstract_becca_entity.ts b/apps/server/src/becca/entities/abstract_becca_entity.tsindex 1f3bd0d863..3b30eccd82 100644--- a/apps/server/src/becca/entities/abstract_becca_entity.ts+++ b/apps/server/src/becca/entities/abstract_becca_entity.ts@@ -1,16 +1,14 @@-"use strict";--import utils from "../../services/utils.js";-import sql from "../../services/sql.js";+import blobService from "../../services/blob.js";+import cls from "../../services/cls.js";+import dateUtils from "../../services/date_utils.js";import entityChangesService from "../../services/entity_changes.js";import eventService from "../../services/events.js";-import dateUtils from "../../services/date_utils.js";-import cls from "../../services/cls.js";import log from "../../services/log.js";import protectedSessionService from "../../services/protected_session.js";-import blobService from "../../services/blob.js";-import type { default as Becca, ConstructorData } from "../becca-interface.js";+import sql from "../../services/sql.js";+import utils from "../../services/utils.js";import becca from "../becca.js";+import type { ConstructorData,default as Becca } from "../becca-interface.js";interface ContentOpts {forceSave?: boolean;@@ -206,9 +204,9 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {// a "random" prefix makes sure that the calculated hash/blobId is different for a decrypted/encrypted contentconst encryptedPrefixSuffix = "t$[nvQg7q)&_ENCRYPTED_?M:Bf&j3jr_";return Buffer.isBuffer(unencryptedContent) ? Buffer.concat([Buffer.from(encryptedPrefixSuffix), unencryptedContent]) : `${encryptedPrefixSuffix}${unencryptedContent}`;- } else {- return unencryptedContent;}+ return unencryptedContent;+}private saveBlob(content: string | Buffer, unencryptedContentForHashCalculation: string | Buffer, opts: ContentOpts = {}) {@@ -227,7 +225,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {const pojo = {blobId: newBlobId,- content: content,+ content,dateModified: dateUtils.localNowDateTime(),utcDateModified: dateUtils.utcNowDateTime()};@@ -241,7 +239,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {entityChangesService.putEntityChange({entityName: "blobs",entityId: newBlobId,- hash: hash,+ hash,isErased: false,utcDateChanged: pojo.utcDateModified,isSynced: true,@@ -266,7 +264,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {throw new Error(`Cannot find content for ${constructorData.primaryKeyName} '${(this as any)[constructorData.primaryKeyName]}', blobId '${this.blobId}'`);}- return blobService.processContent(row.content, this.isProtected || false, this.hasStringContent());+ return blobService.processContent(row.content, this.isProtected || false, this.hasStringContent()) as string | Buffer;}/**diff --git a/apps/server/src/crypto_provider.ts b/apps/server/src/crypto_provider.tsnew file mode 100644index 0000000000..c51b7bc9dd--- /dev/null+++ b/apps/server/src/crypto_provider.ts@@ -0,0 +1,22 @@+import { CryptoProvider } from "@triliumnext/core";+import crypto from "crypto";++export default class NodejsCryptoProvider implements CryptoProvider {++ createHash(algorithm: "sha1", content: string | Uint8Array): Uint8Array {+ return crypto.createHash(algorithm).update(content).digest();+ }++ createCipheriv(algorithm: "aes-128-cbc", key: Uint8Array, iv: Uint8Array): { update(data: Uint8Array): Uint8Array; final(): Uint8Array; } {+ return crypto.createCipheriv(algorithm, key, iv);+ }++ createDecipheriv(algorithm: "aes-128-cbc", key: Uint8Array, iv: Uint8Array) {+ return crypto.createDecipheriv(algorithm, key, iv);+ }++ randomBytes(size: number): Uint8Array {+ return crypto.randomBytes(size);+ }++}diff --git a/apps/server/src/main.ts b/apps/server/src/main.tsindex 38e602e8e4..5d9bb8033c 100644--- a/apps/server/src/main.ts+++ b/apps/server/src/main.ts@@ -6,6 +6,7 @@import { initializeCore } from "@triliumnext/core";import ClsHookedExecutionContext from "./cls_provider.js";+import NodejsCryptoProvider from "./crypto_provider.js";import BetterSqlite3Provider from "./sql_provider.js";async function startApplication() {@@ -41,6 +42,7 @@ async function startApplication() {entity_changes.recalculateMaxEntityChangeId();}},+ crypto: new NodejsCryptoProvider(),executionContext: new ClsHookedExecutionContext()});const { initializeTranslations } = (await import("./services/i18n.js"));diff --git a/apps/server/src/services/blob.ts b/apps/server/src/services/blob.tsindex c4684c2ae5..6804f1ecb5 100644--- a/apps/server/src/services/blob.ts+++ b/apps/server/src/services/blob.ts@@ -1,8 +1,10 @@+import { binary_utils } from "@triliumnext/core";+import becca from "../becca/becca.js";import NotFoundError from "../errors/not_found_error.js";+import type { Blob } from "./blob-interface.js";import protectedSessionService from "./protected_session.js";import { hash } from "./utils.js";-import type { Blob } from "./blob-interface.js";function getBlobPojo(entityName: string, entityId: string, opts?: { preview: boolean }) {// TODO: Unused opts.@@ -21,33 +23,32 @@ function getBlobPojo(entityName: string, entityId: string, opts?: { preview: booif (!entity.hasStringContent()) {pojo.content = null;} else {- pojo.content = processContent(pojo.content, !!entity.isProtected, true);+ pojo.content = processContent(pojo.content, !!entity.isProtected, true) as string | Buffer;}return pojo;}-function processContent(content: Buffer | string | null, isProtected: boolean, isStringContent: boolean) {+function processContent(content: Buffer | Uint8Array | string | null, isProtected: boolean, isStringContent: boolean) {if (isProtected) {if (protectedSessionService.isProtectedSessionAvailable()) {- content = content === null ? null : protectedSessionService.decrypt(content);+ content = content === null ? null : protectedSessionService.decrypt(content as Uint8Array);} else {content = "";}}if (isStringContent) {- return content === null ? "" : content.toString("utf-8");- } else {- // see https://github.com/zadam/trilium/issues/3523- // IIRC a zero-sized buffer can be returned as null from the database- if (content === null) {- // this will force de/encryption- content = Buffer.alloc(0);- }-- return content;+ return content === null ? "" : binary_utils.decodeUtf8(content as Uint8Array);}+ // see https://github.com/zadam/trilium/issues/3523+ // IIRC a zero-sized buffer can be returned as null from the database+ if (content === null) {+ // this will force de/encryption+ content = Buffer.alloc(0);+ }++ return content;}function calculateContentHash({ blobId, content }: Blob) {diff --git a/apps/server/src/services/encryption/data_encryption.ts b/apps/server/src/services/encryption/data_encryption.tsdeleted file mode 100644index 250db687b2..0000000000--- a/apps/server/src/services/encryption/data_encryption.ts+++ /dev/null@@ -1,114 +0,0 @@-import crypto from "crypto";-import log from "../log.js";--function arraysIdentical(a: any[] | Buffer, b: any[] | Buffer) {- let i = a.length;- if (i !== b.length) return false;- while (i--) {- if (a[i] !== b[i]) return false;- }- return true;-}--function shaArray(content: crypto.BinaryLike) {- // we use this as a simple checksum and don't rely on its security, so SHA-1 is good enough- return crypto.createHash("sha1").update(content).digest();-}--function pad(data: Buffer): Buffer {- if (data.length > 16) {- data = data.slice(0, 16);- } else if (data.length < 16) {- const zeros = Array(16 - data.length).fill(0);-- data = Buffer.concat([data, Buffer.from(zeros)]);- }-- return Buffer.from(data);-}--function encrypt(key: Buffer, plainText: Buffer | string) {- if (!key) {- throw new Error("No data key!");- }-- const plainTextBuffer = Buffer.isBuffer(plainText) ? plainText : Buffer.from(plainText);-- const iv = crypto.randomBytes(16);- const cipher = crypto.createCipheriv("aes-128-cbc", pad(key), pad(iv));-- const digest = shaArray(plainTextBuffer).slice(0, 4);-- const digestWithPayload = Buffer.concat([digest, plainTextBuffer]);-- const encryptedData = Buffer.concat([cipher.update(digestWithPayload), cipher.final()]);-- const encryptedDataWithIv = Buffer.concat([iv, encryptedData]);-- return encryptedDataWithIv.toString("base64");-}--function decrypt(key: Buffer, cipherText: string | Buffer): Buffer | false | null {- if (cipherText === null) {- return null;- }-- if (!key) {- return Buffer.from("[protected]");- }-- try {- const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), "base64");-- // old encrypted data can have IV of length 13, see some details here: https://github.com/zadam/trilium/issues/3017- const ivLength = cipherTextBufferWithIv.length % 16 === 0 ? 16 : 13;-- const iv = cipherTextBufferWithIv.slice(0, ivLength);-- const cipherTextBuffer = cipherTextBufferWithIv.slice(ivLength);-- const decipher = crypto.createDecipheriv("aes-128-cbc", pad(key), pad(iv));-- const decryptedBytes = Buffer.concat([decipher.update(cipherTextBuffer), decipher.final()]);-- const digest = decryptedBytes.slice(0, 4);- const payload = decryptedBytes.slice(4);-- const computedDigest = shaArray(payload).slice(0, 4);-- if (!arraysIdentical(digest, computedDigest)) {- return false;- }-- return payload;- } catch (e: any) {- // recovery from https://github.com/zadam/trilium/issues/510- if (e.message?.includes("WRONG_FINAL_BLOCK_LENGTH") || e.message?.includes("wrong final block length")) {- log.info("Caught WRONG_FINAL_BLOCK_LENGTH, returning cipherText instead");-- return (Buffer.isBuffer(cipherText) ? cipherText : Buffer.from(cipherText));- } else {- throw e;- }- }-}--function decryptString(dataKey: Buffer, cipherText: string) {- const buffer = decrypt(dataKey, cipherText);-- if (buffer === null) {- return null;- } else if (buffer === false) {- log.error(`Could not decrypt string. Buffer: ${buffer}`);-- throw new Error("Could not decrypt string.");- }-- return buffer.toString("utf-8");-}--export default {- encrypt,- decrypt,- decryptString-};diff --git a/apps/server/src/services/encryption/open_id_encryption.ts b/apps/server/src/services/encryption/open_id_encryption.tsindex 5ba14ca829..a191b782b3 100644--- a/apps/server/src/services/encryption/open_id_encryption.ts+++ b/apps/server/src/services/encryption/open_id_encryption.ts@@ -1,9 +1,10 @@-import myScryptService from "./my_scrypt.js";-import utils, { constantTimeCompare } from "../utils.js";-import dataEncryptionService from "./data_encryption.js";+import { data_encryption } from "@triliumnext/core";++import OpenIdError from "../../errors/open_id_error.js";import sql from "../sql.js";import sqlInit from "../sql_init.js";-import OpenIdError from "../../errors/open_id_error.js";+import utils, { constantTimeCompare } from "../utils.js";+import myScryptService from "./my_scrypt.js";function saveUser(subjectIdentifier: string, name: string, email: string) {if (isUserSaved()) return false;@@ -16,7 +17,7 @@ function saveUser(subjectIdentifier: string, name: string, email: string) {verificationSalt);if (!verificationHash) {- throw new OpenIdError("Verification hash undefined!")+ throw new OpenIdError("Verification hash undefined!");}const userIDEncryptedDataKey = setDataKey(@@ -35,10 +36,10 @@ function saveUser(subjectIdentifier: string, name: string, email: string) {userIDVerificationHash: utils.toBase64(verificationHash),salt: verificationSalt,derivedKey: derivedKeySalt,- userIDEncryptedDataKey: userIDEncryptedDataKey,+ userIDEncryptedDataKey,isSetup: "true",username: name,- email: email};sql.upsert("user_data", "tmpID", data);@@ -53,7 +54,7 @@ function isSubjectIdentifierSaved() {function isUserSaved() {const isSaved = sql.getValue<string>("SELECT isSetup FROM user_data;");- return isSaved === "true" ? true : false;+ return isSaved === "true";}function verifyOpenIDSubjectIdentifier(subjectIdentifier: string) {@@ -102,7 +103,7 @@ function setDataKey(console.error("SOMETHING WENT WRONG SAVING USER ID DERIVED KEY");return undefined;}- const newEncryptedDataKey = dataEncryptionService.encrypt(+ const newEncryptedDataKey = data_encryption.encrypt(subjectIdentifierDerivedKey,plainTextDataKey);@@ -127,7 +128,7 @@ function getDataKey(subjectIdentifier: string) {console.error("SOMETHING WENT WRONG SAVING USER ID DERIVED KEY");return undefined;}- const decryptedDataKey = dataEncryptionService.decrypt(+ const decryptedDataKey = data_encryption.decrypt(subjectIdentifierDerivedKey,encryptedDataKey.toString());diff --git a/apps/server/src/services/encryption/password_encryption.ts b/apps/server/src/services/encryption/password_encryption.tsindex 61e73495ce..7c126f3260 100644--- a/apps/server/src/services/encryption/password_encryption.ts+++ b/apps/server/src/services/encryption/password_encryption.ts@@ -1,7 +1,8 @@+import { data_encryption } from "@triliumnext/core";+import optionService from "../options.js";+import { constantTimeCompare,toBase64 } from "../utils.js";import myScryptService from "./my_scrypt.js";-import { toBase64, constantTimeCompare } from "../utils.js";-import dataEncryptionService from "./data_encryption.js";function verifyPassword(password: string) {const givenPasswordHash = toBase64(myScryptService.getVerificationHash(password));@@ -15,10 +16,10 @@ function verifyPassword(password: string) {return constantTimeCompare(givenPasswordHash, dbPasswordHash);}-function setDataKey(password: string, plainTextDataKey: string | Buffer) {+function setDataKey(password: string, plainTextDataKey: string | Buffer | Uint8Array) {const passwordDerivedKey = myScryptService.getPasswordDerivedKey(password);- const newEncryptedDataKey = dataEncryptionService.encrypt(passwordDerivedKey, plainTextDataKey);+ const newEncryptedDataKey = data_encryption.encrypt(passwordDerivedKey, plainTextDataKey);optionService.setOption("encryptedDataKey", newEncryptedDataKey);}@@ -28,7 +29,7 @@ function getDataKey(password: string) {const encryptedDataKey = optionService.getOption("encryptedDataKey");- const decryptedDataKey = dataEncryptionService.decrypt(passwordDerivedKey, encryptedDataKey);+ const decryptedDataKey = data_encryption.decrypt(passwordDerivedKey, encryptedDataKey);return decryptedDataKey;}diff --git a/apps/server/src/services/encryption/totp_encryption.ts b/apps/server/src/services/encryption/totp_encryption.tsindex 87f4cfef18..1d1297dc52 100644--- a/apps/server/src/services/encryption/totp_encryption.ts+++ b/apps/server/src/services/encryption/totp_encryption.ts@@ -1,8 +1,9 @@+import type { OptionNames } from "@triliumnext/commons";+import { data_encryption } from "@triliumnext/core";+import optionService from "../options.js";+import { constantTimeCompare,randomSecureToken, toBase64 } from "../utils.js";import myScryptService from "./my_scrypt.js";-import { randomSecureToken, toBase64, constantTimeCompare } from "../utils.js";-import dataEncryptionService from "./data_encryption.js";-import type { OptionNames } from "@triliumnext/commons";const TOTP_OPTIONS: Record<string, OptionNames> = {SALT: "totpEncryptionSalt",@@ -32,7 +33,7 @@ function setTotpSecret(secret: string) {const verificationHash = toBase64(myScryptService.getVerificationHash(secret));optionService.setOption(TOTP_OPTIONS.VERIFICATION_HASH, verificationHash);- const encryptedSecret = dataEncryptionService.encrypt(+ const encryptedSecret = data_encryption.encrypt(Buffer.from(encryptionSalt),secret);@@ -48,7 +49,7 @@ function getTotpSecret(): string | null {}try {- const decryptedSecret = dataEncryptionService.decrypt(+ const decryptedSecret = data_encryption.decrypt(Buffer.from(encryptionSalt),encryptedSecret);diff --git a/apps/server/src/services/protected_session.ts b/apps/server/src/services/protected_session.tsindex d69d318d1b..780b584b27 100644--- a/apps/server/src/services/protected_session.ts+++ b/apps/server/src/services/protected_session.ts@@ -1,69 +1,3 @@-"use strict";+import { protected_session } from "@triliumnext/core";-import dataEncryptionService from "./encryption/data_encryption.js";--let dataKey: Buffer | null = null;--function setDataKey(decryptedDataKey: Buffer) {- dataKey = Buffer.from(decryptedDataKey);-}--function getDataKey() {- return dataKey;-}--export function resetDataKey() {- dataKey = null;-}--export function isProtectedSessionAvailable() {- return !!dataKey;-}--function encrypt(plainText: string | Buffer) {- const dataKey = getDataKey();- if (plainText === null || dataKey === null) {- return null;- }-- return dataEncryptionService.encrypt(dataKey, plainText);-}--function decrypt(cipherText: string | Buffer): Buffer | null {- const dataKey = getDataKey();- if (cipherText === null || dataKey === null) {- return null;- }-- return dataEncryptionService.decrypt(dataKey, cipherText) || null;-}--function decryptString(cipherText: string): string | null {- const dataKey = getDataKey();- if (dataKey === null) {- return null;- }- return dataEncryptionService.decryptString(dataKey, cipherText);-}--let lastProtectedSessionOperationDate: number | null = null;--function touchProtectedSession() {- if (isProtectedSessionAvailable()) {- lastProtectedSessionOperationDate = Date.now();- }-}--export function getLastProtectedSessionOperationDate() {- return lastProtectedSessionOperationDate;-}--export default {- setDataKey,- resetDataKey,- isProtectedSessionAvailable,- encrypt,- decrypt,- decryptString,- touchProtectedSession-};+export default protected_session.default;diff --git a/apps/server/src/services/scheduler.ts b/apps/server/src/services/scheduler.tsindex f44e3aa430..0ed4236513 100644--- a/apps/server/src/services/scheduler.ts+++ b/apps/server/src/services/scheduler.ts@@ -1,13 +1,14 @@-import scriptService from "./script.js";+import { protected_session } from "@triliumnext/core";++import type BNote from "../becca/entities/bnote.js";+import attributeService from "../services/attributes.js";import cls from "./cls.js";-import sqlInit from "./sql_init.js";import config from "./config.js";-import log from "./log.js";-import attributeService from "../services/attributes.js";import hiddenSubtreeService from "./hidden_subtree.js";-import type BNote from "../becca/entities/bnote.js";+import log from "./log.js";import options from "./options.js";-import { getLastProtectedSessionOperationDate, isProtectedSessionAvailable, resetDataKey } from "./protected_session.js";+import scriptService from "./script.js";+import sqlInit from "./sql_init.js";import ws from "./ws.js";function getRunAtHours(note: BNote): number[] {@@ -71,9 +72,9 @@ sqlInit.dbReady.then(() => {function checkProtectedSessionExpiration() {const protectedSessionTimeout = options.getOptionInt("protectedSessionTimeout");- const lastProtectedSessionOperationDate = getLastProtectedSessionOperationDate();- if (isProtectedSessionAvailable() && lastProtectedSessionOperationDate && Date.now() - lastProtectedSessionOperationDate > protectedSessionTimeout * 1000) {- resetDataKey();+ const lastProtectedSessionOperationDate = protected_session.getLastProtectedSessionOperationDate();+ if (protected_session.isProtectedSessionAvailable() && lastProtectedSessionOperationDate && Date.now() - lastProtectedSessionOperationDate > protectedSessionTimeout * 1000) {+ protected_session.resetDataKey();log.info("Expiring protected session");ws.reloadFrontend("leaving protected session");}diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 733e1faf1e..eee6b2d65b 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -1,17 +1,24 @@import { ExecutionContext, initContext } from "./services/context";+import { CryptoProvider, initCrypto } from "./services/encryption/crypto";import { getLog, initLog } from "./services/log";import { initSql } from "./services/sql/index";import { SqlService, SqlServiceParams } from "./services/sql/sql";export type * from "./services/sql/types";export * from "./services/sql/index";+export * as protected_session from "./services/encryption/protected_session";+export { default as data_encryption } from "./services/encryption/data_encryption"+export * as binary_utils from "./services/utils/binary";export type { ExecutionContext } from "./services/context";+export type { CryptoProvider } from "./services/encryption/crypto";-export function initializeCore({ dbConfig, executionContext }: {+export function initializeCore({ dbConfig, executionContext, crypto }: {dbConfig: SqlServiceParams,- executionContext: ExecutionContext+ executionContext: ExecutionContext,+ crypto: CryptoProvider}) {initLog();+ initCrypto(crypto);initSql(new SqlService(dbConfig, getLog()));initContext(executionContext);};diff --git a/packages/trilium-core/src/services/encryption/crypto.ts b/packages/trilium-core/src/services/encryption/crypto.tsnew file mode 100644index 0000000000..94ebcb1ad9--- /dev/null+++ b/packages/trilium-core/src/services/encryption/crypto.ts@@ -0,0 +1,23 @@+interface Cipher {+ update(data: Uint8Array): Uint8Array;+ final(): Uint8Array;+}++export interface CryptoProvider {++ createHash(algorithm: "sha1", content: string | Uint8Array): Uint8Array;+ randomBytes(size: number): Uint8Array;+ createCipheriv(algorithm: "aes-128-cbc", key: Uint8Array, iv: Uint8Array): Cipher;+ createDecipheriv(algorithm: "aes-128-cbc", key: Uint8Array, iv: Uint8Array): Cipher;+}++let crypto: CryptoProvider | null = null;++export function initCrypto(cryptoProvider: CryptoProvider) {+ crypto = cryptoProvider;+}++export function getCrypto() {+ if (!crypto) throw new Error("Crypto not initialized.");+ return crypto;+}diff --git a/packages/trilium-core/src/services/encryption/data_encryption.ts b/packages/trilium-core/src/services/encryption/data_encryption.tsnew file mode 100644index 0000000000..e6bb9d1e84--- /dev/null+++ b/packages/trilium-core/src/services/encryption/data_encryption.ts@@ -0,0 +1,115 @@+import { getLog } from "../log.js";+import { concat2, decodeBase64, decodeUtf8, encodeBase64 } from "../utils/binary.js";+import { getCrypto } from "./crypto.js";++function arraysIdentical(a: any[] | Uint8Array, b: any[] | Uint8Array) {+ let i = a.length;+ if (i !== b.length) return false;+ while (i--) {+ if (a[i] !== b[i]) return false;+ }+ return true;+}++function shaArray(content: string | Uint8Array) {+ // we use this as a simple checksum and don't rely on its security, so SHA-1 is good enough+ return getCrypto().createHash("sha1", content);+}++function pad(data: Uint8Array): Uint8Array {+ if (data.length > 16) {+ data = data.slice(0, 16);+ } else if (data.length < 16) {+ const zeros = Array(16 - data.length).fill(0);++ data = concat2(data, Uint8Array.from(zeros));+ }++ return Uint8Array.from(data);+}++function encrypt(key: Uint8Array, plainText: Uint8Array | string) {+ if (!key) {+ throw new Error("No data key!");+ }++ const plainTextUint8Array = ArrayBuffer.isView(plainText) ? plainText : Uint8Array.from(plainText);++ const iv = getCrypto().randomBytes(16);+ const cipher = getCrypto().createCipheriv("aes-128-cbc", pad(key), pad(iv));++ const digest = shaArray(plainTextUint8Array).slice(0, 4);++ const digestWithPayload = concat2(digest, plainTextUint8Array);++ const encryptedData = concat2(cipher.update(digestWithPayload), cipher.final());++ const encryptedDataWithIv = concat2(iv, encryptedData);++ return encodeBase64(encryptedDataWithIv);+}++function decrypt(key: Uint8Array, cipherText: string | Uint8Array): Uint8Array | false | null {+ if (cipherText === null) {+ return null;+ }++ if (!key) {+ return Uint8Array.from("[protected]");+ }++ try {+ const cipherTextStr = typeof cipherText === "string" ? cipherText : decodeUtf8(cipherText);+ const cipherTextUint8ArrayWithIv = decodeBase64(cipherTextStr);++ // old encrypted data can have IV of length 13, see some details here: https://github.com/zadam/trilium/issues/3017+ const ivLength = cipherTextUint8ArrayWithIv.length % 16 === 0 ? 16 : 13;++ const iv = cipherTextUint8ArrayWithIv.slice(0, ivLength);++ const cipherTextUint8Array = cipherTextUint8ArrayWithIv.slice(ivLength);++ const decipher = getCrypto().createDecipheriv("aes-128-cbc", pad(key), pad(iv));++ const decryptedBytes = concat2(decipher.update(cipherTextUint8Array), decipher.final());++ const digest = decryptedBytes.slice(0, 4);+ const payload = decryptedBytes.slice(4);++ const computedDigest = shaArray(payload).slice(0, 4);++ if (!arraysIdentical(digest, computedDigest)) {+ return false;+ }++ return payload;+ } catch (e: any) {+ // recovery from https://github.com/zadam/trilium/issues/510+ if (e.message?.includes("WRONG_FINAL_BLOCK_LENGTH") || e.message?.includes("wrong final block length")) {+ getLog().info("Caught WRONG_FINAL_BLOCK_LENGTH, returning cipherText instead");++ return (ArrayBuffer.isView(cipherText) ? cipherText : Uint8Array.from(cipherText));+ }+ throw e;+ }+}++function decryptString(dataKey: Uint8Array, cipherText: string) {+ const buffer = decrypt(dataKey, cipherText);++ if (buffer === null) {+ return null;+ } else if (buffer === false) {+ getLog().error(`Could not decrypt string. Uint8Array: ${buffer}`);++ throw new Error("Could not decrypt string.");+ }++ return decodeUtf8(buffer);+}++export default {+ encrypt,+ decrypt,+ decryptString+};diff --git a/packages/trilium-core/src/services/encryption/protected_session.ts b/packages/trilium-core/src/services/encryption/protected_session.tsnew file mode 100644index 0000000000..ae4d69029b--- /dev/null+++ b/packages/trilium-core/src/services/encryption/protected_session.ts@@ -0,0 +1,69 @@+"use strict";++import dataEncryptionService from "./data_encryption.js";++let dataKey: Uint8Array | null = null;++function setDataKey(decryptedDataKey: Uint8Array) {+ dataKey = Uint8Array.from(decryptedDataKey);+}++function getDataKey() {+ return dataKey;+}++export function resetDataKey() {+ dataKey = null;+}++export function isProtectedSessionAvailable() {+ return !!dataKey;+}++function encrypt(plainText: string | Uint8Array) {+ const dataKey = getDataKey();+ if (plainText === null || dataKey === null) {+ return null;+ }++ return dataEncryptionService.encrypt(dataKey, plainText);+}++function decrypt(cipherText: string | Uint8Array): Uint8Array | null {+ const dataKey = getDataKey();+ if (cipherText === null || dataKey === null) {+ return null;+ }++ return dataEncryptionService.decrypt(dataKey, cipherText) || null;+}++function decryptString(cipherText: string): string | null {+ const dataKey = getDataKey();+ if (dataKey === null) {+ return null;+ }+ return dataEncryptionService.decryptString(dataKey, cipherText);+}++let lastProtectedSessionOperationDate: number | null = null;++function touchProtectedSession() {+ if (isProtectedSessionAvailable()) {+ lastProtectedSessionOperationDate = Date.now();+ }+}++export function getLastProtectedSessionOperationDate() {+ return lastProtectedSessionOperationDate;+}++export default {+ setDataKey,+ resetDataKey,+ isProtectedSessionAvailable,+ encrypt,+ decrypt,+ decryptString,+ touchProtectedSession+};diff --git a/packages/trilium-core/src/services/utils/binary.ts b/packages/trilium-core/src/services/utils/binary.tsnew file mode 100644index 0000000000..5861ac9067--- /dev/null+++ b/packages/trilium-core/src/services/utils/binary.ts@@ -0,0 +1,35 @@+const utf8Decoder = new TextDecoder("utf-8");++export function concat2(a: Uint8Array, b: Uint8Array): Uint8Array {+ const out = new Uint8Array(a.length + b.length);+ out.set(a, 0);+ out.set(b, a.length);+ return out;+}++export function encodeBase64(bytes: Uint8Array): string {+ let binary = "";+ const len = bytes.length;++ for (let i = 0; i < len; i++) {+ binary += String.fromCharCode(bytes[i]);+ }++ return btoa(binary);+}++export function decodeBase64(base64: string): Uint8Array {+ const binary = atob(base64);+ const len = binary.length;++ const bytes = new Uint8Array(len);+ for (let i = 0; i < len; i++) {+ bytes[i] = binary.charCodeAt(i);+ }++ return bytes;+}++export function decodeUtf8(bytes: Uint8Array) {+ return utf8Decoder.decode(bytes);+}