9 changed files with 50 additions and 11 deletions
@ -0,0 +1,33 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
|
|||
const REMOVED_ELEMENTS = 'script,iframe,frame,frameset,object,embed,applet,link,meta,base,form,style,template,noscript,svg,math'; |
|||
|
|||
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 COPY_CODE_CLICK = /^markdownCopyCode\(\d+\)$/; |
|||
|
|||
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); |
|||
} |
|||
} |
|||
}); |
|||
return doc.body.innerHTML; |
|||
} |
|||
Loading…
Reference in new issue