Browse Source

AI content is rendered through an allowlist sanitizer: tb-markdown with sanitizeHtml renders plain HTML sanitized with DOMPurify, images load only from this origin or inline data, and styles keep text and box properties

pull/16882/head
Igor Kulikov 24 hours ago
parent
commit
05ab16b418
  1. 1
      ui-ngx/package.json
  2. 181
      ui-ngx/src/app/shared/components/markdown-html-sanitize.ts
  3. 4
      ui-ngx/src/app/shared/components/markdown.component.ts

1
ui-ngx/package.json

@ -59,6 +59,7 @@
"angular2-hotkeys": "^16.0.1",
"canvas-gauges": "^2.1.7",
"dayjs": "1.11.23",
"dompurify": "^3.3.3",
"echarts": "https://github.com/thingsboard/echarts/archive/5.5.4-TB.tar.gz",
"exceljs-hardened": "~5.1.0",
"flag-icons": "7.6.0",

181
ui-ngx/src/app/shared/components/markdown-html-sanitize.ts

@ -1,33 +1,172 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import DOMPurify, { UponSanitizeAttributeHookEvent } from 'dompurify';
const REMOVED_ELEMENTS = 'script,iframe,frame,frameset,object,embed,applet,link,meta,base,form,style,template,noscript,svg,math';
const ALLOWED_TAGS = [
'a', 'abbr', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'button', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del',
'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img',
'input', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'span', 'strong',
'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'u', 'ul', 'var', 'wbr'
];
const URL_ATTRIBUTES = new Set(['href', 'src', 'srcset', 'xlink:href', 'action', 'formaction', 'background', 'poster', 'data', 'ping']);
const UNSAFE_URL = /^(javascript|vbscript|data:(?!image\/(png|jpe?g|gif|webp|bmp);))/i;
const ALLOWED_ATTR = [
'abbr', 'align', 'alt', 'checked', 'cite', 'class', 'colspan', 'datetime', 'dir', 'disabled', 'headers', 'height', 'href',
'id', 'lang', 'ngnonbindable', 'onclick', 'open', 'rel', 'reversed', 'rowspan', 'scope', 'span', 'src', 'start', 'style', 'tabindex',
'target', 'title', 'type', 'valign', 'width'
];
const COPY_CODE_CLICK = /^markdownCopyCode\(\d+\)$/;
const COPY_CODE_ID = /^(codeWrapper|copyCodeId)\d+$/;
const SAFE_DATA_IMAGE = /^data:image\/(png|jpe?g|gif|webp|bmp);/i;
const ALLOWED_STYLE_PROPERTIES = new Set([
'background-color', 'border', 'border-bottom', 'border-collapse', 'border-color', 'border-left', 'border-radius',
'border-right', 'border-spacing', 'border-style', 'border-top', 'border-width', 'color', 'display', 'font-family',
'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'list-style-type',
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'max-height', 'max-width', 'min-height',
'min-width', 'opacity', 'overflow', 'overflow-wrap', 'padding', 'padding-bottom', 'padding-left', 'padding-right',
'padding-top', 'table-layout', 'text-align', 'text-decoration', 'text-decoration-color', 'text-decoration-line',
'text-decoration-style', 'text-indent', 'text-transform', 'vertical-align', 'white-space', 'width', 'word-break'
]);
const ALLOWED_STYLE_FUNCTIONS = new Set(['rgb', 'rgba', 'hsl', 'hsla', 'calc', 'min', 'max', 'clamp']);
let purifier: ReturnType<typeof DOMPurify> | null = null;
/**
* Sanitizes HTML that is not trusted, such as AI content, for rendering with innerHTML. Only an allowlist of elements
* and attributes is kept: scripts, event handlers, SVG, forms and frames are dropped, and ids only stay on the copy-code
* markup of the markdown renderer. Images load only from this origin or from inline image data; an image from another
* host becomes a link to it, so nothing is fetched until the person opens it. Styles keep only text and box properties
* with plain values.
*/
export function sanitizeMarkdownHtml(html: string): string {
const doc = new DOMParser().parseFromString(`<!DOCTYPE html><html><body>${html}</body></html>`, 'text/html');
doc.body.querySelectorAll(REMOVED_ELEMENTS).forEach(element => element.remove());
doc.body.querySelectorAll('*').forEach(element => {
for (const attribute of Array.from(element.attributes)) {
const name = attribute.name.toLowerCase();
const value = attribute.value;
if (name.startsWith('on')) {
if (!(name === 'onclick' && COPY_CODE_CLICK.test(value.trim()))) {
element.removeAttribute(attribute.name);
}
} else if (URL_ATTRIBUTES.has(name) && UNSAFE_URL.test(value.replace(/[\u0000- \u007f-\u009f]/g, ''))) {
element.removeAttribute(attribute.name);
} else if (name === 'style' && /url\s*\(|expression\s*\(|@import/i.test(value)) {
element.removeAttribute(attribute.name);
} else if (name === 'srcdoc' || name === 'formaction') {
element.removeAttribute(attribute.name);
const body = getPurifier().sanitize(html, {
ALLOWED_TAGS,
ALLOWED_ATTR,
ALLOW_DATA_ATTR: true,
ALLOW_ARIA_ATTR: true,
RETURN_DOM: true
}) as HTMLElement;
postProcess(body);
return body.innerHTML;
}
function getPurifier(): ReturnType<typeof DOMPurify> {
if (!purifier) {
purifier = DOMPurify(window);
purifier.addHook('uponSanitizeAttribute', sanitizeAttribute);
}
return purifier;
}
function sanitizeAttribute(node: Element, data: UponSanitizeAttributeHookEvent): void {
const value = data.attrValue ?? '';
switch (data.attrName) {
case 'onclick':
if (COPY_CODE_CLICK.test(value.trim()) && node.classList.contains('code-wrapper')) {
data.forceKeepAttr = true;
} else {
data.keepAttr = false;
}
break;
case 'id':
if (!COPY_CODE_ID.test(value)) {
data.keepAttr = false;
}
break;
case 'style':
data.attrValue = sanitizeStyle(value);
if (!data.attrValue) {
data.keepAttr = false;
}
break;
}
}
function postProcess(root: HTMLElement): void {
root.querySelectorAll('img').forEach(img => {
if (!isSafeImageSource(img.getAttribute('src'))) {
replaceExternalImage(img);
}
});
root.querySelectorAll('button').forEach(button => {
if (!isCopyCodeButton(button)) {
button.replaceWith(...Array.from(button.childNodes));
}
});
return doc.body.innerHTML;
root.querySelectorAll('input').forEach(input => {
if (input.getAttribute('type') !== 'checkbox' || !input.hasAttribute('disabled')) {
input.remove();
}
});
root.querySelectorAll('a[target]').forEach(link => link.setAttribute('rel', 'noopener noreferrer'));
}
function isSafeImageSource(src: string | null): boolean {
const value = src?.trim();
if (!value) {
return false;
}
if (value.toLowerCase().startsWith('data:')) {
return SAFE_DATA_IMAGE.test(value);
}
try {
return new URL(value, window.location.href).origin === window.location.origin;
} catch {
return false;
}
}
function replaceExternalImage(img: HTMLImageElement): void {
let href: URL | null = null;
try {
href = new URL(img.getAttribute('src')?.trim() ?? '', window.location.href);
} catch {
href = null;
}
if (!href || !/^https?:$/.test(href.protocol) || href.origin === window.location.origin) {
img.remove();
return;
}
const link = img.ownerDocument.createElement('a');
link.setAttribute('href', href.href);
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
link.textContent = img.getAttribute('alt')?.trim() || img.getAttribute('title')?.trim() || href.host;
img.replaceWith(link);
}
function isCopyCodeButton(button: HTMLButtonElement): boolean {
const wrapper = button.parentElement;
return button.classList.contains('clipboard-btn') && !!wrapper?.classList.contains('code-wrapper') &&
COPY_CODE_CLICK.test(wrapper.getAttribute('onclick')?.trim() ?? '');
}
function sanitizeStyle(style: string): string {
const declarations = style.split(';').map(declaration => declaration.trim()).filter(declaration => declaration);
const kept = declarations.filter(declaration => {
const colon = declaration.indexOf(':');
if (colon <= 0) {
return false;
}
const property = declaration.substring(0, colon).trim().toLowerCase();
const value = declaration.substring(colon + 1).trim().toLowerCase();
return ALLOWED_STYLE_PROPERTIES.has(property) && isSafeStyleValue(property, value);
});
return kept.length === declarations.length ? style : kept.join('; ');
}
function isSafeStyleValue(property: string, value: string): boolean {
if (!value || /[\\@<>"']|\/\*|url|expression|image|attr\s*\(/.test(value)) {
return false;
}
for (const call of value.matchAll(/([a-z-]+)\s*\(/g)) {
if (!ALLOWED_STYLE_FUNCTIONS.has(call[1])) {
return false;
}
}
return !(property.startsWith('margin') && value.includes('-'));
}

4
ui-ngx/src/app/shared/components/markdown.component.ts

@ -133,7 +133,7 @@ export class TbMarkdownComponent implements OnChanges {
const preHtml = preElements.item(i).outerHTML.replace('ngnonbindable=""', 'ngNonBindable');
template = template.replace(matches[i][0], preHtml);
}
template = sanitizeTemplate(template);
template = this.sanitizeHtml ? sanitizeMarkdownHtml(template) : sanitizeTemplate(template);
this.markdownContainer.clear();
let styles: string[] = [];
let readyObservable: Observable<void>;
@ -148,7 +148,7 @@ export class TbMarkdownComponent implements OnChanges {
if (this.additionalStyles) {
styles = styles.concat(this.additionalStyles);
}
if (this.usePlainMarkdown) {
if (this.usePlainMarkdown || this.sanitizeHtml) {
readyObservable = this.plainMarkdown(template, styles);
this.cd.detectChanges();
readyObservable.subscribe(() => {

Loading…
Cancel
Save