Skip to content

Build your personal knowledge base with Trilium Notes

5.5 KB
Raw Blame
import { sanitizeUrl as sanitizeUrlInternal } from "@braintree/sanitize-url";
import { ALLOWED_PROTOCOLS, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";

import optionService from "./options.js";
import sanitize from "sanitize-html";
import sanitizeFileNameInternal from "sanitize-filename";

// intended mainly as protection against XSS via import
// secondarily, it (partly) protects against "CSS takeover"
// sanitize also note titles, label values etc. - there are so many usages which make it difficult
// to guarantee all of them are properly handled
export function sanitizeHtml(dirtyHtml: string) {
    if (!dirtyHtml) {
        return dirtyHtml;
    }

    // avoid H1 per https://github.com/zadam/trilium/issues/1552
    // demote H1, and if that conflicts with existing H2, demote that, etc
    const transformTags: Record<string, string> = {};
    const lowercasedHtml = dirtyHtml.toLowerCase();
    for (let i = 1; i < 6; ++i) {
        if (lowercasedHtml.includes(`<h${i}`)) {
            transformTags[`h${i}`] = `h${i + 1}`;
        } else {
            break;
        }
    }

    // Get allowed tags from options, with fallback to default list if option not yet set
    let allowedTags: readonly string[];
    try {
        allowedTags = JSON.parse(optionService.getOption("allowedHtmlTags"));
    } catch (e) {
        // Fallback to default list if option doesn't exist or is invalid
        allowedTags = SANITIZER_DEFAULT_ALLOWED_TAGS;
    }

    const colorRegex = [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/, /^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/];
    const borderColorRegex = [ ...colorRegex, /^\s*transparent\s*$/ ];
    const sizeRegex = [/^\d+\.?\d*(?:px|em|%)$/];
    // The border styles CKEditor writes for tables and cells: the shorthand for a border with a
    // custom width, separate properties otherwise.
    const tableBorderStyles = {
        "border": [
            /^\s*\d+\.?\d*(?:px|em|%)\s*(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)\s*(#(0x)?[0-9a-fA-F]+|rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)|hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\))\s*$/
        ],
        "border-color": borderColorRegex,
        "--tn-border-color": borderColorRegex,
        "border-style": [
            /^\s*(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)\s*$/
        ],
        "border-width": sizeRegex
    };

    // to minimize document changes, compress H
    return sanitizeHtmlCustom(dirtyHtml, {
        allowedTags: allowedTags as string[],
        allowedAttributes: {
            "*": ["class", "style", "title", "src", "href", "hash", "disabled", "align", "alt", "center", "data-*"],
            a: ["id"],
            h2: ["id"],
            li: ["id"],
            ol: ["start", "reversed"],
            // Collapsible blocks: keep the native open/closed state (e.g. preserved from a Notion import)
            // so the published/share view, which renders this HTML directly, reflects it.
            details: ["open"],
            input: ["type", "checked"],
            img: ["width", "height"],
            td: ["colspan", "rowspan"],
            th: ["colspan", "rowspan", "scope"]
        },
        allowedStyles: {
            "*": {
                color: colorRegex,
                "background-color": colorRegex,
                // Copies of the colors that the app's and the share theme's stylesheets adapt.
                "--tn-color": colorRegex,
                "--tn-background": colorRegex,
                "margin-left": sizeRegex,
                "padding-left": sizeRegex,
                "text-align": [/^\s*(left|center|right|justify)\s*$/],
                "list-style-type": [/^\s*(disc|circle|square|decimal|decimal-leading-zero|lower-latin|upper-latin|lower-alpha|upper-alpha|lower-roman|upper-roman|none)\s*$/]
            },
            figure: {
                float: [/^\s*(left|right|none)\s*$/],
                width: sizeRegex,
                height: sizeRegex,
                // The size of a resized embed.
                "--include-note-width": sizeRegex,
                "--include-note-height": sizeRegex
            },
            // The size of a resized embed that keeps its source in the note, as a code block.
            pre: {
                "--include-note-width": sizeRegex,
                "--include-note-height": sizeRegex
            },
            // The width of a resized video, saved as the `<section>` of its link preview.
            section: {
                "--include-note-width": sizeRegex
            },
            img: {
                // Allow fractional ratios too (e.g. OneNote reports 577.5×277.5 screen clippings).
                "aspect-ratio": [ /^\d+(\.\d+)?\/\d+(\.\d+)?$/ ],
                width: sizeRegex,
                height: sizeRegex
            },
            table: tableBorderStyles,
            td: tableBorderStyles,
            th: tableBorderStyles,
            col: {
                width: sizeRegex
            }
        },
        selfClosing: [ "img", "br", "hr", "area", "base", "basefont", "input", "link", "meta", "col" ],
        allowedSchemes: ALLOWED_PROTOCOLS,
        nonTextTags: ["head"],
        transformTags
    });
}

export function sanitizeHtmlCustom(dirtyHtml: string, config: sanitize.IOptions) {
    return sanitize(dirtyHtml, config);
}

export function sanitizeUrl(url: string) {
    return sanitizeUrlInternal(url).trim();
}

export function sanitizeFileName(fileName: string) {
    return sanitizeFileNameInternal(fileName);
}