3 changed files with 163 additions and 23 deletions
@ -1,33 +1,172 @@ |
|||||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
// SPDX-License-Identifier: BUSL-1.1
|
// 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 ALLOWED_ATTR = [ |
||||
|
'abbr', 'align', 'alt', 'checked', 'cite', 'class', 'colspan', 'datetime', 'dir', 'disabled', 'headers', 'height', 'href', |
||||
const UNSAFE_URL = /^(javascript|vbscript|data:(?!image\/(png|jpe?g|gif|webp|bmp);))/i; |
'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_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 { |
export function sanitizeMarkdownHtml(html: string): string { |
||||
const doc = new DOMParser().parseFromString(`<!DOCTYPE html><html><body>${html}</body></html>`, 'text/html'); |
const body = getPurifier().sanitize(html, { |
||||
doc.body.querySelectorAll(REMOVED_ELEMENTS).forEach(element => element.remove()); |
ALLOWED_TAGS, |
||||
doc.body.querySelectorAll('*').forEach(element => { |
ALLOWED_ATTR, |
||||
for (const attribute of Array.from(element.attributes)) { |
ALLOW_DATA_ATTR: true, |
||||
const name = attribute.name.toLowerCase(); |
ALLOW_ARIA_ATTR: true, |
||||
const value = attribute.value; |
RETURN_DOM: true |
||||
if (name.startsWith('on')) { |
}) as HTMLElement; |
||||
if (!(name === 'onclick' && COPY_CODE_CLICK.test(value.trim()))) { |
postProcess(body); |
||||
element.removeAttribute(attribute.name); |
return body.innerHTML; |
||||
} |
} |
||||
} else if (URL_ATTRIBUTES.has(name) && UNSAFE_URL.test(value.replace(/[\u0000- \u007f-\u009f]/g, ''))) { |
|
||||
element.removeAttribute(attribute.name); |
function getPurifier(): ReturnType<typeof DOMPurify> { |
||||
} else if (name === 'style' && /url\s*\(|expression\s*\(|@import/i.test(value)) { |
if (!purifier) { |
||||
element.removeAttribute(attribute.name); |
purifier = DOMPurify(window); |
||||
} else if (name === 'srcdoc' || name === 'formaction') { |
purifier.addHook('uponSanitizeAttribute', sanitizeAttribute); |
||||
element.removeAttribute(attribute.name); |
} |
||||
|
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('-')); |
||||
} |
} |
||||
|
|||||
Loading…
Reference in new issue