2016-08-14 10:32:22 +00:00
|
|
|
// allow some attributes
|
2016-02-11 20:33:21 +00:00
|
|
|
var whiteListAttr = ['id', 'class', 'style'];
|
2016-08-14 10:32:22 +00:00
|
|
|
// allow link starts with '.', '/' and custom protocol with '://'
|
|
|
|
var linkRegex = /^([\w|-]+:\/\/)|^([\.|\/])+/;
|
2016-08-15 03:00:02 +00:00
|
|
|
// allow data uri, from https://gist.github.com/bgrins/6194623
|
|
|
|
var dataUriRegex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*)\s*$/i;
|
2016-08-14 10:32:22 +00:00
|
|
|
// custom white list
|
|
|
|
var whiteList = filterXSS.whiteList;
|
|
|
|
// allow ol specify start number
|
|
|
|
whiteList['ol'] = ['start'];
|
|
|
|
// allow style tag
|
|
|
|
whiteList['style'] = [];
|
|
|
|
// allow kbd tag
|
|
|
|
whiteList['kbd'] = [];
|
|
|
|
// allow ifram tag with some safe attributes
|
|
|
|
whiteList['iframe'] = ['allowfullscreen', 'name', 'referrerpolicy', 'sandbox', 'src', 'srcdoc', 'width', 'height'];
|
2016-02-11 20:33:21 +00:00
|
|
|
|
|
|
|
var filterXSSOptions = {
|
|
|
|
allowCommentTag: true,
|
2016-08-14 10:32:22 +00:00
|
|
|
whiteList: whiteList,
|
2016-04-20 10:10:43 +00:00
|
|
|
escapeHtml: function (html) {
|
2016-08-14 10:32:22 +00:00
|
|
|
// allow html comment in multiple lines
|
2016-04-20 10:10:43 +00:00
|
|
|
return html.replace(/<(.*?)>/g, '<$1>');
|
|
|
|
},
|
2016-02-11 20:33:21 +00:00
|
|
|
onIgnoreTag: function (tag, html, options) {
|
2016-08-14 10:32:22 +00:00
|
|
|
// allow comment tag
|
|
|
|
if (tag == "!--") {
|
2016-02-11 20:33:21 +00:00
|
|
|
// do not filter its attributes
|
|
|
|
return html;
|
|
|
|
}
|
|
|
|
},
|
2016-04-20 10:18:52 +00:00
|
|
|
onTagAttr: function (tag, name, value, isWhiteAttr) {
|
2016-08-14 10:32:22 +00:00
|
|
|
// allow href and src that match linkRegex
|
|
|
|
if (isWhiteAttr && (name === 'href' || name === 'src') && linkRegex.test(value)) {
|
2016-04-20 10:18:52 +00:00
|
|
|
return name + '="' + filterXSS.escapeAttrValue(value) + '"';
|
|
|
|
}
|
2016-08-15 03:00:02 +00:00
|
|
|
// allow data uri in img src
|
|
|
|
if (isWhiteAttr && (tag == "img" && name === 'src') && dataUriRegex.test(value)) {
|
|
|
|
return name + '="' + filterXSS.escapeAttrValue(value) + '"';
|
|
|
|
}
|
2016-04-20 10:18:52 +00:00
|
|
|
},
|
2016-02-11 20:33:21 +00:00
|
|
|
onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
|
|
|
|
// allow attr start with 'data-' or in the whiteListAttr
|
|
|
|
if (name.substr(0, 5) === 'data-' || whiteListAttr.indexOf(name) !== -1) {
|
|
|
|
// escape its value using built-in escapeAttrValue function
|
|
|
|
return name + '="' + filterXSS.escapeAttrValue(value) + '"';
|
2016-02-11 09:45:13 +00:00
|
|
|
}
|
2016-02-11 20:33:21 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
function preventXSS(html) {
|
|
|
|
return filterXSS(html, filterXSSOptions);
|
2016-02-11 09:45:13 +00:00
|
|
|
}
|