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
Merge remote-tracking branch 'origin/main' into feat/fun-take1
Elian Dorane42cb077b413
diff --cc apps/client/src/services/content_renderer_text.tsindex 04be825298,283340ecc2..715e5c2c04--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@@ -3,9 -3,9 +3,10 @@@ import FNote from "../entities/fnote.jsimport { default as content_renderer, type RenderOptions } from "./content_renderer.js";import froca from "./froca.js";import link from "./link.js";+ import { applyLinkEmbeds } from "./link_embed.js";import { renderMathInElement } from "./math.js";import { getMermaidConfig } from "./mermaid.js";+import { sanitizeNoteContentHtml } from "./sanitize_content.js";import { formatCodeBlocks } from "./syntax_highlight.js";import tree from "./tree.js";import { isHtmlEmpty } from "./utils.js";@@@ -15,36 -15,47 +16,47 @@@ export default async function renderTexconst blob = await note.getBlob();if (blob && !isHtmlEmpty(blob.content)) {- $renderedContent.append($('<div class="ck-content">').html(blob.content));+ $renderedContent.append($('<div class="ck-content">').html(sanitizeNoteContentHtml(blob.content)));+ await postProcessRichContent(note, $renderedContent, options);+ } else if (note instanceof FNote && !options.noChildrenList) {+ await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);+ }+ }- const seenNoteIds = options.seenNoteIds ?? new Set<string>();- seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);- if (!options.noIncludedNotes) {- await renderIncludedNotes($renderedContent[0], seenNoteIds);- } else {- $renderedContent.find("section.include-note").remove();- }+ /**+ * Apply the post-render passes that make CKEditor-compatible HTML fully+ * interactive: expand `<section class="include-note">`, render inline math and+ * Mermaid diagrams, rewrite reference-link titles, and highlight code blocks.+ * Assumes the caller has already appended the HTML inside a `.ck-content` child+ * of `$renderedContent`.+ */+ export async function postProcessRichContent(note: FNote | FAttachment, $renderedContent: JQuery<HTMLElement>, options: RenderOptions = {}) {+ const seenNoteIds = options.seenNoteIds ?? new Set<string>();+ seenNoteIds.add("noteId" in note ? note.noteId : note.attachmentId);+ if (!options.noIncludedNotes) {+ await renderIncludedNotes($renderedContent[0], seenNoteIds);+ } else {+ $renderedContent.find("section.include-note").remove();+ }- if ($renderedContent.find("span.math-tex").length > 0) {- renderMathInElement($renderedContent[0], { trust: true });- }+ if ($renderedContent.find("span.math-tex").length > 0) {+ renderMathInElement($renderedContent[0], { trust: true });+ }- const getNoteIdFromLink = (el: HTMLElement) => tree.getNoteIdFromUrl($(el).attr("href") || "");- const referenceLinks = $renderedContent.find<HTMLAnchorElement>("a.reference-link");- const noteIdsToPrefetch = referenceLinks.map((i, el) => getNoteIdFromLink(el));- await froca.getNotes(noteIdsToPrefetch);+ const getNoteIdFromLink = (el: HTMLElement) => tree.getNoteIdFromUrl($(el).attr("href") || "");+ const referenceLinks = $renderedContent.find<HTMLAnchorElement>("a.reference-link");+ const noteIdsToPrefetch = referenceLinks.map((i, el) => getNoteIdFromLink(el));+ await froca.getNotes(noteIdsToPrefetch);- for (const el of referenceLinks) {- const innerSpan = document.createElement("span");- await link.loadReferenceLinkTitle($(innerSpan), el.href);- el.replaceChildren(innerSpan);- }+ await Promise.all(referenceLinks.toArray().map(async (el) => {+ const innerSpan = document.createElement("span");+ await link.loadReferenceLinkTitle($(innerSpan), el.getAttribute("href"));+ el.replaceChildren(innerSpan);+ }));- await rewriteMermaidDiagramsInContainer($renderedContent[0] as HTMLDivElement);- await formatCodeBlocks($renderedContent);- } else if (note instanceof FNote && !options.noChildrenList) {- await renderChildrenList($renderedContent, note, options.includeArchivedNotes ?? false);- }+ applyLinkEmbeds($renderedContent[0]);+ await rewriteMermaidDiagramsInContainer($renderedContent[0] as HTMLDivElement);+ await formatCodeBlocks($renderedContent);}async function renderIncludedNotes(contentEl: HTMLElement, seenNoteIds: Set<string>) {diff --cc apps/client/src/services/note_tooltip.tsindex c868781952,9ab8fc8e8f..616d43ff09--- a/apps/client/src/services/note_tooltip.ts+++ b/apps/client/src/services/note_tooltip.ts@@@ -93,9 -94,8 +95,9 @@@ async function mouseEnterHandler<T>(thireturn;}- const html = `<div class="note-tooltip-content">${content}</div>`;+ const sanitizedContent = sanitizeNoteContentHtml(content);+ const html = `<div class="note-tooltip-content">${sanitizedContent}</div>`;- const tooltipClass = `tooltip-${Math.floor(Math.random() * 999_999_999)}`;+ const tooltipClass = `tooltip-${Math.floor(Math.random() * 999_999_999)}${note ? ` ${note.getColorClass()}` : ""}`;// we need to check if we're still hovering over the element// since the operation to get tooltip content was async, it is possible thatdiff --cc apps/server/src/backup_provider.tsindex 0000000000,1da8d1b273..c2138c0222mode 000000,100644..100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@@ -1,0 -1,71 +1,78 @@@+ import type { DatabaseBackup } from "@triliumnext/commons";+ import { BackupOptionsService, BackupService, sync_mutex as syncMutexService } from "@triliumnext/core";+ import fs from "fs";+ import path from "path";++ import dataDir from "./services/data_dir.js";+ import { getLog } from "@triliumnext/core";+ import sql from "./services/sql.js";++ export default class ServerBackupService extends BackupService {+ constructor(options: BackupOptionsService) {+ super(options);+ }++ override async getExistingBackups(): Promise<DatabaseBackup[]> {+ if (!fs.existsSync(dataDir.BACKUP_DIR)) {+ return [];+ }++ return fs+ .readdirSync(dataDir.BACKUP_DIR)+ .filter((fileName) => fileName.includes("backup"))+ .map((fileName) => {+ const filePath = path.resolve(dataDir.BACKUP_DIR, fileName);+ const stat = fs.statSync(filePath);++ return { fileName, filePath, mtime: stat.mtime };+ });+ }++ override scheduleBackups(): void {+ // Run regular backups every 4 hours+ setInterval(() => this.regularBackup(), 4 * 60 * 60 * 1000);++ // Kickoff first backup soon after startup+ setTimeout(() => this.regularBackup(), 5 * 60 * 1000);+ }++ override async backupNow(name: string): Promise<string> {++ // Sanitize backup name to prevent path traversal (CWE-22).++ // Only allow alphanumeric characters, hyphens, and underscores.++ const sanitizedName = name.replace(/[^a-zA-Z0-9_-]/g, "");++ if (!sanitizedName) {++ throw new Error("Invalid backup name: must contain at least one alphanumeric character, hyphen, or underscore.");++ }+++ // we don't want to back up DB in the middle of sync with potentially inconsistent DB state+ return await syncMutexService.doExclusively(async () => {- const backupFile = path.resolve(`${dataDir.BACKUP_DIR}/backup-${name}.db`);++ const backupFile = path.resolve(`${dataDir.BACKUP_DIR}/backup-${sanitizedName}.db`);++ if (!fs.existsSync(dataDir.BACKUP_DIR)) {+ fs.mkdirSync(dataDir.BACKUP_DIR, 0o700);+ }++ getLog().info("Creating backup...");+ await sql.copyDatabase(backupFile);+ getLog().info(`Created backup at ${backupFile}`);++ return backupFile;+ });+ }++ override async getBackupContent(filePath: string): Promise<Uint8Array | null> {+ const resolvedPath = path.resolve(filePath);+ const backupDir = path.resolve(dataDir.BACKUP_DIR);++ // Security check: ensure the path is within the backup directory+ if (!resolvedPath.startsWith(backupDir + path.sep)) {+ return null;+ }++ if (!fs.existsSync(resolvedPath)) {+ return null;+ }++ return fs.readFileSync(resolvedPath);+ }+ }diff --cc apps/server/src/routes/api/files.tsindex a0ce2daf7a,1484d26092..ecc0b85b44--- a/apps/server/src/routes/api/files.ts+++ b/apps/server/src/routes/api/files.ts@@@ -1,7 -1,7 +1,8 @@@+ import { note_service as noteService, ValidationError, ws } from "@triliumnext/core";import chokidar from "chokidar";- import type { Request, Response } from "express";+ import type { Request } from "express";import fs from "fs";+import path from "path";import { Readable } from "stream";import tmp from "tmp";diff --cc apps/server/src/routes/csrf_protection.tsindex 7f3f61813b,8b153909be..2098a95851--- a/apps/server/src/routes/csrf_protection.ts+++ b/apps/server/src/routes/csrf_protection.ts@@@ -1,9 -1,8 +1,9 @@@- import crypto from "crypto";import { doubleCsrf } from "csrf-csrf";+ import type { NextFunction, Request, Response } from "express";+ import { isInternalElectronRequest } from "../services/electron_request.js";import sessionSecret from "../services/session_secret.js";- import { isElectron } from "../services/utils.js";+import config from "../services/config.js";export const CSRF_COOKIE_NAME = "trilium-csrf";@@@ -17,12 -10,26 +11,26 @@@ const doubleCsrfUtilities = doubleCsrf(getSecret: () => sessionSecret,cookieOptions: {path: "/",- secure: false,+ secure: config.Network.https,sameSite: "strict",- httpOnly: !isElectron // set to false for Electron, see https://github.com/TriliumNext/Trilium/pull/966+ httpOnly: true},cookieName: CSRF_COOKIE_NAME,- getSessionIdentifier: (req) => isElectron ? electronSessionId : req.session.id+ getSessionIdentifier: (req) => req.session.id});- export const { generateCsrfToken, doubleCsrfProtection } = doubleCsrfUtilities;+ export const { generateCsrfToken } = doubleCsrfUtilities;++ // Skip CSRF validation only for requests dispatched via the `trilium-app://`+ // custom protocol from our own renderer — Express sessions don't round-trip+ // through that path, so the HMAC double-submit check has nothing meaningful+ // to validate against. Keying off the per-request marker (rather than the+ // process-wide `isElectron` flag) means TCP requests to the desktop's HTTP+ // listener still get the full CSRF check. Auth is similarly gated in+ // `services/auth.ts`.+ export function doubleCsrfProtection(req: Request, res: Response, next: NextFunction) {+ if (isInternalElectronRequest(req)) {+ return next();+ }+ return doubleCsrfUtilities.doubleCsrfProtection(req, res, next);+ }diff --cc apps/server/src/routes/custom.tsindex dd342f26bf,c7be8ec64e..fea247d25f--- a/apps/server/src/routes/custom.ts+++ b/apps/server/src/routes/custom.ts@@@ -1,12 -1,8 +1,9 @@@- import log from "../services/log.js";- import fileService from "./api/files.js";- import scriptService from "../services/script.js";- import cls from "../services/cls.js";- import sql from "../services/sql.js";- import becca from "../becca/becca.js";+ import { becca, cls, getLog, routeHelpers, scriptService, utils } from "@triliumnext/core";import type { Request, Response, Router } from "express";- import { safeExtractMessageAndStackFromError, normalizeCustomHandlerPattern } from "../services/utils.js";++ import { namespace } from "../cls_provider.js";+import { isScriptingEnabled } from "../services/scripting_guard.js";+ import sql from "../services/sql.js";function handleRequest(req: Request, res: Response) {@@@ -70,15 -61,7 +67,15 @@@if (attr.name === "customRequestHandler") {const note = attr.getNote();+ // Require authentication unless note has #customRequestHandlerPublic label+ if (!note.hasLabel("customRequestHandlerPublic")) {+ if (!req.session?.loggedIn) {+ res.status(401).send("Authentication required for this endpoint.");+ return;+ }+ }+- log.info(`Handling custom request '${path}' with note '${note.noteId}'`);+ getLog().info(`Handling custom request '${path}' with note '${note.noteId}'`);try {scriptService.executeNote(note, {diff --cc apps/server/src/routes/routes.tsindex 645b1b0feb,8558ff84f3..b332ec5b1f--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@@ -15,48 -16,20 +16,20 @@@ import etapiSpecRoute from "../etapi/spimport etapiSpecialNoteRoutes from "../etapi/special_notes.js";import auth from "../services/auth.js";import openID from '../services/open_id.js';-import { isElectron } from "../services/utils.js";+import shareRoutes from "../share/routes.js";- import appInfoRoute from "./api/app_info.js";- import attachmentsApiRoute from "./api/attachments.js";- import attributesRoute from "./api/attributes.js";- import autocompleteApiRoute from "./api/autocomplete.js";- import backendLogRoute from "./api/backend_log.js";- import branchesApiRoute from "./api/branches.js";- import bulkActionRoute from "./api/bulk_action.js";import clipperRoute from "./api/clipper.js";- import cloningApiRoute from "./api/cloning.js";import databaseRoute from "./api/database.js";import etapiTokensApiRoutes from "./api/etapi_tokens.js";- import exportRoute from "./api/export.js";import filesRoute from "./api/files.js";import fontsRoute from "./api/fonts.js";- import imageRoute from "./api/image.js";- import importRoute from "./api/import.js";- import keysRoute from "./api/keys.js";import llmChatRoute from "./api/llm_chat.js";+ import llmSpecialNotesRoute from "./api/llm_special_notes.js";import loginApiRoute from "./api/login.js";import metricsRoute from "./api/metrics.js";- import noteMapRoute from "./api/note_map.js";- import notesApiRoute from "./api/notes.js";import ocrRoute from "./api/ocr.js";- import optionsApiRoute from "./api/options.js";- import otherRoute from "./api/other.js";- import passwordApiRoute from "./api/password.js";- import recentChangesApiRoute from "./api/recent_changes.js";- import recentNotesRoute from "./api/recent_notes.js";import recoveryCodes from './api/recovery_codes.js';- import relationMapApiRoute from "./api/relation-map.js";- import revisionsApiRoute from "./api/revisions.js";- import scriptRoute from "./api/script.js";- import searchRoute from "./api/search.js";import senderRoute from "./api/sender.js";- import setupApiRoute from "./api/setup.js";- import similarNotesRoute from "./api/similar_notes.js";- import specialNotesRoute from "./api/special_notes.js";- import sqlRoute from "./api/sql.js";- import statsRoute from "./api/stats.js";- import syncApiRoute from "./api/sync.js";import systemInfoRoute from "./api/system_info.js";import totp from './api/totp.js';// API routesdiff --cc apps/server/src/services/config.tsindex 32e4a86274,2c846f49a9..5b0fe521ab--- a/apps/server/src/services/config.ts+++ b/apps/server/src/services/config.ts@@@ -463,23 -461,8 +468,23 @@@ const configMapping =aliasEnvVars: ['TRILIUM_LOGGING_RETENTION_DAYS'],iniGetter: () => getIniSection("Logging")?.retentionDays,defaultValue: LOGGING_DEFAULT_RETENTION_DAYS,- transformer: (value: unknown) => stringToInt(String(value)) ?? LOGGING_DEFAULT_RETENTION_DAYS+ transformer: (value: unknown) => utils.stringToInt(String(value)) ?? LOGGING_DEFAULT_RETENTION_DAYS}+ },+ Scripting: {+ enabled: {+ standardEnvVar: 'TRILIUM_SCRIPTING_ENABLED',+ iniGetter: () => getIniSection("Scripting")?.enabled,+ defaultValue: false,+ transformer: transformBoolean+ },+ sqlConsoleEnabled: {+ standardEnvVar: 'TRILIUM_SCRIPTING_SQLCONSOLEENABLED',+ aliasEnvVars: ['TRILIUM_SCRIPTING_SQL_CONSOLE_ENABLED'],+ iniGetter: () => getIniSection("Scripting")?.sqlConsoleEnabled,+ defaultValue: false,+ transformer: transformBoolean+ }}};diff --cc apps/server/src/services/safe_template.tsindex d68ad15557,0000000000..eb71a4946amode 100644,000000..100644--- a/apps/server/src/services/safe_template.ts+++ b/apps/server/src/services/safe_template.ts@@@ -1,188 -1,0 +1,188 @@@+/**+ * Safe template evaluator that replaces eval()-based template string interpolation.+ *+ * Supports only a controlled set of operations within ${...} expressions:+ * - Property access chains: `obj.prop.subprop`+ * - Method calls with a single string literal argument: `obj.method('arg')`+ * - Chained combinations: `obj.prop.method('arg')`+ *+ * This prevents arbitrary code execution while supporting the documented+ * titleTemplate and bulk rename use cases:+ * - ${now.format('YYYY-MM-DD')}+ * - ${parentNote.title}+ * - ${parentNote.getLabelValue('authorName')}+ * - ${note.title}+ * - ${note.dateCreatedObj.format('MM-DD')}+ */+- import log from "./log.js";++import { getLog } from "@triliumnext/core";++/** Allowed method names that can be called on template variables. */+const ALLOWED_METHODS = new Set([+ "format",+ "getLabelValue",+ "getLabel",+ "getLabelValues",+ "getRelationValue",+ "getAttributeValue"+]);++/** Allowed property names that can be accessed on template variables. */+const ALLOWED_PROPERTIES = new Set([+ "title",+ "type",+ "mime",+ "noteId",+ "dateCreated",+ "dateModified",+ "utcDateCreated",+ "utcDateModified",+ "dateCreatedObj",+ "utcDateCreatedObj",+ "isProtected",+ "content"+]);++interface TemplateVariables {+ [key: string]: unknown;+}++/**+ * Evaluates a template string safely without using eval().+ *+ * Template strings can contain ${...} expressions which are evaluated+ * against the provided variables map.+ *+ * @param template - The template string, e.g. "Note: ${now.format('YYYY-MM-DD')}"+ * @param variables - Map of variable names to their values+ * @returns The interpolated string+ * @throws Error if an expression cannot be safely evaluated+ */+export function evaluateTemplate(template: string, variables: TemplateVariables): string {+ return template.replace(/\$\{([^}]+)\}/g, (_match, expression: string) => {+ const result = evaluateExpression(expression.trim(), variables);+ return result == null ? "" : String(result);+ });+}++/**+ * Evaluates a single expression like "now.format('YYYY-MM-DD')" or "parentNote.title".+ *+ * Supported forms:+ * - `varName` -> variables[varName]+ * - `varName.prop` -> variables[varName].prop+ * - `varName.prop1.prop2` -> variables[varName].prop1.prop2+ * - `varName.method('arg')` -> variables[varName].method('arg')+ * - `varName.prop.method('arg')` -> variables[varName].prop.method('arg')+ */+function evaluateExpression(expr: string, variables: TemplateVariables): unknown {+ // Parse the expression into segments: variable name, property accesses, and optional method call.+ // We handle: varName(.propName)*.methodName('stringArg')?++ // First, check for a method call at the end: .methodName('arg') or .methodName("arg")+ const methodCallMatch = expr.match(+ /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*(?:'([^']*)'|"([^"]*)")\s*\)$/+ );++ if (methodCallMatch) {+ const [, chainStr, methodName, singleQuoteArg, doubleQuoteArg] = methodCallMatch;+ const methodArg = singleQuoteArg !== undefined ? singleQuoteArg : doubleQuoteArg;++ if (!ALLOWED_METHODS.has(methodName)) {+ throw new Error(`Method '${methodName}' is not allowed in template expressions`);+ }++ const target = resolvePropertyChain(chainStr, variables);+ if (target == null) {+ return null;+ }++ const method = (target as Record<string, unknown>)[methodName];+ if (typeof method !== "function") {+ throw new Error(`'${methodName}' is not a function on the resolved object`);+ }++ return (method as (arg: string) => unknown).call(target, methodArg as string);+ }++ // Check for a no-arg method call at the end: .methodName()+ const noArgMethodMatch = expr.match(+ /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*\)$/+ );++ if (noArgMethodMatch) {+ const [, chainStr, methodName] = noArgMethodMatch;++ if (!ALLOWED_METHODS.has(methodName)) {+ throw new Error(`Method '${methodName}' is not allowed in template expressions`);+ }++ const target = resolvePropertyChain(chainStr, variables);+ if (target == null) {+ return null;+ }++ const method = (target as Record<string, unknown>)[methodName];+ if (typeof method !== "function") {+ throw new Error(`'${methodName}' is not a function on the resolved object`);+ }++ return (method as () => unknown).call(target);+ }++ // Otherwise it's a pure property chain: varName.prop1.prop2...+ const propChainMatch = expr.match(/^[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*$/);+ if (!propChainMatch) {+ throw new Error(`Template expression '${expr}' is not a supported expression. ` ++ `Only property access and whitelisted method calls are allowed.`);+ }++ return resolvePropertyChain(expr, variables);+}++/**+ * Resolves a dot-separated property chain like "parentNote.title" against variables.+ */+function resolvePropertyChain(chain: string, variables: TemplateVariables): unknown {+ const parts = chain.split(".");+ const rootName = parts[0];++ if (!(rootName in variables)) {+ throw new Error(`Unknown variable '${rootName}' in template expression`);+ }++ let current: unknown = variables[rootName];++ for (let i = 1; i < parts.length; i++) {+ if (current == null) {+ return null;+ }++ const prop = parts[i];+ if (!ALLOWED_PROPERTIES.has(prop)) {+ throw new Error(`Property '${prop}' is not allowed in template expressions`);+ }++ current = (current as Record<string, unknown>)[prop];+ }++ return current;+}++/**+ * Convenience wrapper that evaluates a template and catches errors,+ * logging them and returning the fallback value.+ */+export function evaluateTemplateSafe(+ template: string,+ variables: TemplateVariables,+ fallback: string,+ contextDescription: string+): string {+ try {+ return evaluateTemplate(template, variables);+ } catch (e: any) {- log.error(`Template evaluation for ${contextDescription} failed with: ${e.message}`);++ getLog().error(`Template evaluation for ${contextDescription} failed with: ${e.message}`);+ return fallback;+ }+}diff --cc apps/server/src/services/url_validator.tsindex 63bdb7b6b6,0000000000..6267f1b2b8mode 100644,000000..100644--- a/apps/server/src/services/url_validator.ts+++ b/apps/server/src/services/url_validator.ts@@@ -1,140 -1,0 +1,140 @@@+/**+ * URL validation utilities to prevent SSRF (Server-Side Request Forgery) attacks.+ *+ * These checks enforce scheme allowlists and optionally block requests to+ * private/internal IP ranges so that user-controlled URLs cannot be used to+ * reach local files or internal network services.+ */++import { URL } from "url";- import log from "./log.js";++import { getLog } from "@triliumnext/core";++/**+ * IPv4 private and reserved ranges that should not be reachable from+ * server-side HTTP requests initiated by user-supplied URLs.+ */+const PRIVATE_IPV4_RANGES: Array<{ prefix: number; mask: number }> = [+ { prefix: 0x7F000000, mask: 0xFF000000 }, // 127.0.0.0/8 (loopback)+ { prefix: 0x0A000000, mask: 0xFF000000 }, // 10.0.0.0/8 (private)+ { prefix: 0xAC100000, mask: 0xFFF00000 }, // 172.16.0.0/12 (private)+ { prefix: 0xC0A80000, mask: 0xFFFF0000 }, // 192.168.0.0/16 (private)+ { prefix: 0xA9FE0000, mask: 0xFFFF0000 }, // 169.254.0.0/16 (link-local)+ { prefix: 0x00000000, mask: 0xFF000000 }, // 0.0.0.0/8 (current network)+];++/**+ * Parse a dotted-decimal IPv4 address into a 32-bit integer, or return null+ * if the string is not a valid IPv4 literal.+ */+function parseIPv4(ip: string): number | null {+ const parts = ip.split(".");+ if (parts.length !== 4) return null;++ let result = 0;+ for (const part of parts) {+ const octet = Number(part);+ if (!Number.isInteger(octet) || octet < 0 || octet > 255) return null;+ result = (result << 8) | octet;+ }+ // Convert to unsigned 32-bit+ return result >>> 0;+}++/**+ * Returns true when the hostname is a private/internal IPv4 address, an IPv6+ * loopback (::1), or an IPv6 unique-local address (fc00::/7).+ *+ * DNS resolution is NOT performed here; the check only applies when the+ * hostname is already an IP literal. For full SSRF protection against DNS+ * rebinding you would need an additional check after resolution, but+ * blocking IP literals covers the most common attack vectors.+ */+function isPrivateIP(hostname: string): boolean {+ // Strip IPv6 bracket notation that URL may retain.+ const cleanHost = hostname.replace(/^\[|\]$/g, "");++ // IPv6 checks+ if (cleanHost === "::1") return true;+ if (cleanHost.toLowerCase().startsWith("fc") || cleanHost.toLowerCase().startsWith("fd")) {+ // fc00::/7 covers fc00:: through fdff::+ return true;+ }++ // IPv4 check+ const ipNum = parseIPv4(cleanHost);+ if (ipNum !== null) {+ for (const range of PRIVATE_IPV4_RANGES) {+ if ((ipNum & range.mask) === (range.prefix >>> 0)) {+ return true;+ }+ }+ }++ // "localhost" as a hostname (not an IP literal)+ if (cleanHost.toLowerCase() === "localhost") {+ return true;+ }++ return false;+}++/** Schemes that are safe for outbound HTTP(S) image downloads. */+const ALLOWED_HTTP_SCHEMES = new Set(["http:", "https:"]);++/**+ * Validate that a URL is safe for server-side fetching (e.g. image downloads).+ *+ * Rules:+ * 1. Only http: and https: schemes are permitted.+ * 2. The hostname must not resolve to a private/internal IP range.+ *+ * Returns `true` when the URL passes all checks, `false` otherwise.+ * Invalid / unparseable URLs also return `false`.+ */+export function isSafeUrlForFetch(urlStr: string): boolean {+ try {+ const parsed = new URL(urlStr);++ if (!ALLOWED_HTTP_SCHEMES.has(parsed.protocol)) {- log.info(`URL rejected - disallowed scheme '${parsed.protocol}': ${urlStr}`);++ getLog().info(`URL rejected - disallowed scheme '${parsed.protocol}': ${urlStr}`);+ return false;+ }++ if (isPrivateIP(parsed.hostname)) {- log.info(`URL rejected - private/internal IP '${parsed.hostname}': ${urlStr}`);++ getLog().info(`URL rejected - private/internal IP '${parsed.hostname}': ${urlStr}`);+ return false;+ }++ return true;+ } catch {- log.info(`URL rejected - failed to parse: ${urlStr}`);++ getLog().info(`URL rejected - failed to parse: ${urlStr}`);+ return false;+ }+}++/**+ * Validate that a base URL intended for an LLM provider API is using a safe+ * scheme (http or https only).+ *+ * This is a lighter check than `isSafeUrlForFetch` because LLM base URLs are+ * configured by authenticated administrators, so we only enforce the scheme+ * restriction without blocking private IPs (which are legitimate for+ * self-hosted services like Ollama).+ *+ * Returns `true` when the URL passes the check, `false` otherwise.+ */+export function isSafeProviderBaseUrl(urlStr: string): boolean {+ try {+ const parsed = new URL(urlStr);++ if (!ALLOWED_HTTP_SCHEMES.has(parsed.protocol)) {- log.info(`LLM provider base URL rejected - disallowed scheme '${parsed.protocol}': ${urlStr}`);++ getLog().info(`LLM provider base URL rejected - disallowed scheme '${parsed.protocol}': ${urlStr}`);+ return false;+ }++ return true;+ } catch {- log.info(`LLM provider base URL rejected - failed to parse: ${urlStr}`);++ getLog().info(`LLM provider base URL rejected - failed to parse: ${urlStr}`);+ return false;+ }+}diff --cc apps/server/src/share/content_renderer.tsindex 9a61852f9a,f1d7335baa..161cb285fe--- a/apps/server/src/share/content_renderer.ts+++ b/apps/server/src/share/content_renderer.ts@@@ -8,16 -8,8 +8,9 @@@ import { t } from "i18next"import { HTMLElement, Options, parse, TextNode } from "node-html-parser";import { join } from "path";- import becca from "../becca/becca.js";- import BAttachment from '../becca/entities/battachment.js';- import type BBranch from "../becca/entities/bbranch.js";- import BNote from "../becca/entities/bnote.js";import assetPath, { assetUrlFragment } from "../services/asset_path.js";- import { generateCss, getIconPacks, MIME_TO_EXTENSION_MAPPINGS, ProcessedIconPack } from "../services/icon_packs.js";- import log from "../services/log.js";+import { isScriptingEnabled } from "../services/scripting_guard.js";- import options from "../services/options.js";- import utils, { getResourceDir, isDev, safeExtractMessageAndStackFromError } from "../services/utils.js";+ import { getResourceDir, isDev } from "../services/utils.js";import SAttachment from "./shaca/entities/sattachment.js";import SBranch from "./shaca/entities/sbranch.js";import type SNote from "./shaca/entities/snote.js";@@@ -195,7 -193,6 +194,7 @@@ function renderNoteContentInternal(notet,isDev,utils,- sanitizeUrl,++ sanitizeUrl: sanitize.sanitizeUrl,...renderArgs,};diff --cc apps/server/src/share/routes.tsindex de39d81fd3,5b96cb4827..e1027e6f2a--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@@ -232,17 -222,10 +229,20 @@@ function register(router: Router)}if (image.type === "image") {- // normal image- res.set("Content-Type", image.mime);addNoIndexHeader(image, res);- res.send(image.getContent());+ if (image.mime === "image/svg+xml") {+ // SVG images require sanitization to prevent stored XSS+ const content = image.getContent();- const sanitized = sanitizeSvg(typeof content === "string" ? content : content?.toString("utf-8") ?? "");- setSvgHeaders(res);++ const svgContent = typeof content === "string" ? content : new TextDecoder().decode(content ?? new Uint8Array());++ const sanitized = utils.sanitizeSvg(svgContent);++ res.set("Content-Type", "image/svg+xml");++ res.set("Cache-Control", "no-cache, no-store, must-revalidate");++ res.set("Content-Security-Policy", "script-src 'none'");+ res.send(sanitized);+ } else {+ res.set("Content-Type", image.mime);+ res.send(image.getContent());+ }} else if (image.type === "canvas") {renderImageAttachment(image, res, "canvas-export.svg");} else if (image.type === "mermaid") {@@@ -265,17 -248,9 +265,20 @@@}if (attachment.role === "image") {- res.set("Content-Type", attachment.mime);addNoIndexHeader(attachment.note, res);- res.send(attachment.getContent());+ if (attachment.mime === "image/svg+xml") {+ // SVG attachments require sanitization to prevent stored XSS+ const content = attachment.getContent();- const sanitized = sanitizeSvg(typeof content === "string" ? content : content?.toString("utf-8") ?? "");- setSvgHeaders(res);++ const svgContent = typeof content === "string" ? content : new TextDecoder().decode(content ?? new Uint8Array());++ const sanitized = utils.sanitizeSvg(svgContent);++ res.set("Content-Type", "image/svg+xml");++ res.set("Cache-Control", "no-cache, no-store, must-revalidate");++ res.set("Content-Security-Policy", "script-src 'none'");+ res.send(sanitized);+ } else {+ res.set("Content-Type", attachment.mime);+ res.send(attachment.getContent());+ }} else {res.status(400).json({ message: "Requested attachment is not a shareable image" });}diff --cc apps/server/src/www.tsindex 26d64a22e9,31f50b1933..715876539b--- a/apps/server/src/www.ts+++ b/apps/server/src/www.ts@@@ -2,17 -4,15 +4,16 @@@ import fs from "fs"import http from "http";import https from "https";import tmp from "tmp";++ import buildApp from "./app.js";import config from "./services/config.js";- import log from "./services/log.js";- import appInfo from "./services/app_info.js";- import ws from "./services/ws.js";- import utils, { formatSize, formatUtcTime } from "./services/utils.js";- import port from "./services/port.js";+ import { registerOcrHandlers } from "./services/handlers.js";import host from "./services/host.js";- import buildApp from "./app.js";- import type { Express } from "express";+ import { getLog } from "@triliumnext/core";+ import port from "./services/port.js";import { getDbSize } from "./services/sql_init.js";+import { isScriptingEnabled } from "./services/scripting_guard.js";+ import WebSocketMessagingProvider from "./services/ws_messaging_provider.js";const MINIMUM_NODE_VERSION = "20.0.0";@@@ -79,18 -88,10 +89,18 @@@ async function displayStartupMessage()if (cpuInfos && cpuInfos[0] !== undefined) {// https://github.com/zadam/trilium/pull/3957const cpuModel = (cpuInfos[0].model || "").trimEnd();- log.info(`💻 CPU: ${cpuModel} (${cpuInfos.length}-core @ ${cpuInfos[0].speed} Mhz)`);+ getLog().info(`💻 CPU: ${cpuModel} (${cpuInfos.length}-core @ ${cpuInfos[0].speed} Mhz)`);}- log.info(`💾 DB size: ${formatSize(getDbSize() * 1024)}`);+ getLog().info(`💾 DB size: ${utils.formatSize(getDbSize() * 1024)}`);++ if (isScriptingEnabled()) {- log.info("WARNING: Script execution is ENABLED. Scripts have full server access including " +++ getLog().info("WARNING: Script execution is ENABLED. Scripts have full server access including " ++ "filesystem, network, and OS commands. Only enable in trusted environments.");+ } else {- log.info("Script execution is DISABLED. Set [Scripting] enabled=true in config.ini to enable.");++ getLog().info("Script execution is DISABLED. Set [Scripting] enabled=true in config.ini to enable.");+ }+- log.info("");+ getLog().info("");}function startHttpServer(app: Express) {diff --cc packages/trilium-core/src/routes/api/image.tsindex 1505f1c505,48db824d7f..06496c6e4a--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@@ -142,8 -145,8 +145,9 @@@ export defaultupdateImage};- function sendSanitizedSvg(res: Response, content: string | Buffer) {- const svgString = typeof content === "string" ? content : content.toString("utf-8");- setSvgHeaders(res);+ function sendSanitizedSvg(res: Response, content: string | Uint8Array) {+ const svgString = unwrapStringOrBuffer(content);- res.set("Content-Security-Policy", "script-src 'none'");++ res.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:");++ res.set("X-Content-Type-Options", "nosniff");res.send(sanitizeSvg(svgString));}diff --cc packages/trilium-core/src/routes/api/options.tsindex 7e2bca00e4,c7eba5aa04..175f4ddb51--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@@ -174,10 -187,7 +201,10 @@@ function update(name: string, value: st}if (name !== "openNoteContexts") {- getLog().info(`Updating option '${name}' to '${value}'`);+ const logValue = (WRITE_ONLY_OPTIONS as Set<string>).has(name)+ ? "[redacted]"+ : value;- log.info(`Updating option '${name}' to '${logValue}'`);++ getLog().info(`Updating option '${name}' to '${logValue}'`);}optionService.setOption(name as OptionNames, value);diff --cc packages/trilium-core/src/routes/api/script.tsindex 2cf7fecb27,0a46725121..c8998a981e--- a/packages/trilium-core/src/routes/api/script.ts+++ b/packages/trilium-core/src/routes/api/script.ts@@@ -5,10 -5,9 +5,10 @@@ import type { Request } from "express"import becca from "../../becca/becca.js";import attributeService from "../../services/attributes.js";import scriptService, { type Bundle } from "../../services/script.js";- import sql from "../../services/sql.js";import syncService from "../../services/sync.js";- import { safeExtractMessageAndStackFromError } from "../../services/utils.js";-import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";+import { assertScriptingEnabled, isScriptingEnabled } from "../../services/scripting_guard.js";+ import { getSql } from "../../services/sql/index.js";++import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";interface ScriptBody {script: string;@@@ -87,16 -80,10 +87,14 @@@ function getStartupBundles(req: Request}function getWidgetBundles() {+ if (!isScriptingEnabled()) {+ return [];+ }+if (!process.env.TRILIUM_SAFE_MODE) {return getBundlesWithLabel("widget");- }+ }return [];-}function getRelationBundles(req: Request<{ noteId: string, relationName: string }>) {diff --cc packages/trilium-core/src/routes/api/sql.tsindex 13cf40f64c,3df8cd3b77..c180f7a216--- a/packages/trilium-core/src/routes/api/sql.ts+++ b/packages/trilium-core/src/routes/api/sql.ts@@@ -1,10 -1,9 +1,10 @@@import type { Request } from "express";import becca from "../../becca/becca.js";- import ValidationError from "../../errors/validation_error.js";- import sql from "../../services/sql.js";- import { safeExtractMessageAndStackFromError } from "../../services/utils.js";+ import { getSql } from "../../services/sql/index.js";+ import { ValidationError } from "../../errors.js";+import { assertSqlConsoleEnabled } from "../../services/scripting_guard.js";+ import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";interface Table {name: string;@@@ -26,7 -26,7 +27,8 @@@ function getSchema()}function execute(req: Request<{ noteId: string }>) {+ assertSqlConsoleEnabled();+ const sql = getSql();const note = becca.getNoteOrThrow(req.params.noteId);const content = note.getContent();diff --cc packages/trilium-core/src/services/bulk_actions.tsindex fd5eb52b7f,87a681b7f3..b289737cfa--- a/packages/trilium-core/src/services/bulk_actions.ts+++ b/packages/trilium-core/src/services/bulk_actions.ts@@@ -1,14 -1,12 +1,15 @@@- import log from "./log.js";- import becca from "../becca/becca.js";- import cloningService from "./cloning.js";- import branchService from "./branches.js";- import { randomString } from "./utils.js";+ import { ActionHandlers, BulkAction, BulkActionData } from "@triliumnext/commons";+ import branchService from "./branches";import eraseService from "./erase.js";++ import becca from "../becca/becca.js";import type BNote from "../becca/entities/bnote.js";- import { ActionHandlers, BulkAction, BulkActionData } from "@triliumnext/commons";+ import cloningService from "./cloning.js";-import { randomString } from "./utils/index.js";+ import { getLog } from "./log";+import { evaluateTemplate } from "./safe_template.js";+import { executeBundle } from "./script.js";+import { assertScriptingEnabled } from "./scripting_guard.js";++import { randomString } from "./utils/index.js";type ActionHandler<T> = (action: T, note: BNote) => void;@@@ -107,9 -106,8 +108,9 @@@ const ACTION_HANDLERS: ActionHandlerMa}},executeScript: (action, note) => {+ assertScriptingEnabled();if (!action.script || !action.script.trim()) {- log.info("Ignoring executeScript since the script is empty.");+ getLog().info("Ignoring executeScript since the script is empty.");return;}diff --cc packages/trilium-core/src/services/config.tsindex 0000000000,76a3c2914a..fe9390e1d7mode 000000,100644..100644--- a/packages/trilium-core/src/services/config.ts+++ b/packages/trilium-core/src/services/config.ts@@@ -1,0 -1,52 +1,60 @@@+ /**+ * Subset of application config consumed by trilium-core.+ *+ * The full config (INI parsing, env-var precedence, etc.) lives on the server+ * side and is not available in browser-based runtimes like standalone. Core+ * only needs these fields, so the host (server / desktop / standalone) injects+ * them via `initConfig()` at startup.+ *+ * Empty strings / `false` signal "no override" — `sync_options` then falls+ * back to the DB option. Standalone uses an all-empty config by default.+ */+ export interface CoreConfig {+ General: {+ instanceName: string;+ readOnly: boolean;+ };+ Sync: {+ syncServerHost: string;+ syncServerTimeout: string;+ syncProxy: string;+ };++ Scripting: {++ enabled: boolean;++ sqlConsoleEnabled: boolean;++ };+ }++ const EMPTY_CONFIG: CoreConfig = {+ General: {+ instanceName: "",+ readOnly: false+ },+ Sync: {+ syncServerHost: "",+ syncServerTimeout: "",+ syncProxy: ""++ },++ Scripting: {++ enabled: false,++ sqlConsoleEnabled: false+ }+ };++ let injected: CoreConfig = EMPTY_CONFIG;++ export function initConfig(config: CoreConfig) {+ injected = config;+ }++ export function getConfig(): CoreConfig {+ return injected;+ }++ // Legacy `import config from "./config.js"` reads stay working: the Proxy+ // resolves each top-level access against the currently injected config, so+ // existing call sites that read inside functions (e.g. `config.General.readOnly`+ // inside a request handler) see the live values without modification.+ export default new Proxy({} as CoreConfig, {+ get: (_target, prop: string) => injected[prop as keyof CoreConfig]+ });diff --cc packages/trilium-core/src/services/handlers.tsindex 0000000000,0ad5d22286..f4c828aaa1mode 000000,100644..100644--- a/packages/trilium-core/src/services/handlers.ts+++ b/packages/trilium-core/src/services/handlers.ts@@@ -1,0 -1,251 +1,252 @@@+ import eventService from "./events.js";++import { isScriptingEnabled } from "./scripting_guard.js";+ import scriptService from "./script.js";+ import treeService from "./tree.js";+ import noteService from "./notes.js";+ import becca from "../becca/becca.js";+ import BAttribute from "../becca/entities/battribute.js";+ import hiddenSubtreeService from "./hidden_subtree.js";+ import oneTimeTimer from "./one_time_timer.js";+ import type BNote from "../becca/entities/bnote.js";+ import type AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";+ import { DefinitionObject } from "@triliumnext/commons";++ type Handler = (definition: DefinitionObject, note: BNote, targetNote: BNote) => void;++ function runAttachedRelations(note: BNote, relationName: string, originEntity: AbstractBeccaEntity<any>) {- if (!note) {++ if (!note || !isScriptingEnabled()) {+ return;+ }++ // the same script note can get here with multiple ways, but execute only once+ const notesToRun = new Set(+ note+ .getRelations(relationName)+ .map((relation) => relation.getTargetNote())+ .filter((note) => !!note) as BNote[]+ );++ for (const noteToRun of notesToRun) {+ scriptService.executeNoteNoException(noteToRun, { originEntity });+ }+ }++ eventService.subscribe(eventService.NOTE_TITLE_CHANGED, (note) => {+ runAttachedRelations(note, "runOnNoteTitleChange", note);++ if (!note.isRoot()) {+ const noteFromCache = becca.notes[note.noteId];++ if (!noteFromCache) {+ return;+ }++ for (const parentNote of noteFromCache.parents) {+ if (parentNote.hasLabel("sorted")) {+ treeService.sortNotesIfNeeded(parentNote.noteId);+ }+ }+ }+ });++ eventService.subscribe([eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED], ({ entityName, entity }) => {+ if (entityName === "attributes") {+ runAttachedRelations(entity.getNote(), "runOnAttributeChange", entity);++ if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {+ handleSortedAttribute(entity);+ } else if (entity.type === "label") {+ handleMaybeSortingLabel(entity);+ }+ } else if (entityName === "notes") {+ // ENTITY_DELETED won't trigger anything since all branches/attributes are already deleted at this point+ runAttachedRelations(entity, "runOnNoteChange", entity);+ }+ });++ eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {+ if (entityName === "branches") {+ const parentNote = becca.getNote(entity.parentNoteId);++ if (parentNote?.hasLabel("sorted")) {+ treeService.sortNotesIfNeeded(parentNote.noteId);+ }++ const childNote = becca.getNote(entity.noteId);++ if (childNote) {+ runAttachedRelations(childNote, "runOnBranchChange", entity);+ }+ }+ });++ eventService.subscribe(eventService.NOTE_CONTENT_CHANGE, ({ entity }) => {+ runAttachedRelations(entity, "runOnNoteContentChange", entity);+ });++ eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) => {+ if (entityName === "attributes") {+ runAttachedRelations(entity.getNote(), "runOnAttributeCreation", entity);++ if (entity.type === "relation" && entity.name === "template") {+ const note = becca.getNote(entity.noteId);+ if (!note) {+ return;+ }++ const templateNote = becca.getNote(entity.value);++ if (!templateNote) {+ return;+ }++ const content = note.getContent();++ if (+ note.hasStringContent() &&+ typeof content === "string" &&+ // if the note has already content we're not going to overwrite it with template's one+ (!content || content.trim().length === 0) &&+ templateNote.hasStringContent()+ ) {+ const templateNoteContent = templateNote.getContent();++ if (templateNoteContent) {+ note.setContent(templateNoteContent);+ }++ note.type = templateNote.type;+ note.mime = templateNote.mime;+ note.save();+ }++ // we'll copy the children notes only if there's none so far+ // this protects against e.g. multiple assignment of template relation resulting in having multiple copies of the subtree+ if (note.getChildNotes().length === 0 && !note.isDescendantOfNote(templateNote.noteId)) {+ noteService.duplicateSubtreeWithoutRoot(templateNote.noteId, note.noteId);+ }+ } else if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {+ handleSortedAttribute(entity);+ } else if (entity.type === "label") {+ handleMaybeSortingLabel(entity);+ }+ } else if (entityName === "branches") {+ runAttachedRelations(entity.getNote(), "runOnBranchCreation", entity);++ if (entity.parentNote?.hasLabel("sorted")) {+ treeService.sortNotesIfNeeded(entity.parentNoteId);+ }+ } else if (entityName === "notes") {+ runAttachedRelations(entity, "runOnNoteCreation", entity);+ }+ });++ eventService.subscribe(eventService.CHILD_NOTE_CREATED, ({ parentNote, childNote }) => {+ runAttachedRelations(parentNote, "runOnChildNoteCreation", childNote);+ });++ function processInverseRelations(entityName: string, entity: BAttribute, handler: Handler) {+ if (entityName === "attributes" && entity.type === "relation") {+ const note = entity.getNote();+ const relDefinitions = note.getLabels(`relation:${entity.name}`);++ for (const relDefinition of relDefinitions) {+ const definition = relDefinition.getDefinition();++ if (definition.inverseRelation && definition.inverseRelation.trim()) {+ const targetNote = entity.getTargetNote();++ if (targetNote) {+ handler(definition, note, targetNote);+ }+ }+ }+ }+ }++ function handleSortedAttribute(entity: BAttribute) {+ treeService.sortNotesIfNeeded(entity.noteId);++ if (entity.isInheritable) {+ const note = becca.notes[entity.noteId];++ if (note) {+ for (const noteId of note.getSubtreeNoteIds()) {+ treeService.sortNotesIfNeeded(noteId);+ }+ }+ }+ }++ function handleMaybeSortingLabel(entity: BAttribute) {+ // check if this label is used for sorting, if yes force re-sort+ const note = becca.notes[entity.noteId];++ // this will not work on deleted notes, but in that case we don't really need to re-sort+ if (note) {+ for (const parentNote of note.getParentNotes()) {+ const sorted = parentNote.getLabelValue("sorted");+ if (sorted === null) {+ // checking specifically for null since that means the label doesn't exist+ // empty valued "sorted" is still valid+ continue;+ }++ if (+ sorted.includes(entity.name) || // hacky check if this label is used in the sort+ entity.name === "top" ||+ entity.name === "bottom"+ ) {+ treeService.sortNotesIfNeeded(parentNote.noteId);+ }+ }+ }+ }++ eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {+ processInverseRelations(entityName, entity, (definition, note, targetNote) => {+ // we need to make sure that also target's inverse attribute exists and if not, then create it+ // inverse attribute has to target our note as well+ const hasInverseAttribute = targetNote.getRelations(definition.inverseRelation).some((attr) => attr.value === note.noteId);++ if (!hasInverseAttribute) {+ new BAttribute({+ noteId: targetNote.noteId,+ type: "relation",+ name: definition.inverseRelation || "",+ value: note.noteId,+ isInheritable: entity.isInheritable+ }).save();++ // becca will not be updated before we'll check from the other side which would create infinite relation creation (#2269)+ targetNote.invalidateThisCache();+ }+ });+ });++ eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) => {+ processInverseRelations(entityName, entity, (definition: DefinitionObject, note: BNote, targetNote: BNote) => {+ // if one inverse attribute is deleted, then the other should be deleted as well+ const relations = targetNote.getOwnedRelations(definition.inverseRelation);++ for (const relation of relations) {+ if (relation.value === note.noteId) {+ relation.markAsDeleted();+ }+ }+ });++ if (entityName === "branches") {+ runAttachedRelations(entity.getNote(), "runOnBranchDeletion", entity);+ }++ if (entityName === "notes" && entity.noteId.startsWith("_")) {+ // "named" note has been deleted, we will probably need to rebuild the hidden subtree+ // scheduling so that bulk deletes won't trigger so many checks+ oneTimeTimer.scheduleExecution("hidden-subtree-check", 1000, () => hiddenSubtreeService.checkHiddenSubtree());+ }+ });++ export default {+ runAttachedRelations+ };diff --cc packages/trilium-core/src/services/notes.tsindex 0304d3dd35,9d8b3e29bd..7204a192bf--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@@ -24,11 -20,13 +20,14 @@@ import noteTypesService from "./note_tyimport optionService from "./options.js";import request from "./request.js";import revisionService from "./revisions.js";+import { evaluateTemplateSafe } from "./safe_template.js";- import sql from "./sql.js";+ import { sanitizeHtml } from "./sanitizer.js";+ import { getSql } from "./sql/index.js";import type TaskContext from "./task_context.js";- import { isSafeUrlForFetch } from "./url_validator.js";+ import { decodeBase64 } from "./utils/binary.js";+ import date_utils from "./utils/date.js";+ import { newEntityId, quoteRegex, toMap, unescapeHtml } from "./utils/index.js";+ import { basename } from "./utils/path.js";import ws from "./ws.js";interface FoundLink {@@@ -121,17 -147,17 +148,17 @@@ function getNewNoteTitle(parentNote: BNconst titleTemplate = parentNote.getLabelValue("titleTemplate");if (titleTemplate !== null) {- const now = dayjs(cls.getLocalNowDateTime() || new Date());- try {- const now = dayjs(date_utils.localNowDateTime() || new Date());-- // "officially" injected values:- // - now- // - parentNote-- title = eval(`\`${titleTemplate}\``);- } catch (e: any) {- getLog().error(`Title template of note '${parentNote.noteId}' failed with: ${e.message}`);- }++ const now = dayjs(date_utils.localNowDateTime() || new Date());++ // "officially" injected values:+ // - now+ // - parentNote+ title = evaluateTemplateSafe(+ titleTemplate,+ { now, parentNote },+ title,+ `titleTemplate of note '${parentNote.noteId}'`+ );}// this isn't in theory a good place to sanitize title, but this will catch a lot of XSS attempts.diff --cc packages/trilium-core/src/services/safe_template.tsindex 0000000000,0000000000..d22091b737new file mode 100644--- /dev/null+++ b/packages/trilium-core/src/services/safe_template.ts@@@ -1,0 -1,0 +1,185 @@@++/**++ * Safe template evaluator that replaces eval()-based template string interpolation.++ *++ * Supports only a controlled set of operations within ${...} expressions:++ * - Property access chains: `obj.prop.subprop`++ * - Method calls with a single string literal argument: `obj.method('arg')`++ * - Chained combinations: `obj.prop.method('arg')`++ *++ * This prevents arbitrary code execution while supporting the documented++ * titleTemplate and bulk rename use cases:++ * - ${now.format('YYYY-MM-DD')}++ * - ${parentNote.title}++ * - ${parentNote.getLabelValue('authorName')}++ * - ${note.title}++ * - ${note.dateCreatedObj.format('MM-DD')}++ */++++import { getLog } from "./log.js";++++/** Allowed method names that can be called on template variables. */++const ALLOWED_METHODS = new Set([++ "format",++ "getLabelValue",++ "getLabel",++ "getLabelValues",++ "getRelationValue",++ "getAttributeValue"++]);++++/** Allowed property names that can be accessed on template variables. */++const ALLOWED_PROPERTIES = new Set([++ "title",++ "type",++ "mime",++ "noteId",++ "dateCreated",++ "dateModified",++ "utcDateCreated",++ "utcDateModified",++ "dateCreatedObj",++ "utcDateCreatedObj",++ "isProtected",++ "content"++]);++++interface TemplateVariables {++ [key: string]: unknown;++}++++/**++ * Evaluates a template string safely without using eval().++ *++ * Template strings can contain ${...} expressions which are evaluated++ * against the provided variables map.++ *++ * @param template - The template string, e.g. "Note: ${now.format('YYYY-MM-DD')}"++ * @param variables - Map of variable names to their values++ * @returns The interpolated string++ * @throws Error if an expression cannot be safely evaluated++ */++export function evaluateTemplate(template: string, variables: TemplateVariables): string {++ return template.replace(/\$\{([^}]+)\}/g, (_match, expression: string) => {++ const result = evaluateExpression(expression.trim(), variables);++ return result == null ? "" : String(result);++ });++}++++/**++ * Evaluates a single expression like "now.format('YYYY-MM-DD')" or "parentNote.title".++ *++ * Supported forms:++ * - `varName` -> variables[varName]++ * - `varName.prop` -> variables[varName].prop++ * - `varName.prop1.prop2` -> variables[varName].prop1.prop2++ * - `varName.method('arg')` -> variables[varName].method('arg')++ * - `varName.prop.method('arg')` -> variables[varName].prop.method('arg')++ */++function evaluateExpression(expr: string, variables: TemplateVariables): unknown {++ // First, check for a method call at the end: .methodName('arg') or .methodName("arg")++ const methodCallMatch = expr.match(++ /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*(?:'([^']*)'|"([^"]*)")\s*\)$/++ );++++ if (methodCallMatch) {++ const [, chainStr, methodName, singleQuoteArg, doubleQuoteArg] = methodCallMatch;++ const methodArg = singleQuoteArg !== undefined ? singleQuoteArg : doubleQuoteArg;++++ if (!ALLOWED_METHODS.has(methodName)) {++ throw new Error(`Method '${methodName}' is not allowed in template expressions`);++ }++++ const target = resolvePropertyChain(chainStr, variables);++ if (target == null) {++ return null;++ }++++ const method = (target as Record<string, unknown>)[methodName];++ if (typeof method !== "function") {++ throw new Error(`'${methodName}' is not a function on the resolved object`);++ }++++ return (method as (arg: string) => unknown).call(target, methodArg as string);++ }++++ // Check for a no-arg method call at the end: .methodName()++ const noArgMethodMatch = expr.match(++ /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*\)$/++ );++++ if (noArgMethodMatch) {++ const [, chainStr, methodName] = noArgMethodMatch;++++ if (!ALLOWED_METHODS.has(methodName)) {++ throw new Error(`Method '${methodName}' is not allowed in template expressions`);++ }++++ const target = resolvePropertyChain(chainStr, variables);++ if (target == null) {++ return null;++ }++++ const method = (target as Record<string, unknown>)[methodName];++ if (typeof method !== "function") {++ throw new Error(`'${methodName}' is not a function on the resolved object`);++ }++++ return (method as () => unknown).call(target);++ }++++ // Otherwise it's a pure property chain: varName.prop1.prop2...++ const propChainMatch = expr.match(/^[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*$/);++ if (!propChainMatch) {++ throw new Error(`Template expression '${expr}' is not a supported expression. ` +++ `Only property access and whitelisted method calls are allowed.`);++ }++++ return resolvePropertyChain(expr, variables);++}++++/**++ * Resolves a dot-separated property chain like "parentNote.title" against variables.++ */++function resolvePropertyChain(chain: string, variables: TemplateVariables): unknown {++ const parts = chain.split(".");++ const rootName = parts[0];++++ if (!(rootName in variables)) {++ throw new Error(`Unknown variable '${rootName}' in template expression`);++ }++++ let current: unknown = variables[rootName];++++ for (let i = 1; i < parts.length; i++) {++ if (current == null) {++ return null;++ }++++ const prop = parts[i];++ if (!ALLOWED_PROPERTIES.has(prop)) {++ throw new Error(`Property '${prop}' is not allowed in template expressions`);++ }++++ current = (current as Record<string, unknown>)[prop];++ }++++ return current;++}++++/**++ * Convenience wrapper that evaluates a template and catches errors,++ * logging them and returning the fallback value.++ */++export function evaluateTemplateSafe(++ template: string,++ variables: TemplateVariables,++ fallback: string,++ contextDescription: string++): string {++ try {++ return evaluateTemplate(template, variables);++ } catch (e: any) {++ getLog().error(`Template evaluation for ${contextDescription} failed with: ${e.message}`);++ return fallback;++ }++}diff --cc packages/trilium-core/src/services/scheduler.tsindex 64d814692c,bbfe78eb88..b4e4b900dc--- a/packages/trilium-core/src/services/scheduler.ts+++ b/packages/trilium-core/src/services/scheduler.ts@@@ -1,14 -1,13 +1,14 @@@- import scriptService from "./script.js";- import cls from "./cls.js";- import sqlInit from "./sql_init.js";- import config from "./config.js";- import log from "./log.js";+ import type BNote from "../becca/entities/bnote.js";import attributeService from "../services/attributes.js";+ import config from "./config.js";+ import * as cls from "./context.js";import hiddenSubtreeService from "./hidden_subtree.js";- import type BNote from "../becca/entities/bnote.js";+ import { getLog } from "./log.js";import options from "./options.js";- import { getLastProtectedSessionOperationDate, isProtectedSessionAvailable, resetDataKey } from "./protected_session.js";+ import protected_session from "./protected_session.js";+ import scriptService from "./script.js";+import { isScriptingEnabled } from "./scripting_guard.js";+ import sqlInit from "./sql_init.js";import ws from "./ws.js";function getRunAtHours(note: BNote): number[] {diff --cc packages/trilium-core/src/services/script_context.tsindex a106cc3445,083be5df19..6326466d7e--- a/packages/trilium-core/src/services/script_context.ts+++ b/packages/trilium-core/src/services/script_context.ts@@@ -1,53 -1,8 +1,53 @@@- import { toObject } from "./utils.js";- import BackendScriptApi from "./backend_script_api.js";import type BNote from "../becca/entities/bnote.js";+ import BackendScriptApi from "./backend_script_api.js";import type { ApiParams } from "./backend_script_api_interface.js";+ import { toObject } from "./utils/index.js";+/**+ * IMPORTANT: This module allowlist/blocklist is a defense-in-depth measure only.+ * It is NOT a security sandbox. Scripts execute via eval() in the main Node.js+ * process and can bypass these restrictions through globalThis, process, etc.+ * The actual security boundary is the [Scripting] enabled=false config toggle,+ * which prevents script execution entirely.+ *+ * Modules that are safe for user scripts to require.+ * Note-based modules (resolved via note title matching) are handled separately+ * and always allowed regardless of this list.+ */+const ALLOWED_MODULES = new Set([+ // Safe utility libraries+ "dayjs",+ "marked",+ "turndown",+ "cheerio",+ "axios",+ "xml2js",+ "escape-html",+ "sanitize-html",+ "lodash",+]);++/**+ * Modules that are ALWAYS blocked even when scripting is enabled.+ * These provide OS-level access that makes RCE trivial.+ */+const BLOCKED_MODULES = new Set([+ "child_process",+ "cluster",+ "dgram",+ "dns",+ "fs",+ "fs/promises",+ "net",+ "os",+ "path",+ "process",+ "tls",+ "worker_threads",+ "v8",+ "vm",+]);+type Module = {exports: any[];};diff --cc packages/trilium-core/src/services/scripting_guard.tsindex 0000000000,0000000000..82fdaeffe2new file mode 100644--- /dev/null+++ b/packages/trilium-core/src/services/scripting_guard.ts@@@ -1,0 -1,0 +1,28 @@@++import config from "./config.js";++import { isElectron } from "./utils/index.js";++++/**++ * Throws if scripting is disabled. Desktop (Electron) always allows scripting.++ */++export function assertScriptingEnabled(): void {++ if (isElectron() || config.Scripting.enabled) {++ return;++ }++ throw new Error(++ "Script execution is disabled. Set [Scripting] enabled=true in config.ini or " +++ "TRILIUM_SCRIPTING_ENABLED=true to enable. WARNING: Scripts have full server access."++ );++}++++export function assertSqlConsoleEnabled(): void {++ if (isElectron() || config.Scripting.sqlConsoleEnabled) {++ return;++ }++ throw new Error(++ "SQL console is disabled. Set [Scripting] sqlConsoleEnabled=true in config.ini to enable."++ );++}++++export function isScriptingEnabled(): boolean {++ return isElectron() || config.Scripting.enabled;++}diff --cc packages/trilium-core/src/services/search/services/search.tsindex 37f3efff1c,de61756ef8..47ca78766a--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@@ -1,25 -1,22 +1,23 @@@- "use strict";-import normalizeString from "normalize-strings";- import lex from "./lex.js";- import handleParens from "./handle_parens.js";- import parse from "./parse.js";- import SearchResult from "../search_result.js";- import SearchContext from "../search_context.js";+ import striptags from "striptags";+import becca from "../../../becca/becca.js";- import beccaService from "../../../becca/becca_service.js";- import { normalize, escapeHtml, escapeRegExp } from "../../utils.js";- import log from "../../log.js";- import hoistedNoteService from "../../hoisted_note.js";+ import becca_service from "../../../becca/becca_service.js";import type BNote from "../../../becca/entities/bnote.js";- import type BAttribute from "../../../becca/entities/battribute.js";- import type { SearchParams, TokenStructure } from "./types.js";- import type Expression from "../expressions/expression.js";- import sql from "../../sql.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 striptags from "striptags";- import protectedSessionService from "../../protected_session.js";+ import { escapeHtml, escapeRegExp } from "../../utils/index.js";+ import type Expression from "../expressions/expression.js";+ import SearchContext from "../search_context.js";+ import SearchResult from "../search_result.js";+ import handleParens from "./handle_parens.js";+ import lex from "./lex.js";+ import parse from "./parse.js";+ import type { SearchParams, TokenStructure } from "./types.js";+ import { getSql } from "../../sql/index.js";export interface SearchNoteResult {searchResultNoteIds: string[];diff --cc packages/trilium-core/src/services/sync_update.tsindex 599a456b85,233ceba514..34974ec282--- a/packages/trilium-core/src/services/sync_update.ts+++ b/packages/trilium-core/src/services/sync_update.ts@@@ -1,13 -1,13 +1,15 @@@- import sql from "./sql.js";- import log from "./log.js";- import entityChangesService from "./entity_changes.js";- import eventService from "./events.js";- import entityConstructor from "../becca/entity_constructor.js";- import ws from "./ws.js";import type { EntityChange, EntityChangeRecord, EntityRow } from "@triliumnext/commons";+import attributeService from "./attributes.js";+import { isScriptingEnabled } from "./scripting_guard.js";+ import entityChangesService from "./entity_changes.js";+ import { getLog } from "./log.js";+ import { getSql } from "./sql/index.js";+ import ws from "./ws.js";+ import { default as eventService } from "./events.js";+ import entity_constructor from "../becca/entity_constructor.js";+ import { decodeBase64 } from "./utils/binary.js";+interface UpdateContext {alreadyErased: number;erased: number;@@@ -93,19 -93,7 +95,19 @@@ function updateNormalEntity(remoteEC: EpreProcessContent(remoteEC, remoteEntityRow);+ // When scripting is disabled, prefix dangerous attributes with 'disabled:'+ // Same pattern as safeImport in attributes.ts+ if (remoteEC.entityName === "attributes" && !isScriptingEnabled()) {+ const attrRow = remoteEntityRow as Record<string, unknown>;+ if (typeof attrRow.type === "string" && typeof attrRow.name === "string"+ && !attrRow.isDeleted+ && attributeService.isAttributeDangerous(attrRow.type, attrRow.name)) {- log.info(`Sync: disabling dangerous attribute '${attrRow.name}' (scripting is disabled)`);++ getLog().info(`Sync: disabling dangerous attribute '${attrRow.name}' (scripting is disabled)`);+ attrRow.name = `disabled:${attrRow.name}`;+ }+ }+- sql.replace(remoteEC.entityName, remoteEntityRow);+ getSql().replace(remoteEC.entityName, remoteEntityRow);updateContext.updated[remoteEC.entityName] = updateContext.updated[remoteEC.entityName] || [];updateContext.updated[remoteEC.entityName].push(remoteEC.entityId);