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): remove duplicate SSRF implementation
Elian Doranc417c901dfe4
diff --git a/apps/server/src/services/safe_template.ts b/apps/server/src/services/safe_template.tsdeleted file mode 100644index eb71a4946a..0000000000--- a/apps/server/src/services/safe_template.ts+++ /dev/null@@ -1,188 +0,0 @@-/**- * 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 "@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) {- getLog().error(`Template evaluation for ${contextDescription} failed with: ${e.message}`);- return fallback;- }-}diff --git a/apps/server/src/services/svg_sanitizer.spec.ts b/apps/server/src/services/svg_sanitizer.spec.tsdeleted file mode 100644index a302c42d5e..0000000000--- a/apps/server/src/services/svg_sanitizer.spec.ts+++ /dev/null@@ -1,241 +0,0 @@-import { describe, expect, it } from "vitest";-import { sanitizeSvg } from "./svg_sanitizer.js";--describe("SVG Sanitizer", () => {- describe("removes dangerous elements", () => {- it("strips <script> tags with content", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><script>alert('XSS')</script><circle r="50"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<script");- expect(clean).not.toContain("alert");- expect(clean).toContain("<circle");- });-- it("strips <script> tags case-insensitively", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><SCRIPT>alert('XSS')</SCRIPT></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("SCRIPT");- expect(clean).not.toContain("alert");- });-- it("strips <script> tags with attributes", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><script type="text/javascript">alert('XSS')</script></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<script");- expect(clean).not.toContain("alert");- });-- it("strips self-closing <script> tags", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><script src="evil.js"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<script");- expect(clean).not.toContain("evil.js");- });-- it("strips <foreignObject> elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><foreignObject><body xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></body></foreignObject></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("foreignObject");- expect(clean).not.toContain("alert");- });-- it("strips <iframe> elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><iframe src="https://evil.com"></iframe></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<iframe");- expect(clean).not.toContain("evil.com");- });-- it("strips <embed> elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><embed src="evil.swf"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<embed");- });-- it("strips <object> elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><object data="evil.swf"></object></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<object");- });-- it("strips <link> elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><link rel="stylesheet" href="evil.css"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<link");- });-- it("strips <meta> elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><meta http-equiv="refresh" content="0;url=evil.com"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<meta");- });- });-- describe("removes event handler attributes", () => {- it("strips onload from SVG root", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg" onload="alert('XSS')"><circle r="50"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("onload");- expect(clean).not.toContain("alert");- expect(clean).toContain("<circle");- expect(clean).toContain("<svg");- });-- it("strips onclick from elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><circle r="50" onclick="alert('XSS')"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("onclick");- expect(clean).not.toContain("alert");- expect(clean).toContain("r=\"50\"");- });-- it("strips onerror from elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><image onerror="alert('XSS')" href="x"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("onerror");- expect(clean).not.toContain("alert");- });-- it("strips onmouseover from elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><rect onmouseover="alert('XSS')" width="100" height="100"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("onmouseover");- });-- it("strips onfocus from elements", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><rect onfocus="alert('XSS')" tabindex="0"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("onfocus");- });- });-- describe("removes dangerous URI schemes", () => {- it("strips javascript: URIs from href", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><a href="javascript:alert('XSS')"><text>Click</text></a></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("javascript:");- expect(clean).toContain("<text>Click</text>");- });-- it("strips javascript: URIs from xlink:href", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><a xlink:href="javascript:alert('XSS')"><text>Click</text></a></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("javascript:");- });-- it("strips data:text/html URIs", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><a href="data:text/html,<script>alert(1)</script>"><text>Click</text></a></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("data:text/html");- });-- it("strips vbscript: URIs", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><a href="vbscript:msgbox('XSS')"><text>Click</text></a></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("vbscript:");- });-- it("strips javascript: URIs with whitespace padding", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><a href=" javascript:alert(1)"><text>Click</text></a></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("javascript:");- });- });-- describe("removes xml-stylesheet processing instructions", () => {- it("strips xml-stylesheet PIs", () => {- const dirty = `<?xml-stylesheet type="text/xsl" href="evil.xsl"?><svg xmlns="http://www.w3.org/2000/svg"><circle r="50"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("xml-stylesheet");- expect(clean).toContain("<circle");- });- });-- describe("preserves legitimate SVG content", () => {- it("preserves basic SVG shapes", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="red"/><rect x="10" y="10" width="80" height="80" fill="blue"/></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toBe(svg);- });-- it("preserves SVG paths", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><path d="M10 10 L90 90" stroke="black" stroke-width="2"/></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toBe(svg);- });-- it("preserves SVG text elements", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><text x="50" y="50" font-size="20">Hello World</text></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toBe(svg);- });-- it("preserves SVG groups and transforms", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><g transform="translate(10,10)"><circle r="5"/></g></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toBe(svg);- });-- it("preserves SVG style elements with CSS (not script)", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><style>.cls{fill:red}</style><circle class="cls" r="50"/></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toContain("<style>");- expect(clean).toContain("fill:red");- });-- it("preserves SVG defs and gradients", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="grad"><stop offset="0%" stop-color="red"/><stop offset="100%" stop-color="blue"/></linearGradient></defs><rect fill="url(#grad)" width="100" height="100"/></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toContain("linearGradient");- expect(clean).toContain("url(#grad)");- });-- it("preserves safe href attributes (non-javascript)", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><a href="https://example.com"><text>Link</text></a></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toContain(`href="https://example.com"`);- });-- it("preserves data: URIs for images (non-HTML)", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"><image href="data:image/png;base64,abc123"/></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toContain("data:image/png;base64,abc123");- });-- it("preserves empty SVG", () => {- const svg = `<svg xmlns="http://www.w3.org/2000/svg"></svg>`;- const clean = sanitizeSvg(svg);- expect(clean).toBe(svg);- });- });-- describe("handles edge cases", () => {- it("handles Buffer input", () => {- const svg = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`);- const clean = sanitizeSvg(svg);- expect(clean).not.toContain("<script");- });-- it("handles multiple script tags", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle r="50"/><script>alert(2)</script></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("<script");- expect(clean).toContain("<circle");- });-- it("handles mixed dangerous content", () => {- const dirty = `<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"><script>alert(2)</script><foreignObject><body xmlns="http://www.w3.org/1999/xhtml"><img onerror="alert(3)"/></body></foreignObject><circle r="50" onclick="alert(4)"/></svg>`;- const clean = sanitizeSvg(dirty);- expect(clean).not.toContain("alert");- expect(clean).not.toContain("onload");- expect(clean).not.toContain("<script");- expect(clean).not.toContain("foreignObject");- expect(clean).not.toContain("onclick");- expect(clean).toContain("<circle");- });-- it("handles empty string input", () => {- expect(sanitizeSvg("")).toBe("");- });- });-});diff --git a/apps/server/src/services/svg_sanitizer.ts b/apps/server/src/services/svg_sanitizer.tsdeleted file mode 100644index 7fdc8cb4f8..0000000000--- a/apps/server/src/services/svg_sanitizer.ts+++ /dev/null@@ -1,158 +0,0 @@-/**- * SVG sanitizer to prevent stored XSS via malicious SVG content.- *- * SVG files can contain embedded JavaScript via <script> tags, event handler- * attributes (onload, onclick, etc.), <foreignObject> elements, and- * javascript: URIs. This sanitizer strips all such dangerous constructs- * while preserving legitimate SVG rendering elements.- *- * Defense-in-depth: SVG responses also receive a restrictive- * Content-Security-Policy header (see {@link setSvgHeaders}) to block- * script execution even if sanitization is bypassed.- */--import type { Response } from "express";--// Elements that MUST be removed from SVG (they can execute code or embed arbitrary HTML)-const DANGEROUS_ELEMENTS = new Set([- "script",- "foreignobject",- "iframe",- "embed",- "object",- "applet",- "base",- "link", // can load external resources- "meta",-]);--// Attribute prefixes/names that indicate event handlers-const EVENT_HANDLER_PATTERN = /^on[a-z]/i;--// Dangerous attribute values (javascript:, data: with script content, vbscript:)-const DANGEROUS_URI_PATTERN = /^\s*(javascript|vbscript|data\s*:\s*text\/html)/i;--// Attributes that can contain URIs-const URI_ATTRIBUTES = new Set([- "href",- "xlink:href",- "src",- "action",- "formaction",- "data",-]);--// SVG "set" and "animate" elements can modify attributes to dangerous values-const DANGEROUS_ANIMATION_ATTRIBUTES = new Set([- "attributename",-]);--/**- * Sanitizes SVG content by removing dangerous elements and attributes- * that could lead to script execution (XSS).- *- * This uses regex-based parsing rather than a full DOM parser to avoid- * adding heavy dependencies. The approach is conservative: it removes- * known-dangerous constructs rather than allowlisting, but combined with- * the CSP header this provides robust protection.- */-export function sanitizeSvg(svg: string | Buffer): string {- let content = typeof svg === "string" ? svg : svg.toString("utf-8");-- // 1. Remove dangerous elements and their contents entirely.- // Use a case-insensitive regex that handles self-closing and content-bearing tags.- for (const element of DANGEROUS_ELEMENTS) {- // Remove opening+closing tag pairs (including content between them)- const pairRegex = new RegExp(- `<${element}[\\s>][\\s\\S]*?<\\/${element}\\s*>`,- "gi"- );- content = content.replace(pairRegex, "");-- // Remove self-closing variants- const selfClosingRegex = new RegExp(- `<${element}(\\s[^>]*)?\\/?>`,- "gi"- );- content = content.replace(selfClosingRegex, "");- }-- // 2. Remove event handler attributes (onclick, onload, onerror, etc.)- // and dangerous URI attributes from all remaining elements.- content = content.replace(/<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*?)?)(\s*\/?>)/g,- (_match, tagName, attrs, closing) => {- if (!attrs || !attrs.trim()) {- return `<${tagName}${closing}`;- }-- // Parse and filter attributes- const sanitizedAttrs = sanitizeAttributes(attrs);- return `<${tagName}${sanitizedAttrs}${closing}`;- }- );-- // 3. Remove processing instructions that could be exploited- content = content.replace(/<\?xml-stylesheet[^?]*\?>/gi, "");-- return content;-}--/**- * Sanitizes the attribute string of an SVG element by removing- * event handlers and dangerous URI values.- */-function sanitizeAttributes(attrString: string): string {- // Match individual attributes: name="value", name='value', name=value, or standalone name- return attrString.replace(- /\s+([a-zA-Z_:][\w:.-]*)\s*(?:=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g,- (fullMatch, attrName, dblVal, sglVal, unquotedVal) => {- const lowerAttrName = attrName.toLowerCase();- const attrValue = dblVal ?? sglVal ?? unquotedVal ?? "";-- // Remove all event handler attributes- if (EVENT_HANDLER_PATTERN.test(lowerAttrName)) {- return "";- }-- // Check URI-bearing attributes for dangerous schemes- if (URI_ATTRIBUTES.has(lowerAttrName)) {- if (DANGEROUS_URI_PATTERN.test(attrValue)) {- return "";- }- }-- // Block animation elements from targeting event handlers via attributeName- if (DANGEROUS_ANIMATION_ATTRIBUTES.has(lowerAttrName)) {- const targetAttr = attrValue.toLowerCase();- if (EVENT_HANDLER_PATTERN.test(targetAttr) || targetAttr === "href" || targetAttr === "xlink:href") {- return "";- }- }-- return fullMatch;- }- );-}--/**- * Sets security headers appropriate for SVG responses.- * This provides defense-in-depth: even if SVG sanitization is somehow- * bypassed, the CSP header prevents script execution.- */-export function setSvgHeaders(res: Response): void {- res.set("Content-Type", "image/svg+xml");- res.set("Cache-Control", "no-cache, no-store, must-revalidate");- // Restrictive CSP that allows SVG rendering but blocks all script execution,- // inline event handlers, and plugin-based content.- res.set(- "Content-Security-Policy",- "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:"- );- // Prevent SVG from being reinterpreted in a different MIME context- res.set("X-Content-Type-Options", "nosniff");-}--export default {- sanitizeSvg,- setSvgHeaders-};diff --git a/apps/server/src/services/url_validator.ts b/apps/server/src/services/url_validator.tsdeleted file mode 100644index 6267f1b2b8..0000000000--- a/apps/server/src/services/url_validator.ts+++ /dev/null@@ -1,140 +0,0 @@-/**- * 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 { 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)) {- getLog().info(`URL rejected - disallowed scheme '${parsed.protocol}': ${urlStr}`);- return false;- }-- if (isPrivateIP(parsed.hostname)) {- getLog().info(`URL rejected - private/internal IP '${parsed.hostname}': ${urlStr}`);- return false;- }-- return true;- } catch {- 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)) {- getLog().info(`LLM provider base URL rejected - disallowed scheme '${parsed.protocol}': ${urlStr}`);- return false;- }-- return true;- } catch {- getLog().info(`LLM provider base URL rejected - failed to parse: ${urlStr}`);- return false;- }-}diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 7204a192bf..7f1be4c281 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -1,5 +1,4 @@import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, type NoteType } from "@triliumnext/commons";-import fs from "fs";import html2plaintext from "html2plaintext";import { t } from "i18next";import url from "url";@@ -700,24 +699,20 @@ const imageUrlToAttachmentIdMapping: Record<string, string> = {};async function downloadImage(noteId: string, imageUrl: string) {const unescapedUrl = unescapeHtml(imageUrl);+ // SSRF protection: only allow http(s) URLs and block file:// and other schemes.try {- let imageBuffer: Uint8Array;-- if (imageUrl.toLowerCase().startsWith("file://")) {- imageBuffer = await new Promise((res, rej) => {- const localFilePath = imageUrl.substring("file://".length);-- return fs.readFile(localFilePath, (err, data) => {- if (err) {- rej(err);- } else {- res(data);- }- });- });- } else {- imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));+ const parsed = new URL(unescapedUrl);+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: only http/https URLs are allowed.`);+ return;}+ } catch {+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' rejected: invalid URL.`);+ return;+ }++ try {+ const imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));const parsedUrl = url.parse(unescapedUrl);const title = basename(parsedUrl.pathname || "");