|
| 1 | +import { visit } from 'unist-util-visit' |
| 2 | + |
| 3 | +const dangerousAttributes = [ |
| 4 | + 'onabort', 'onafterprint', 'onanimationend', 'onanimationiteration', 'onanimationstart', |
| 5 | + 'onbeforeprint', 'onbeforeunload', 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', |
| 6 | + 'onchange', 'onclick', 'onclose', 'oncontextmenu', 'oncopy', 'oncuechange', 'oncut', 'ondblclick', |
| 7 | + 'ondrag', 'ondragend', 'ondragenter', 'ondragexit', 'ondragleave', 'ondragover', 'ondragstart', |
| 8 | + 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onfocusin', 'onfocusout', |
| 9 | + 'onformdata', 'onhashchange', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', |
| 10 | + 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmessage', |
| 11 | + 'onmessageerror', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', |
| 12 | + 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', 'onpageshow', 'onpaste', |
| 13 | + 'onpause', 'onplay', 'onplaying', 'onpopstate', 'onprogress', 'onratechange', 'onrejectionhandled', |
| 14 | + 'onreset', 'onresize', 'onscroll', 'onsearch', 'onseeked', 'onseeking', 'onselect', 'onstalled', |
| 15 | + 'onstorage', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'ontransitionend', 'onunhandledrejection', |
| 16 | + 'onunload', 'onvolumechange', 'onwaiting', 'onwheel', 'href', 'src', 'action', 'formaction', 'manifest', |
| 17 | + 'background', 'poster', 'cite', 'data', 'ping', 'xlink:href', 'style', 'srcdoc', 'sandbox' |
| 18 | +].join('|') |
| 19 | + |
| 20 | +export const remarkSanitize = (): (tree: Node) => void => (tree: any) => { |
| 21 | + visit(tree, 'html', (node) => { |
| 22 | + const dangerousAttrRegex = new RegExp(`\\s*(${dangerousAttributes})="[^"]*"`, 'gi') |
| 23 | + |
| 24 | + if (node.value.match(dangerousAttrRegex)) { |
| 25 | + node.value = node.value.replace(dangerousAttrRegex, (match: string) => { |
| 26 | + const attr = match.toLowerCase().trim() |
| 27 | + if (attr.startsWith('href') || attr.startsWith('src') || attr.startsWith('xlink:href')) { |
| 28 | + if (attr.indexOf('"javascript:') > -1) return '' |
| 29 | + return match |
| 30 | + } |
| 31 | + |
| 32 | + return '' |
| 33 | + }) |
| 34 | + } |
| 35 | + }) |
| 36 | +} |
0 commit comments