dompurify
Version:
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It's written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Firefox and Chrome - as well as almost anything else usin
92 lines (84 loc) • 3.5 kB
HTML
<html>
<head>
<script src="../src/purify.js"></script>
<!-- Grab the latest version of MentalJS -->
<script src="./lib/Mental.js"></script>
</head>
<body>
<!-- Our DIV to receive content -->
<div id="sanitized"></div>
<!-- Now let's sanitize that content -->
<script>
/* jshint globalstrict:true */
/* global DOMPurify */
;
// Initialize MentalJS
MentalJS().init({dom: true});
// Specify dirty HTML
var dirty = 'abc<script>alert(1)<\/script>\
<img src="xyz" onload="alert(2)">\
<img src="xyz" onload="alert`3`">\
<img src="xyz" onload="">\
<script src=//evil.com><\/script>\
<script>alert`4`<\/script>\
<script src=//evil.com>alert(5)<\/script>\
<svg><script xlink:href=//evil.com>alert(6)<\/script></svg>\
<svg><script href="//evil.com">123<\/script><p>';
// allow script elements
var config = {
ADD_TAGS: ['script'],
ADD_ATTR: ['onclick', 'onmouseover', 'onload', 'onunload']
}
// Add a hook to sanitize all script content with MentalJS
DOMPurify.addHook('uponSanitizeElement', function(node, data) {
if (data.tagName === 'script') {
var script = node.textContent;
if (!script || 'src' in node.attributes
|| 'href' in node.attributes
|| 'xlink:href' in node.attributes) {
return node.parentNode.removeChild(node)
}
try {
// Pass scripts to MentalJS
var mental = MentalJS().parse(
{
options: {
eval: false,
dom:true
},
code:script
}
);
return node.textContent = mental;
} catch (e) {
return node.parentNode.removeChild(node);
}
}
});
// Add a hook to sanitize all white-listed events with MentalJS
DOMPurify.addHook('uponSanitizeAttribute', function(node, data) {
if (data.attrName.match(/^on\w+/)) {
var script = data.attrValue;
try {
// Pass scripts to MentalJS
return data.attrValue = MentalJS().parse(
{
options: {
eval: false,
dom: true
},
code: script
}
);
} catch (e) {
return data.attrValue = '';
}
}
});
// Clean HTML string and write into our DIV
var clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerHTML = clean;
</script>
</body>
</html>