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(core): integrate utils partially
Elian Doranbd45c3225142
diff --git a/apps/server/src/crypto_provider.ts b/apps/server/src/crypto_provider.tsindex c51b7bc9dd..6ddeecf9f3 100644--- a/apps/server/src/crypto_provider.ts+++ b/apps/server/src/crypto_provider.ts@@ -1,5 +1,8 @@import { CryptoProvider } from "@triliumnext/core";import crypto from "crypto";+import { generator } from "rand-token";++const randtoken = generator({ source: "crypto" });export default class NodejsCryptoProvider implements CryptoProvider {@@ -19,4 +22,8 @@ export default class NodejsCryptoProvider implements CryptoProvider {return crypto.randomBytes(size);}+ randomString(length: number): string {+ return randtoken.generate(length);+ }+}diff --git a/apps/server/src/services/consistency_checks.ts b/apps/server/src/services/consistency_checks.tsindex 887b8990d6..23727c30fb 100644--- a/apps/server/src/services/consistency_checks.ts+++ b/apps/server/src/services/consistency_checks.ts@@ -1,14 +1,12 @@--import type { BranchRow } from "@triliumnext/commons";import type { EntityChange } from "@triliumnext/commons";-import { becca_loader } from "@triliumnext/core";+import { becca_loader, utils } from "@triliumnext/core";import becca from "../becca/becca.js";import BBranch from "../becca/entities/bbranch.js";import eraseService from "../services/erase.js";import noteTypesService from "../services/note_types.js";-import { hash as getHash, hashedBlobId, randomString } from "../services/utils.js";+import { hashedBlobId, randomString } from "../services/utils.js";import cls from "./cls.js";import entityChangesService from "./entity_changes.js";import log from "./log.js";@@ -85,11 +83,11 @@ class ConsistencyChecks {}return true;- }+ }logError(`Tree cycle detected at parent-child relationship: '${parentNoteId}' - '${noteId}', whole path: '${path}'`);this.unrecoveredConsistencyErrors = true;-+} else {const newPath = path.slice();newPath.push(noteId);@@ -492,7 +490,7 @@ class ConsistencyChecks {dateModified: fakeDate});- const hash = getHash(randomString(10));+ const hash = utils.hash(randomString(10));entityChangesService.putEntityChange({entityName: "blobs",diff --git a/apps/server/src/services/content_hash.ts b/apps/server/src/services/content_hash.tsindex 6c8365e2b6..41bd27d29e 100644--- a/apps/server/src/services/content_hash.ts+++ b/apps/server/src/services/content_hash.ts@@ -1,9 +1,8 @@-"use strict";+import { utils } from "@triliumnext/core";-import sql from "./sql.js";-import { hash } from "./utils.js";-import log from "./log.js";import eraseService from "./erase.js";+import log from "./log.js";+import sql from "./sql.js";type SectorHash = Record<string, string>;@@ -48,7 +47,7 @@ function getEntityHashes() {for (const entityHashMap of Object.values(hashMap)) {for (const key in entityHashMap) {- entityHashMap[key] = hash(entityHashMap[key]);+ entityHashMap[key] = utils.hash(entityHashMap[key]);}}diff --git a/apps/server/src/services/utils.ts b/apps/server/src/services/utils.tsindex 370f9297ff..e0e40094d8 100644--- a/apps/server/src/services/utils.ts+++ b/apps/server/src/services/utils.ts@@ -1,23 +1,23 @@-"use strict";++import { utils as coreUtils } from "@triliumnext/core";import chardet from "chardet";-import stripBom from "strip-bom";import crypto from "crypto";-import { generator } from "rand-token";-import unescape from "unescape";import escape from "escape-html";-import sanitize from "sanitize-filename";+import { t } from "i18next";import mimeTypes from "mime-types";+import { release as osRelease } from "os";import path from "path";-import type NoteMeta from "./meta/note_meta.js";+import { generator } from "rand-token";+import sanitize from "sanitize-filename";+import stripBom from "strip-bom";+import unescape from "unescape";+import log from "./log.js";-import { t } from "i18next";-import { release as osRelease } from "os";+import type NoteMeta from "./meta/note_meta.js";const osVersion = osRelease().split('.').map(Number);-const randtoken = generator({ source: "crypto" });-export const isMac = process.platform === "darwin";export const isWindows = process.platform === "win32";@@ -28,12 +28,14 @@ export const isElectron = !!process.versions["electron"];export const isDev = !!(process.env.TRILIUM_ENV && process.env.TRILIUM_ENV === "dev");+/** @deprecated */export function newEntityId() {- return randomString(12);+ return coreUtils.newEntityId();}+/** @deprecated */export function randomString(length: number): string {- return randtoken.generate(length);+ return coreUtils.randomString(length);}export function randomSecureToken(bytes = 32) {@@ -44,19 +46,9 @@ export function md5(content: crypto.BinaryLike) {return crypto.createHash("md5").update(content).digest("hex");}+/** @deprecated */export function hashedBlobId(content: string | Buffer) {- if (content === null || content === undefined) {- content = "";- }-- // sha512 is faster than sha256- const base64Hash = crypto.createHash("sha512").update(content).digest("base64");-- // we don't want such + and / in the IDs- const kindaBase62Hash = base64Hash.replaceAll("+", "X").replaceAll("/", "Y");-- // 20 characters of base62 gives us ~120 bit of entropy which is plenty enough- return kindaBase62Hash.substr(0, 20);+ return coreUtils.hashedBlobId(content);}export function toBase64(plainText: string | Buffer) {@@ -104,12 +96,6 @@ export function constantTimeCompare(a: string | null | undefined, b: string | nureturn crypto.timingSafeEqual(bufA, bufB);}-export function hash(text: string) {- text = text.normalize();-- return crypto.createHash("sha1").update(text).digest("base64");-}-export function isEmptyOrWhitespace(str: string | null | undefined) {if (!str) return true;return str.match(/^ *$/) !== null;@@ -160,22 +146,18 @@ export function getContentDisposition(filename: string) {return `file; filename="${uriEncodedFilename}"; filename*=UTF-8''${uriEncodedFilename}`;}-// render and book are string note in the sense that they are expected to contain empty string-const STRING_NOTE_TYPES = new Set(["text", "code", "relationMap", "search", "render", "book", "mermaid", "canvas", "webView"]);-const STRING_MIME_TYPES = new Set(["application/javascript", "application/x-javascript", "application/json", "application/x-sql", "image/svg+xml"]);-export function isStringNote(type: string | undefined, mime: string) {- return (type && STRING_NOTE_TYPES.has(type)) || mime.startsWith("text/") || STRING_MIME_TYPES.has(mime);+ return coreUtils.isStringNote(type, mime);}+/** @deprecated */export function quoteRegex(url: string) {- return url.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");+ return coreUtils.quoteRegex(url);}+/** @deprecated */export function replaceAll(string: string, replaceWhat: string, replaceWith: string) {- const quotedReplaceWhat = quoteRegex(replaceWhat);-- return string.replace(new RegExp(quotedReplaceWhat, "g"), replaceWith);+ return coreUtils.replaceAll(string, replaceWhat, replaceWith);}export function formatDownloadTitle(fileName: string, type: string | null, mime: string) {@@ -259,16 +241,14 @@ export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?});}+/** @deprecated */export function removeDiacritic(str: string) {- if (!str) {- return "";- }- str = str.toString();- return str.normalize("NFD").replace(/\p{Diacritic}/gu, "");+ return coreUtils.removeDiacritic(str);}+/** @deprecated */export function normalize(str: string) {- return removeDiacritic(str).toLowerCase();+ return coreUtils.normalize(str);}export function toMap<T extends Record<string, any>>(list: T[], key: keyof T) {@@ -467,28 +447,28 @@ export function normalizeCustomHandlerPattern(pattern: string | null | undefined// If already ends with slash, create both versionsif (basePattern.endsWith('/')) {- const withoutSlash = basePattern.slice(0, -1) + '$';+ const withoutSlash = `${basePattern.slice(0, -1) }$`;const withSlash = pattern;return [withoutSlash, withSlash];- } else {- // Add optional trailing slash- const withSlash = basePattern + '/?$';- return [withSlash];}+ // Add optional trailing slash+ const withSlash = `${basePattern }/?$`;+ return [withSlash];+}// For patterns without $, add both versionsif (pattern.endsWith('/')) {const withoutSlash = pattern.slice(0, -1);return [withoutSlash, pattern];- } else {- const withSlash = pattern + '/';- return [pattern, withSlash];}+ const withSlash = `${pattern }/`;+ return [pattern, withSlash];+}export function formatUtcTime(time: string) {- return time.replace("T", " ").substring(0, 19)+ return time.replace("T", " ").substring(0, 19);}// TODO: Deduplicate with client utils@@ -501,9 +481,9 @@ export function formatSize(size: number | null | undefined) {if (size < 1024) {return `${size} KiB`;- } else {- return `${Math.round(size / 102.4) / 10} MiB`;}+ return `${Math.round(size / 102.4) / 10} MiB`;+}function slugify(text: string) {@@ -526,7 +506,6 @@ export default {getContentDisposition,getNoteTitle,getResourceDir,- hash,hashedBlobId,hmac,isDev,diff --git a/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts b/packages/trilium-core/src/becca/entities/abstract_becca_entity.tsindex d14626781e..74f9442484 100644--- a/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts+++ b/packages/trilium-core/src/becca/entities/abstract_becca_entity.ts@@ -6,11 +6,11 @@ import dateUtils from "../../services/utils/date";import entityChangesService from "../../services/entity_changes.js";import { getLog } from "../../services/log.js";import protectedSessionService from "../../services/protected_session.js";-import utils from "../../services/utils.js";import becca from "../becca.js";import type { ConstructorData,default as Becca } from "../becca-interface.js";import { getSql } from "src/services/sql";import { concat2, encodeUtf8, unwrapStringOrBuffer, wrapStringOrBuffer } from "src/services/utils/binary";+import { hash, hashedBlobId, newEntityId, randomString } from "src/services/utils";interface ContentOpts {forceSave?: boolean;@@ -36,7 +36,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {protected beforeSaving(opts?: {}) {const constructorData = this.constructor as unknown as ConstructorData<T>;if (!(this as any)[constructorData.primaryKeyName]) {- (this as any)[constructorData.primaryKeyName] = utils.newEntityId();+ (this as any)[constructorData.primaryKeyName] = newEntityId();}}@@ -72,7 +72,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {contentToHash += "|deleted";}- return utils.hash(contentToHash).substr(0, 10);+ return hash(contentToHash).substr(0, 10);}protected getPojoToSave() {@@ -224,7 +224,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {* This has minor security implications (it's easy to infer that given content is shared between different* notes/attachments), but the trade-off comes out clearly positive.*/- const newBlobId = utils.hashedBlobId(unencryptedContentForHashCalculation);+ const newBlobId = hashedBlobId(unencryptedContentForHashCalculation);const sql = getSql();const blobNeedsInsert = !sql.getValue("SELECT 1 FROM blobs WHERE blobId = ?", [newBlobId]);@@ -254,7 +254,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {isSynced: true,// overriding componentId will cause the frontend to think the change is coming from a different component// and thus reload- componentId: opts.forceFrontendReload ? utils.randomString(10) : null+ componentId: opts.forceFrontendReload ? randomString(10) : null});eventService.emit(eventService.ENTITY_CHANGED, {diff --git a/packages/trilium-core/src/becca/entities/battachment.ts b/packages/trilium-core/src/becca/entities/battachment.tsindex b8b86ace1a..bd6a1ff45f 100644--- a/packages/trilium-core/src/becca/entities/battachment.ts+++ b/packages/trilium-core/src/becca/entities/battachment.ts@@ -6,11 +6,11 @@ import dateUtils from "../../services/utils/date";import { getLog } from "../../services/log.js";import noteService from "../../services/notes.js";import protectedSessionService from "../../services/protected_session.js";-import utils from "../../services/utils.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";import type BBranch from "./bbranch.js";import type BNote from "./bnote.js";import { getSql } from "src/services/sql/index.js";+import { isStringNote, replaceAll } from "src/services/utils";const attachmentRoleToNoteTypeMapping = {image: "image",@@ -105,7 +105,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {/** @returns true if the note has string content (not binary) */override hasStringContent(): boolean {- return utils.isStringNote(this.type, this.mime); // here was !== undefined && utils.isStringNote(this.type, this.mime); I dont know why we need !=undefined. But it filters out canvas libary items+ return isStringNote(this.type, this.mime); // here was !== undefined && utils.isStringNote(this.type, this.mime); I dont know why we need !=undefined. But it filters out canvas libary items}isContentAvailable() {@@ -186,7 +186,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {const oldAttachmentUrl = `api/attachments/${this.attachmentId}/image/`;const newNoteUrl = `api/images/${note.noteId}/`;- const fixedContent = utils.replaceAll(origContent, oldAttachmentUrl, newNoteUrl);+ const fixedContent = replaceAll(origContent, oldAttachmentUrl, newNoteUrl);if (fixedContent !== origContent) {parentNote.setContent(fixedContent);diff --git a/packages/trilium-core/src/becca/entities/bbranch.ts b/packages/trilium-core/src/becca/entities/bbranch.tsindex 78e8bb199d..b7603b2702 100644--- a/packages/trilium-core/src/becca/entities/bbranch.ts+++ b/packages/trilium-core/src/becca/entities/bbranch.ts@@ -6,10 +6,10 @@ import dateUtils from "../../services/utils/date";import handlers from "../../services/handlers.js";import { getLog } from "../../services/log.js";import TaskContext from "../../services/task_context.js";-import utils from "../../services/utils.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";import BNote from "./bnote.js";import { getHoistedNoteId } from "src/services/context";+import { randomString } from "src/services/utils";/*** Branch represents a relationship between a child note and its parent note. Trilium allows a note to have multiple@@ -140,7 +140,7 @@ class BBranch extends AbstractBeccaEntity<BBranch> {*/deleteBranch(deleteId?: string, taskContext?: TaskContext<"deleteNotes">): boolean {if (!deleteId) {- deleteId = utils.randomString(10);+ deleteId = randomString(10);}if (!taskContext) {diff --git a/packages/trilium-core/src/becca/entities/bnote.ts b/packages/trilium-core/src/becca/entities/bnote.tsindex e59be195c5..14402d7798 100644--- a/packages/trilium-core/src/becca/entities/bnote.ts+++ b/packages/trilium-core/src/becca/entities/bnote.ts@@ -6,13 +6,12 @@ import cloningService from "../../services/cloning.js";import dateUtils from "../../services/utils/date";import eraseService from "../../services/erase.js";import handlers from "../../services/handlers.js";-import log, { getLog } from "../../services/log.js";+import { getLog } from "../../services/log.js";import noteService from "../../services/notes.js";import optionService from "../../services/options.js";import protectedSessionService from "../../services/protected_session.js";import searchService from "../../services/search/services/search.js";import TaskContext from "../../services/task_context.js";-import utils from "../../services/utils.js";import type { NotePojo } from "../becca-interface.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";import BAttachment from "./battachment.js";@@ -20,6 +19,7 @@ import BAttribute from "./battribute.js";import type BBranch from "./bbranch.js";import BRevision from "./brevision.js";import { getSql } from "src/services/sql/index.js";+import { isStringNote, normalize, randomString, replaceAll } from "src/services/utils";const LABEL = "label";const RELATION = "relation";@@ -316,7 +316,7 @@ class BNote extends AbstractBeccaEntity<BNote> {/** @returns true if the note has string content (not binary) */override hasStringContent() {- return utils.isStringNote(this.type, this.mime);+ return isStringNote(this.type, this.mime);}/** @returns JS script environment - either "frontend" or "backend" */@@ -798,7 +798,7 @@ class BNote extends AbstractBeccaEntity<BNote> {this.__flatTextCache += " ";}- this.__flatTextCache = utils.normalize(this.__flatTextCache);+ this.__flatTextCache = normalize(this.__flatTextCache);}return this.__flatTextCache as string;@@ -1481,7 +1481,7 @@ class BNote extends AbstractBeccaEntity<BNote> {throw new Error("Unable to convert image note into attachment because parent note does not have a string content.");}- const fixedContent = utils.replaceAll(parentContent, oldNoteUrl, newAttachmentUrl);+ const fixedContent = replaceAll(parentContent, oldNoteUrl, newAttachmentUrl);parentNote.setContent(fixedContent);@@ -1503,7 +1503,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}if (!deleteId) {- deleteId = utils.randomString(10);+ deleteId = randomString(10);}if (!taskContext) {diff --git a/packages/trilium-core/src/becca/entities/brevision.ts b/packages/trilium-core/src/becca/entities/brevision.tsindex c09e9ff211..9a5f79740a 100644--- a/packages/trilium-core/src/becca/entities/brevision.ts+++ b/packages/trilium-core/src/becca/entities/brevision.ts@@ -1,7 +1,6 @@"use strict";import protectedSessionService from "../../services/protected_session.js";-import utils from "../../services/utils.js";import dateUtils from "../../services/utils/date";import becca from "../becca.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";@@ -9,6 +8,7 @@ import BAttachment from "./battachment.js";import type { AttachmentRow, NoteType, RevisionPojo, RevisionRow } from "@triliumnext/commons";import eraseService from "../../services/erase.js";import { getSql } from "src/services/sql/index.js";+import { isStringNote } from "src/services/utils/index.js";interface ContentOpts {/** will also save this BRevision entity */@@ -76,7 +76,7 @@ class BRevision extends AbstractBeccaEntity<BRevision> {/** @returns true if the note has string content (not binary) */override hasStringContent(): boolean {- return utils.isStringNote(this.type, this.mime);+ return isStringNote(this.type, this.mime);}isContentAvailable() {diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex cbdcba64d9..5abb13025e 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -9,6 +9,7 @@ export * from "./services/sql/index";export * as protected_session from "./services/protected_session";export { default as data_encryption } from "./services/encryption/data_encryption"export * as binary_utils from "./services/utils/binary";+export * as utils from "./services/utils/index";export { default as date_utils } from "./services/utils/date";export { default as events } from "./services/events";export { default as blob } from "./services/blob";diff --git a/packages/trilium-core/src/services/blob.ts b/packages/trilium-core/src/services/blob.tsindex 9de989abcd..6792c75270 100644--- a/packages/trilium-core/src/services/blob.ts+++ b/packages/trilium-core/src/services/blob.ts@@ -2,8 +2,8 @@ import { BlobRow } from "@triliumnext/commons";import becca from "../becca/becca.js";import { NotFoundError } from "../errors";import protectedSessionService from "./protected_session.js";-import { hash } from "./utils.js";import { decodeUtf8 } from "./utils/binary.js";+import { hash } from "./utils/index.js";function getBlobPojo(entityName: string, entityId: string, opts?: { preview: boolean }) {// TODO: Unused opts.diff --git a/packages/trilium-core/src/services/encryption/crypto.ts b/packages/trilium-core/src/services/encryption/crypto.tsindex 94ebcb1ad9..87cd8fb6c0 100644--- a/packages/trilium-core/src/services/encryption/crypto.ts+++ b/packages/trilium-core/src/services/encryption/crypto.ts@@ -5,8 +5,9 @@ interface Cipher {export interface CryptoProvider {- createHash(algorithm: "sha1", content: string | Uint8Array): Uint8Array;+ createHash(algorithm: "sha1" | "sha512", content: string | Uint8Array): Uint8Array;randomBytes(size: number): Uint8Array;+ randomString(length: number): string;createCipheriv(algorithm: "aes-128-cbc", key: Uint8Array, iv: Uint8Array): Cipher;createDecipheriv(algorithm: "aes-128-cbc", key: Uint8Array, iv: Uint8Array): Cipher;}diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsnew file mode 100644index 0000000000..06f730dcbf--- /dev/null+++ b/packages/trilium-core/src/services/utils/index.ts@@ -0,0 +1,60 @@+import { getCrypto } from "../encryption/crypto";+import { encodeBase64 } from "./binary";++// render and book are string note in the sense that they are expected to contain empty string+const STRING_NOTE_TYPES = new Set(["text", "code", "relationMap", "search", "render", "book", "mermaid", "canvas", "webView"]);+const STRING_MIME_TYPES = new Set(["application/javascript", "application/x-javascript", "application/json", "application/x-sql", "image/svg+xml"]);++export function hash(text: string) {+ return encodeBase64(getCrypto().createHash("sha1", text.normalize()));+}++export function isStringNote(type: string | undefined, mime: string) {+ return (type && STRING_NOTE_TYPES.has(type)) || mime.startsWith("text/") || STRING_MIME_TYPES.has(mime);+}++// TODO: Refactor to use getCrypto() directly.+export function randomString(length: number) {+ return getCrypto().randomString(length);+}++export function newEntityId() {+ return randomString(12);+}++export function hashedBlobId(content: string | Uint8Array) {+ if (content === null || content === undefined) {+ content = "";+ }++ // sha512 is faster than sha256+ const base64Hash = encodeBase64(getCrypto().createHash("sha512", content));++ // we don't want such + and / in the IDs+ const kindaBase62Hash = base64Hash.replaceAll("+", "X").replaceAll("/", "Y");++ // 20 characters of base62 gives us ~120 bit of entropy which is plenty enough+ return kindaBase62Hash.substr(0, 20);+}++export function quoteRegex(url: string) {+ return url.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");+}++export function replaceAll(string: string, replaceWhat: string, replaceWith: string) {+ const quotedReplaceWhat = quoteRegex(replaceWhat);++ return string.replace(new RegExp(quotedReplaceWhat, "g"), replaceWith);+}++export function removeDiacritic(str: string) {+ if (!str) {+ return "";+ }+ str = str.toString();+ return str.normalize("NFD").replace(/\p{Diacritic}/gu, "");+}++export function normalize(str: string) {+ return removeDiacritic(str).toLowerCase();+}