"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "dist/purify.js" between
DOMPurify-3.0.1.tar.gz and DOMPurify-3.0.2.tar.gz

About: DOMPurify is a DOM-only XSS sanitizer for HTML, MathML and SVG (written in JavaScript).

purify.js  (DOMPurify-3.0.1):purify.js  (DOMPurify-3.0.2)
/*! @license DOMPurify 3.0.1 | (c) Cure53 and other contributors | Released unde r the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMP urify/blob/3.0.1/LICENSE */ /*! @license DOMPurify 3.0.2 | (c) Cure53 and other contributors | Released unde r the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMP urify/blob/3.0.2/LICENSE */
(function (global, factory) { (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) : typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, glo bal.DOMPurify = factory()); (global = typeof globalThis !== 'undefined' ? globalThis : global || self, glo bal.DOMPurify = factory());
})(this, (function () { 'use strict'; })(this, (function () { 'use strict';
function _typeof(obj) { const {
"@babel/helpers - typeof"; entries,
setPrototypeOf,
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.it isFrozen,
erator ? function (obj) { getPrototypeOf,
return typeof obj; getOwnPropertyDescriptor
} : function (obj) { } = Object;
return obj && "function" == typeof Symbol && obj.constructor === Symbol && let {
obj !== Symbol.prototype ? "symbol" : typeof obj; freeze,
}, _typeof(obj); seal,
} create
} = Object; // eslint-disable-line import/no-mutable-exports
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { let {
o.__proto__ = p; apply,
return o; construct
}; } = typeof Reflect !== 'undefined' && Reflect;
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function ()
{}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupported
IterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedItera
bleToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["
@@iterator"] != null) return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.it
erator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn or
der to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\n
In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
d.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterato
r"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArra
yLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn
order to be iterable, non-array objects must have a [Symbol.iterator]() method.
");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = it.call(o);
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var entries = Object.entries,
setPrototypeOf = Object.setPrototypeOf,
isFrozen = Object.isFrozen,
getPrototypeOf = Object.getPrototypeOf,
getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var freeze = Object.freeze,
seal = Object.seal,
create = Object.create; // eslint-disable-line import/no-mutable-exports
var _ref = typeof Reflect !== 'undefined' && Reflect,
apply = _ref.apply,
construct = _ref.construct;
if (!apply) { if (!apply) {
apply = function apply(fun, thisValue, args) { apply = function apply(fun, thisValue, args) {
return fun.apply(thisValue, args); return fun.apply(thisValue, args);
}; };
} }
if (!freeze) { if (!freeze) {
freeze = function freeze(x) { freeze = function freeze(x) {
return x; return x;
skipping to change at line 223 skipping to change at line 47
} }
if (!seal) { if (!seal) {
seal = function seal(x) { seal = function seal(x) {
return x; return x;
}; };
} }
if (!construct) { if (!construct) {
construct = function construct(Func, args) { construct = function construct(Func, args) {
return _construct(Func, _toConsumableArray(args)); return new Func(...args);
}; };
} }
var arrayForEach = unapply(Array.prototype.forEach); const arrayForEach = unapply(Array.prototype.forEach);
var arrayPop = unapply(Array.prototype.pop); const arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push); const arrayPush = unapply(Array.prototype.push);
var stringToLowerCase = unapply(String.prototype.toLowerCase); const stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringToString = unapply(String.prototype.toString); const stringToString = unapply(String.prototype.toString);
var stringMatch = unapply(String.prototype.match); const stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace); const stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf); const stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim); const stringTrim = unapply(String.prototype.trim);
var regExpTest = unapply(RegExp.prototype.test); const regExpTest = unapply(RegExp.prototype.test);
var typeErrorCreate = unconstruct(TypeError); const typeErrorCreate = unconstruct(TypeError);
function unapply(func) { function unapply(func) {
return function (thisArg) { return function (thisArg) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0 ), _key = 1; _key < _len; _key++) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0 ), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key]; args[_key - 1] = arguments[_key];
} }
return apply(func, thisArg, args); return apply(func, thisArg, args);
}; };
} }
function unconstruct(func) { function unconstruct(func) {
skipping to change at line 268 skipping to change at line 92
function addToSet(set, array, transformCaseFunc) { function addToSet(set, array, transformCaseFunc) {
transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCas e; transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCas e;
if (setPrototypeOf) { if (setPrototypeOf) {
// Make 'in' and truthy checks like Boolean(set.constructor) // Make 'in' and truthy checks like Boolean(set.constructor)
// independent of any properties defined on Object.prototype. // independent of any properties defined on Object.prototype.
// Prevent prototype setters from intercepting set as a this value. // Prevent prototype setters from intercepting set as a this value.
setPrototypeOf(set, null); setPrototypeOf(set, null);
} }
var l = array.length; let l = array.length;
while (l--) { while (l--) {
var element = array[l]; let element = array[l];
if (typeof element === 'string') { if (typeof element === 'string') {
var lcElement = transformCaseFunc(element); const lcElement = transformCaseFunc(element);
if (lcElement !== element) { if (lcElement !== element) {
// Config presets (e.g. tags.js, attrs.js) are immutable. // Config presets (e.g. tags.js, attrs.js) are immutable.
if (!isFrozen(array)) { if (!isFrozen(array)) {
array[l] = lcElement; array[l] = lcElement;
} }
element = lcElement; element = lcElement;
} }
} }
set[element] = true; set[element] = true;
} }
return set; return set;
} }
/* Shallow clone an object */ /* Shallow clone an object */
function clone(object) { function clone(object) {
var newObject = create(null); const newObject = create(null);
var _iterator = _createForOfIteratorHelper(entries(object)),
_step;
try { for (const [property, value] of entries(object)) {
for (_iterator.s(); !(_step = _iterator.n()).done;) { newObject[property] = value;
var _step$value = _slicedToArray(_step.value, 2),
property = _step$value[0],
value = _step$value[1];
newObject[property] = value;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
} }
return newObject; return newObject;
} }
/* This method automatically checks if the prop is function /* This method automatically checks if the prop is function
* or getter and behaves accordingly. */ * or getter and behaves accordingly. */
function lookupGetter(object, prop) { function lookupGetter(object, prop) {
while (object !== null) { while (object !== null) {
var desc = getOwnPropertyDescriptor(object, prop); const desc = getOwnPropertyDescriptor(object, prop);
if (desc) { if (desc) {
if (desc.get) { if (desc.get) {
return unapply(desc.get); return unapply(desc.get);
} }
if (typeof desc.value === 'function') { if (typeof desc.value === 'function') {
return unapply(desc.value); return unapply(desc.value);
} }
} }
skipping to change at line 343 skipping to change at line 154
} }
function fallbackValue(element) { function fallbackValue(element) {
console.warn('fallback value for', element); console.warn('fallback value for', element);
return null; return null;
} }
return fallbackValue; return fallbackValue;
} }
var html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'as ide', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'b utton', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'conte nt', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', ' dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'f ont', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'h group', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li' , 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'r p', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table' , 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', ' track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', ' aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'con tent', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'l i', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr' , 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source ', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'tabl e', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG
var svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'an const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', '
imatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs'
'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', , 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image
'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'patte ', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pat
rn', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', tern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch
'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); ', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'f const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer',
eComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDi 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'fe
stantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianB DistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussia
lur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointL nBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePoin
ight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List tLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // Lis
of SVG elements that are disallowed by default. t of SVG elements that are disallowed by default.
// We still need to know them so that we can do namespace // We still need to know them so that we can do namespace
// checks properly in case one wants to add them to // checks properly in case one wants to add them to
// allow-list. // allow-list.
var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', ' const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard',
fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-s
', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient rc', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradie
', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unkn nt', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'un
own', 'use']); known', 'use']);
var mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mgly const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mg
ph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphan lyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mph
tom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubs antom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msu
up', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to bsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
SVG, we want to know all MathML elements, // Similarly to SVG, we want to know all MathML elements,
// even those that we disallow by default. // even those that we disallow by default.
var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongd const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlon
iv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics' gdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantic
, 'annotation', 'annotation-xml', 'mprescripts', 'none']); s', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
var text = freeze(['#text']); const text = freeze(['#text']);
var html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'auto const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'au
complete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border' tocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'borde
, 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', r', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear'
'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', , 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin
'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture' ', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpictur
, 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', ' e', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint',
face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', ' 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id',
inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'l 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading',
oop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multipl 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multi
e', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimu ple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'opti
m', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'ra mum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', '
diogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'ro radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', '
wspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'sr rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', '
clang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'tit
', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']); le', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']
var svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseli );
ne', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'ba const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-base
seline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-pa line', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', '
th', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-
'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconsta path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters
nt', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', ' ', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffusecons
fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flo tant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end',
od-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'fo 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'f
nt-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', lood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', '
'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name'
-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', ' , 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'ima
keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix ge-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints',
', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'm 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatr
arker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', ix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid',
'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctave 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits'
s', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', , 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numocta
'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patter ves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin
ntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', ' ', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patt
primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repe erntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio',
atdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'spec 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 're
ularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation' peatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'sp
, 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dasho ecularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviatio
ffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacit n', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-das
y', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabind hoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opac
ex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text ity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabi
-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'va ndex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'te
lues', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert- xt-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', '
origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'ver
'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan' t-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector'
]); , 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpa
var mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'c n']);
olumnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'displa const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close',
y', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'large 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'disp
op', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor lay', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'lar
', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', geop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcol
'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', or', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation
'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', ' ', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace'
separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symme , 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection',
tric', 'voffset', 'width', 'xmlns']); 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'sym
var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:x metric', 'voffset', 'width', 'xmlns']);
link']); const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns
:xlink']);
var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template det ection regex for SAFE_FOR_TEMPLATES mode const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template d etection regex for SAFE_FOR_TEMPLATES mode
var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm); const TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no- const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line n
useless-escape o-useless-escape
var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-esca pe const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-es cape
var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^ a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmp p):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-esca pe
); );
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205 const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u2
F\u3000]/g // eslint-disable-line no-control-regex 05F\u3000]/g // eslint-disable-line no-control-regex
); );
var DOCTYPE_NAME = seal(/^html$/i); const DOCTYPE_NAME = seal(/^html$/i);
var getGlobal = function getGlobal() { var EXPRESSIONS = /*#__PURE__*/Object.freeze({
return typeof window === 'undefined' ? null : window; __proto__: null,
}; MUSTACHE_EXPR: MUSTACHE_EXPR,
ERB_EXPR: ERB_EXPR,
TMPLIT_EXPR: TMPLIT_EXPR,
DATA_ATTR: DATA_ATTR,
ARIA_ATTR: ARIA_ATTR,
IS_ALLOWED_URI: IS_ALLOWED_URI,
IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
ATTR_WHITESPACE: ATTR_WHITESPACE,
DOCTYPE_NAME: DOCTYPE_NAME
});
const getGlobal = () => typeof window === 'undefined' ? null : window;
/** /**
* Creates a no-op policy for internal use only. * Creates a no-op policy for internal use only.
* Don't export this function outside this module! * Don't export this function outside this module!
* @param {?TrustedTypePolicyFactory} trustedTypes The policy factory. * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
* @param {Document} document The document object (to determine policy name su ffix) * @param {Document} document The document object (to determine policy name su ffix)
* @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
* are not supported). * are not supported).
*/ */
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedType const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTy
s, document) { pes, document) {
if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy ! if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !==
== 'function') { 'function') {
return null; return null;
} // Allow the callers to control the unique policy name } // Allow the callers to control the unique policy name
// by adding a data-tt-policy-suffix to the script element with the DOMPurif y. // by adding a data-tt-policy-suffix to the script element with the DOMPurif y.
// Policy creation with duplicate names throws in Trusted Types. // Policy creation with duplicate names throws in Trusted Types.
var suffix = null; let suffix = null;
var ATTR_NAME = 'data-tt-policy-suffix'; const ATTR_NAME = 'data-tt-policy-suffix';
if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME) ) { if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME) ) {
suffix = document.currentScript.getAttribute(ATTR_NAME); suffix = document.currentScript.getAttribute(ATTR_NAME);
} }
var policyName = 'dompurify' + (suffix ? '#' + suffix : ''); const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
try { try {
return trustedTypes.createPolicy(policyName, { return trustedTypes.createPolicy(policyName, {
createHTML: function createHTML(html) { createHTML(html) {
return html; return html;
}, },
createScriptURL: function createScriptURL(scriptUrl) {
createScriptURL(scriptUrl) {
return scriptUrl; return scriptUrl;
} }
}); });
} catch (_) { } catch (_) {
// Policy creation failed (most likely another DOMPurify script has // Policy creation failed (most likely another DOMPurify script has
// already run). Skip creating the policy, as this will only cause errors // already run). Skip creating the policy, as this will only cause errors
// if TT are enforced. // if TT are enforced.
console.warn('TrustedTypes policy ' + policyName + ' could not be created. '); console.warn('TrustedTypes policy ' + policyName + ' could not be created. ');
return null; return null;
} }
}; };
function createDOMPurify() { function createDOMPurify() {
var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[ 0] : getGlobal(); let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[ 0] : getGlobal();
var DOMPurify = function DOMPurify(root) { const DOMPurify = root => createDOMPurify(root);
return createDOMPurify(root);
};
/** /**
* Version label, exposed for easier checks * Version label, exposed for easier checks
* if DOMPurify is up to date or not * if DOMPurify is up to date or not
*/ */
DOMPurify.version = '3.0.1'; DOMPurify.version = '3.0.2';
/** /**
* Array of elements that DOMPurify removed during sanitation. * Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed. * Empty if nothing was removed.
*/ */
DOMPurify.removed = []; DOMPurify.removed = [];
if (!window || !window.document || window.document.nodeType !== 9) { if (!window || !window.document || window.document.nodeType !== 9) {
// Not running in a browser, provide a factory function // Not running in a browser, provide a factory function
// so that you can pass your own Window // so that you can pass your own Window
DOMPurify.isSupported = false; DOMPurify.isSupported = false;
return DOMPurify; return DOMPurify;
} }
var originalDocument = window.document; const originalDocument = window.document;
var document = window.document; let {
var DocumentFragment = window.DocumentFragment, document
HTMLTemplateElement = window.HTMLTemplateElement, } = window;
Node = window.Node, const {
Element = window.Element, DocumentFragment,
NodeFilter = window.NodeFilter, HTMLTemplateElement,
_window$NamedNodeMap = window.NamedNodeMap, Node,
NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || Element,
window.MozNamedAttrMap : _window$NamedNodeMap, NodeFilter,
HTMLFormElement = window.HTMLFormElement, NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
DOMParser = window.DOMParser, HTMLFormElement,
trustedTypes = window.trustedTypes; DOMParser,
var ElementPrototype = Element.prototype; trustedTypes
var cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); } = window;
var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); const ElementPrototype = Element.prototype;
var getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
issue #47, the web-components registry is inherited by a const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As pe
r issue #47, the web-components registry is inherited by a
// new document created via createHTMLDocument. As per the spec // new document created via createHTMLDocument. As per the spec
// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-reg istries) // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-reg istries)
// a new empty registry is used when creating a template contents owner // a new empty registry is used when creating a template contents owner
// document, so we use that as our parent document to ensure nothing // document, so we use that as our parent document to ensure nothing
// is inherited. // is inherited.
if (typeof HTMLTemplateElement === 'function') { if (typeof HTMLTemplateElement === 'function') {
var template = document.createElement('template'); const template = document.createElement('template');
if (template.content && template.content.ownerDocument) { if (template.content && template.content.ownerDocument) {
document = template.content.ownerDocument; document = template.content.ownerDocument;
} }
} }
var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDoc ument); const trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalD ocument);
var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : ''; const emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '
var _document = document, ';
implementation = _document.implementation, const {
createNodeIterator = _document.createNodeIterator, implementation,
createDocumentFragment = _document.createDocumentFragment, createNodeIterator,
getElementsByTagName = _document.getElementsByTagName; createDocumentFragment,
var importNode = originalDocument.importNode; getElementsByTagName
var hooks = {}; } = document;
const {
importNode
} = originalDocument;
let hooks = {};
/** /**
* Expose whether this browser supports running the full DOMPurify. * Expose whether this browser supports running the full DOMPurify.
*/ */
DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNod e === 'function' && implementation && typeof implementation.createHTMLDocument ! == 'undefined'; DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNod e === 'function' && implementation && typeof implementation.createHTMLDocument ! == 'undefined';
var MUSTACHE_EXPR$1 = MUSTACHE_EXPR, const {
ERB_EXPR$1 = ERB_EXPR, MUSTACHE_EXPR,
TMPLIT_EXPR$1 = TMPLIT_EXPR, ERB_EXPR,
DATA_ATTR$1 = DATA_ATTR, TMPLIT_EXPR,
ARIA_ATTR$1 = ARIA_ATTR, DATA_ATTR,
IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ARIA_ATTR,
ATTR_WHITESPACE$1 = ATTR_WHITESPACE; IS_SCRIPT_OR_DATA,
var IS_ALLOWED_URI$1 = IS_ALLOWED_URI; ATTR_WHITESPACE
} = EXPRESSIONS;
let {
IS_ALLOWED_URI: IS_ALLOWED_URI$1
} = EXPRESSIONS;
/** /**
* We consider the elements and attributes below to be safe. Ideally * We consider the elements and attributes below to be safe. Ideally
* don't add any new ones but feel free to remove unwanted ones. * don't add any new ones but feel free to remove unwanted ones.
*/ */
/* allowed element names */ /* allowed element names */
var ALLOWED_TAGS = null; let ALLOWED_TAGS = null;
var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1) const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilter
, _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray( s, ...mathMl$1, ...text]);
mathMl$1), _toConsumableArray(text)));
/* Allowed attribute names */ /* Allowed attribute names */
var ALLOWED_ATTR = null; let ALLOWED_ATTR = null;
var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xm
_toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml))); l]);
/* /*
* Configure how DOMPUrify should handle custom elements and their attribute s as well as customized built-in elements. * Configure how DOMPUrify should handle custom elements and their attribute s as well as customized built-in elements.
* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPa ttern, predicate]. Default: `null` (disallow any attributes not on the allow lis t) * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPa ttern, predicate]. Default: `null` (disallow any attributes not on the allow lis t)
* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Defaul t: `false`. * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Defaul t: `false`.
*/ */
var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, { let CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
tagNameCheck: { tagNameCheck: {
writable: true, writable: true,
configurable: false, configurable: false,
enumerable: true, enumerable: true,
value: null value: null
}, },
attributeNameCheck: { attributeNameCheck: {
writable: true, writable: true,
configurable: false, configurable: false,
enumerable: true, enumerable: true,
skipping to change at line 546 skipping to change at line 378
}, },
allowCustomizedBuiltInElements: { allowCustomizedBuiltInElements: {
writable: true, writable: true,
configurable: false, configurable: false,
enumerable: true, enumerable: true,
value: false value: false
} }
})); }));
/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
var FORBID_TAGS = null; let FORBID_TAGS = null;
/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
var FORBID_ATTR = null; let FORBID_ATTR = null;
/* Decide if ARIA attributes are okay */ /* Decide if ARIA attributes are okay */
var ALLOW_ARIA_ATTR = true; let ALLOW_ARIA_ATTR = true;
/* Decide if custom data attributes are okay */ /* Decide if custom data attributes are okay */
var ALLOW_DATA_ATTR = true; let ALLOW_DATA_ATTR = true;
/* Decide if unknown protocols are okay */ /* Decide if unknown protocols are okay */
var ALLOW_UNKNOWN_PROTOCOLS = false; let ALLOW_UNKNOWN_PROTOCOLS = false;
/* Decide if self-closing tags in attributes are allowed. /* Decide if self-closing tags in attributes are allowed.
* Usually removed due to a mXSS issue in jQuery 3.0 */ * Usually removed due to a mXSS issue in jQuery 3.0 */
var ALLOW_SELF_CLOSE_IN_ATTR = true; let ALLOW_SELF_CLOSE_IN_ATTR = true;
/* Output should be safe for common template engines. /* Output should be safe for common template engines.
* This means, DOMPurify removes data attributes, mustaches and ERB * This means, DOMPurify removes data attributes, mustaches and ERB
*/ */
var SAFE_FOR_TEMPLATES = false; let SAFE_FOR_TEMPLATES = false;
/* Decide if document with <html>... should be returned */ /* Decide if document with <html>... should be returned */
var WHOLE_DOCUMENT = false; let WHOLE_DOCUMENT = false;
/* Track whether config is already set on this instance of DOMPurify. */ /* Track whether config is already set on this instance of DOMPurify. */
var SET_CONFIG = false; let SET_CONFIG = false;
/* Decide if all elements (e.g. style, script) must be children of /* Decide if all elements (e.g. style, script) must be children of
* document.body. By default, browsers might move them to document.head */ * document.body. By default, browsers might move them to document.head */
var FORCE_BODY = false; let FORCE_BODY = false;
/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
* string (or a TrustedHTML object if Trusted Types are supported). * string (or a TrustedHTML object if Trusted Types are supported).
* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned inste ad * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned inste ad
*/ */
var RETURN_DOM = false; let RETURN_DOM = false;
/* Decide if a DOM `DocumentFragment` should be returned, instead of a html /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
* string (or a TrustedHTML object if Trusted Types are supported) */ * string (or a TrustedHTML object if Trusted Types are supported) */
var RETURN_DOM_FRAGMENT = false; let RETURN_DOM_FRAGMENT = false;
/* Try to return a Trusted Type object instead of a string, return a string in /* Try to return a Trusted Type object instead of a string, return a string in
* case Trusted Types are not supported */ * case Trusted Types are not supported */
var RETURN_TRUSTED_TYPE = false; let RETURN_TRUSTED_TYPE = false;
/* Output should be free from DOM clobbering attacks? /* Output should be free from DOM clobbering attacks?
* This sanitizes markups named with colliding, clobberable built-in DOM API s. * This sanitizes markups named with colliding, clobberable built-in DOM API s.
*/ */
var SANITIZE_DOM = true; let SANITIZE_DOM = true;
/* Achieve full DOM Clobbering protection by isolating the namespace of name d /* Achieve full DOM Clobbering protection by isolating the namespace of name d
* properties and JS variables, mitigating attacks that abuse the HTML/DOM s pec rules. * properties and JS variables, mitigating attacks that abuse the HTML/DOM s pec rules.
* *
* HTML/DOM spec rules that enable DOM Clobbering: * HTML/DOM spec rules that enable DOM Clobbering:
* - Named Access on Window (§7.3.3) * - Named Access on Window (§7.3.3)
* - DOM Tree Accessors (§3.1.5) * - DOM Tree Accessors (§3.1.5)
* - Form Element Parent-Child Relations (§4.10.3) * - Form Element Parent-Child Relations (§4.10.3)
* - Iframe srcdoc / Nested WindowProxies (§4.8.5) * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
* - HTMLCollection (§4.2.10.2) * - HTMLCollection (§4.2.10.2)
* *
* Namespace isolation is implemented by prefixing `id` and `name` attribute s * Namespace isolation is implemented by prefixing `id` and `name` attribute s
* with a constant string, i.e., `user-content-` * with a constant string, i.e., `user-content-`
*/ */
var SANITIZE_NAMED_PROPS = false; let SANITIZE_NAMED_PROPS = false;
var SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
/* Keep element content when removing element? */ /* Keep element content when removing element? */
var KEEP_CONTENT = true; let KEEP_CONTENT = true;
/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
* of importing it into a new Document and returning a sanitized copy */ * of importing it into a new Document and returning a sanitized copy */
var IN_PLACE = false; let IN_PLACE = false;
/* Allow usage of profiles like html, svg and mathMl */ /* Allow usage of profiles like html, svg and mathMl */
var USE_PROFILES = {}; let USE_PROFILES = {};
/* Tags to ignore content of when KEEP_CONTENT is true */ /* Tags to ignore content of when KEEP_CONTENT is true */
var FORBID_CONTENTS = null; let FORBID_CONTENTS = null;
var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colg const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'co
roup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms' lgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'm
, 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 's s', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style',
vg', 'template', 'thead', 'title', 'video', 'xmp']); 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
/* Tags that are safe for data: URIs */ /* Tags that are safe for data: URIs */
var DATA_URI_TAGS = null; let DATA_URI_TAGS = null;
var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source
'image', 'track']); ', 'image', 'track']);
/* Attributes safe for values like "javascript:" */ /* Attributes safe for values like "javascript:" */
var URI_SAFE_ATTRIBUTES = null; let URI_SAFE_ATTRIBUTES = null;
var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id
'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', ', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value
'style', 'xmlns']); ', 'style', 'xmlns']);
var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
/* Document namespace */ /* Document namespace */
var NAMESPACE = HTML_NAMESPACE; let NAMESPACE = HTML_NAMESPACE;
var IS_EMPTY_INPUT = false; let IS_EMPTY_INPUT = false;
/* Allowed XHTML+XML namespaces */ /* Allowed XHTML+XML namespaces */
var ALLOWED_NAMESPACES = null; let ALLOWED_NAMESPACES = null;
var DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPA const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMES
CE, HTML_NAMESPACE], stringToString); PACE, HTML_NAMESPACE], stringToString);
/* Parsing of strict XHTML documents */ /* Parsing of strict XHTML documents */
var PARSER_MEDIA_TYPE; let PARSER_MEDIA_TYPE;
var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
var DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
var transformCaseFunc; let transformCaseFunc;
/* Keep a reference to config to pass to hooks */ /* Keep a reference to config to pass to hooks */
var CONFIG = null; let CONFIG = null;
/* Ideally, do not touch anything below this line */ /* Ideally, do not touch anything below this line */
/* ______________________________________________ */ /* ______________________________________________ */
var formElement = document.createElement('form'); const formElement = document.createElement('form');
var isRegexOrFunction = function isRegexOrFunction(testValue) { const isRegexOrFunction = function isRegexOrFunction(testValue) {
return testValue instanceof RegExp || testValue instanceof Function; return testValue instanceof RegExp || testValue instanceof Function;
}; };
/** /**
* _parseConfig * _parseConfig
* *
* @param {Object} cfg optional config literal * @param {Object} cfg optional config literal
*/ */
// eslint-disable-next-line complexity // eslint-disable-next-line complexity
var _parseConfig = function _parseConfig(cfg) { const _parseConfig = function _parseConfig(cfg) {
if (CONFIG && CONFIG === cfg) { if (CONFIG && CONFIG === cfg) {
return; return;
} }
/* Shield configuration object from tampering */ /* Shield configuration object from tampering */
if (!cfg || _typeof(cfg) !== 'object') { if (!cfg || typeof cfg !== 'object') {
cfg = {}; cfg = {};
} }
/* Shield configuration object from prototype pollution */ /* Shield configuration object from prototype pollution */
cfg = clone(cfg); cfg = clone(cfg);
PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSE R_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_ TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercas e. Keeping XHTML as is. SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSE R_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_ TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercas e. Keeping XHTML as is.
transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? string ToString : stringToLowerCase; transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? string ToString : stringToLowerCase;
/* Set configuration parameters */ /* Set configuration parameters */
skipping to change at line 734 skipping to change at line 566
FORCE_BODY = cfg.FORCE_BODY || false; // Default false FORCE_BODY = cfg.FORCE_BODY || false; // Default false
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
IN_PLACE = cfg.IN_PLACE || false; // Default false IN_PLACE = cfg.IN_PLACE || false; // Default false
IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1; IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HA NDLING.tagNameCheck)) { if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HA NDLING.tagNameCheck)) {
CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNa meCheck; CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNa meCheck;
} }
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HA NDLING.attributeNameCheck)) { if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HA NDLING.attributeNameCheck)) {
CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING .attributeNameCheck; CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING .attributeNameCheck;
} }
skipping to change at line 760 skipping to change at line 592
if (SAFE_FOR_TEMPLATES) { if (SAFE_FOR_TEMPLATES) {
ALLOW_DATA_ATTR = false; ALLOW_DATA_ATTR = false;
} }
if (RETURN_DOM_FRAGMENT) { if (RETURN_DOM_FRAGMENT) {
RETURN_DOM = true; RETURN_DOM = true;
} }
/* Parse profile info */ /* Parse profile info */
if (USE_PROFILES) { if (USE_PROFILES) {
ALLOWED_TAGS = addToSet({}, _toConsumableArray(text)); ALLOWED_TAGS = addToSet({}, [...text]);
ALLOWED_ATTR = []; ALLOWED_ATTR = [];
if (USE_PROFILES.html === true) { if (USE_PROFILES.html === true) {
addToSet(ALLOWED_TAGS, html$1); addToSet(ALLOWED_TAGS, html$1);
addToSet(ALLOWED_ATTR, html); addToSet(ALLOWED_ATTR, html);
} }
if (USE_PROFILES.svg === true) { if (USE_PROFILES.svg === true) {
addToSet(ALLOWED_TAGS, svg$1); addToSet(ALLOWED_TAGS, svg$1);
addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, svg);
skipping to change at line 840 skipping to change at line 672
} // Prevent further manipulation of configuration. } // Prevent further manipulation of configuration.
// Not available in IE8, Safari 5, etc. // Not available in IE8, Safari 5, etc.
if (freeze) { if (freeze) {
freeze(cfg); freeze(cfg);
} }
CONFIG = cfg; CONFIG = cfg;
}; };
var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', ' const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms',
mtext']); 'mtext']);
var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title' const HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'titl
, 'annotation-xml']); // Certain elements are allowed in both SVG and HTML e', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
// namespace. We need to specify them explicitly // namespace. We need to specify them explicitly
// so that they don't get erroneously deleted from // so that they don't get erroneously deleted from
// HTML namespace. // HTML namespace.
var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', ' a', 'script']); const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
/* Keep track of all possible SVG and MathML tags /* Keep track of all possible SVG and MathML tags
* so that we can perform the namespace checks * so that we can perform the namespace checks
* correctly. */ * correctly. */
var ALL_SVG_TAGS = addToSet({}, svg$1); const ALL_SVG_TAGS = addToSet({}, svg$1);
addToSet(ALL_SVG_TAGS, svgFilters); addToSet(ALL_SVG_TAGS, svgFilters);
addToSet(ALL_SVG_TAGS, svgDisallowed); addToSet(ALL_SVG_TAGS, svgDisallowed);
var ALL_MATHML_TAGS = addToSet({}, mathMl$1); const ALL_MATHML_TAGS = addToSet({}, mathMl$1);
addToSet(ALL_MATHML_TAGS, mathMlDisallowed); addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
/** /**
* *
* *
* @param {Element} element a DOM element whose namespace is being checked * @param {Element} element a DOM element whose namespace is being checked
* @returns {boolean} Return false if the element has a * @returns {boolean} Return false if the element has a
* namespace that a spec-compliant parser would never * namespace that a spec-compliant parser would never
* return. Return true otherwise. * return. Return true otherwise.
*/ */
var _checkValidNamespace = function _checkValidNamespace(element) { const _checkValidNamespace = function _checkValidNamespace(element) {
var parent = getParentNode(element); // In JSDOM, if we're inside shadow D let parent = getParentNode(element); // In JSDOM, if we're inside shadow D
OM, then parentNode OM, then parentNode
// can be null. We just simulate parent in this case. // can be null. We just simulate parent in this case.
if (!parent || !parent.tagName) { if (!parent || !parent.tagName) {
parent = { parent = {
namespaceURI: NAMESPACE, namespaceURI: NAMESPACE,
tagName: 'template' tagName: 'template'
}; };
} }
var tagName = stringToLowerCase(element.tagName); const tagName = stringToLowerCase(element.tagName);
var parentTagName = stringToLowerCase(parent.tagName); const parentTagName = stringToLowerCase(parent.tagName);
if (!ALLOWED_NAMESPACES[element.namespaceURI]) { if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
return false; return false;
} }
if (element.namespaceURI === SVG_NAMESPACE) { if (element.namespaceURI === SVG_NAMESPACE) {
// The only way to switch from HTML namespace to SVG // The only way to switch from HTML namespace to SVG
// is via <svg>. If it happens via any other tag, then // is via <svg>. If it happens via any other tag, then
// it should be killed. // it should be killed.
if (parent.namespaceURI === HTML_NAMESPACE) { if (parent.namespaceURI === HTML_NAMESPACE) {
skipping to change at line 949 skipping to change at line 781
// Return false just in case. // Return false just in case.
return false; return false;
}; };
/** /**
* _forceRemove * _forceRemove
* *
* @param {Node} node a DOM node * @param {Node} node a DOM node
*/ */
var _forceRemove = function _forceRemove(node) { const _forceRemove = function _forceRemove(node) {
arrayPush(DOMPurify.removed, { arrayPush(DOMPurify.removed, {
element: node element: node
}); });
try { try {
// eslint-disable-next-line unicorn/prefer-dom-node-remove // eslint-disable-next-line unicorn/prefer-dom-node-remove
node.parentNode.removeChild(node); node.parentNode.removeChild(node);
} catch (_) { } catch (_) {
node.remove(); node.remove();
} }
}; };
/** /**
* _removeAttribute * _removeAttribute
* *
* @param {String} name an Attribute name * @param {String} name an Attribute name
* @param {Node} node a DOM node * @param {Node} node a DOM node
*/ */
var _removeAttribute = function _removeAttribute(name, node) { const _removeAttribute = function _removeAttribute(name, node) {
try { try {
arrayPush(DOMPurify.removed, { arrayPush(DOMPurify.removed, {
attribute: node.getAttributeNode(name), attribute: node.getAttributeNode(name),
from: node from: node
}); });
} catch (_) { } catch (_) {
arrayPush(DOMPurify.removed, { arrayPush(DOMPurify.removed, {
attribute: null, attribute: null,
from: node from: node
}); });
skipping to change at line 1002 skipping to change at line 834
} }
} }
}; };
/** /**
* _initDocument * _initDocument
* *
* @param {String} dirty a string of dirty markup * @param {String} dirty a string of dirty markup
* @return {Document} a DOM, filled with the dirty markup * @return {Document} a DOM, filled with the dirty markup
*/ */
var _initDocument = function _initDocument(dirty) { const _initDocument = function _initDocument(dirty) {
/* Create a HTML document */ /* Create a HTML document */
var doc; let doc;
var leadingWhitespace; let leadingWhitespace;
if (FORCE_BODY) { if (FORCE_BODY) {
dirty = '<remove></remove>' + dirty; dirty = '<remove></remove>' + dirty;
} else { } else {
/* If FORCE_BODY isn't used, leading whitespace needs to be preserved ma nually */ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved ma nually */
var matches = stringMatch(dirty, /^[\r\n\t ]+/); const matches = stringMatch(dirty, /^[\r\n\t ]+/);
leadingWhitespace = matches && matches[0]; leadingWhitespace = matches && matches[0];
} }
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NA MESPACE) { if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NA MESPACE) {
// Root of XHTML doc must contain xmlns declaration (see https://www.w3. org/TR/xhtml1/normative.html#strict) // Root of XHTML doc must contain xmlns declaration (see https://www.w3. org/TR/xhtml1/normative.html#strict)
dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>'; dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
} }
var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirt y) : dirty; const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(di rty) : dirty;
/* /*
* Use the DOMParser API by default, fallback later if needs be * Use the DOMParser API by default, fallback later if needs be
* DOMParser not work for svg when has multiple root element. * DOMParser not work for svg when has multiple root element.
*/ */
if (NAMESPACE === HTML_NAMESPACE) { if (NAMESPACE === HTML_NAMESPACE) {
try { try {
doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE) ; doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE) ;
} catch (_) {} } catch (_) {}
} }
skipping to change at line 1042 skipping to change at line 874
if (!doc || !doc.documentElement) { if (!doc || !doc.documentElement) {
doc = implementation.createDocument(NAMESPACE, 'template', null); doc = implementation.createDocument(NAMESPACE, 'template', null);
try { try {
doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayl oad; doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayl oad;
} catch (_) {// Syntax error if dirtyPayload is invalid xml } catch (_) {// Syntax error if dirtyPayload is invalid xml
} }
} }
var body = doc.body || doc.documentElement; const body = doc.body || doc.documentElement;
if (dirty && leadingWhitespace) { if (dirty && leadingWhitespace) {
body.insertBefore(document.createTextNode(leadingWhitespace), body.child Nodes[0] || null); body.insertBefore(document.createTextNode(leadingWhitespace), body.child Nodes[0] || null);
} }
/* Work on whole document or just its body */ /* Work on whole document or just its body */
if (NAMESPACE === HTML_NAMESPACE) { if (NAMESPACE === HTML_NAMESPACE) {
return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[ 0]; return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[ 0];
} }
return WHOLE_DOCUMENT ? doc.documentElement : body; return WHOLE_DOCUMENT ? doc.documentElement : body;
}; };
/** /**
* _createIterator * _createIterator
* *
* @param {Document} root document/fragment to create iterator for * @param {Document} root document/fragment to create iterator for
* @return {Iterator} iterator instance * @return {Iterator} iterator instance
*/ */
var _createIterator = function _createIterator(root) { const _createIterator = function _createIterator(root) {
return createNodeIterator.call(root.ownerDocument || root, root, // eslint -disable-next-line no-bitwise return createNodeIterator.call(root.ownerDocument || root, root, // eslint -disable-next-line no-bitwise
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false); NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
}; };
/** /**
* _isClobbered * _isClobbered
* *
* @param {Node} elm element to check for clobbering attacks * @param {Node} elm element to check for clobbering attacks
* @return {Boolean} true if clobbered, false if safe * @return {Boolean} true if clobbered, false if safe
*/ */
var _isClobbered = function _isClobbered(elm) { const _isClobbered = function _isClobbered(elm) {
return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNod es !== 'function'); return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNod es !== 'function');
}; };
/** /**
* _isNode * _isNode
* *
* @param {Node} obj object to check whether it's a DOM node * @param {Node} obj object to check whether it's a DOM node
* @return {Boolean} true is object is a DOM node * @return {Boolean} true is object is a DOM node
*/ */
var _isNode = function _isNode(object) { const _isNode = function _isNode(object) {
return _typeof(Node) === 'object' ? object instanceof Node : object && _ty return typeof Node === 'object' ? object instanceof Node : object && typeo
peof(object) === 'object' && typeof object.nodeType === 'number' && typeof objec f object === 'object' && typeof object.nodeType === 'number' && typeof object.no
t.nodeName === 'string'; deName === 'string';
}; };
/** /**
* _executeHook * _executeHook
* Execute user configurable hooks * Execute user configurable hooks
* *
* @param {String} entryPoint Name of the hook's entry point * @param {String} entryPoint Name of the hook's entry point
* @param {Node} currentNode node to work on with the hook * @param {Node} currentNode node to work on with the hook
* @param {Object} data additional hook parameters * @param {Object} data additional hook parameters
*/ */
var _executeHook = function _executeHook(entryPoint, currentNode, data) { const _executeHook = function _executeHook(entryPoint, currentNode, data) {
if (!hooks[entryPoint]) { if (!hooks[entryPoint]) {
return; return;
} }
arrayForEach(hooks[entryPoint], function (hook) { arrayForEach(hooks[entryPoint], hook => {
hook.call(DOMPurify, currentNode, data, CONFIG); hook.call(DOMPurify, currentNode, data, CONFIG);
}); });
}; };
/** /**
* _sanitizeElements * _sanitizeElements
* *
* @protect nodeName * @protect nodeName
* @protect textContent * @protect textContent
* @protect removeChild * @protect removeChild
* *
* @param {Node} currentNode to check for permission to exist * @param {Node} currentNode to check for permission to exist
* @return {Boolean} true if node was killed, false if left alive * @return {Boolean} true if node was killed, false if left alive
*/ */
var _sanitizeElements = function _sanitizeElements(currentNode) { const _sanitizeElements = function _sanitizeElements(currentNode) {
var content; let content;
/* Execute a hook if present */ /* Execute a hook if present */
_executeHook('beforeSanitizeElements', currentNode, null); _executeHook('beforeSanitizeElements', currentNode, null);
/* Check if element is clobbered or can clobber */ /* Check if element is clobbered or can clobber */
if (_isClobbered(currentNode)) { if (_isClobbered(currentNode)) {
_forceRemove(currentNode); _forceRemove(currentNode);
return true; return true;
} }
/* Now let's check the element's type and name */ /* Now let's check the element's type and name */
var tagName = transformCaseFunc(currentNode.nodeName); const tagName = transformCaseFunc(currentNode.nodeName);
/* Execute a hook if present */ /* Execute a hook if present */
_executeHook('uponSanitizeElement', currentNode, { _executeHook('uponSanitizeElement', currentNode, {
tagName: tagName, tagName,
allowedTags: ALLOWED_TAGS allowedTags: ALLOWED_TAGS
}); });
/* Detect mXSS attempts abusing namespace confusion */ /* Detect mXSS attempts abusing namespace confusion */
if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementC hild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementC hild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
_forceRemove(currentNode); _forceRemove(currentNode);
return true; return true;
} }
/* Remove element if anything forbids its presence */ /* Remove element if anything forbids its presence */
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
/* Check if we have a custom element to handle */ /* Check if we have a custom element to handle */
if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) { if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTe st(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false; if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTe st(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM _ELEMENT_HANDLING.tagNameCheck(tagName)) return false; if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM _ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
} }
/* Keep content except for bad-listed elements */ /* Keep content except for bad-listed elements */
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
var parentNode = getParentNode(currentNode) || currentNode.parentNode; const parentNode = getParentNode(currentNode) || currentNode.parentNod
var childNodes = getChildNodes(currentNode) || currentNode.childNodes; e;
const childNodes = getChildNodes(currentNode) || currentNode.childNode
s;
if (childNodes && parentNode) { if (childNodes && parentNode) {
var childCount = childNodes.length; const childCount = childNodes.length;
for (var i = childCount - 1; i >= 0; --i) { for (let i = childCount - 1; i >= 0; --i) {
parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSib ling(currentNode)); parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSib ling(currentNode));
} }
} }
} }
_forceRemove(currentNode); _forceRemove(currentNode);
return true; return true;
} }
/* Check whether element has a valid namespace */ /* Check whether element has a valid namespace */
skipping to change at line 1189 skipping to change at line 1021
if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no (script|embed)/i, currentNode.innerHTML)) { if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no (script|embed)/i, currentNode.innerHTML)) {
_forceRemove(currentNode); _forceRemove(currentNode);
return true; return true;
} }
/* Sanitize element content to be template-safe */ /* Sanitize element content to be template-safe */
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) { if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
/* Get the element's text content */ /* Get the element's text content */
content = currentNode.textContent; content = currentNode.textContent;
content = stringReplace(content, MUSTACHE_EXPR$1, ' '); content = stringReplace(content, MUSTACHE_EXPR, ' ');
content = stringReplace(content, ERB_EXPR$1, ' '); content = stringReplace(content, ERB_EXPR, ' ');
content = stringReplace(content, TMPLIT_EXPR$1, ' '); content = stringReplace(content, TMPLIT_EXPR, ' ');
if (currentNode.textContent !== content) { if (currentNode.textContent !== content) {
arrayPush(DOMPurify.removed, { arrayPush(DOMPurify.removed, {
element: currentNode.cloneNode() element: currentNode.cloneNode()
}); });
currentNode.textContent = content; currentNode.textContent = content;
} }
} }
/* Execute a hook if present */ /* Execute a hook if present */
skipping to change at line 1216 skipping to change at line 1048
/** /**
* _isValidAttribute * _isValidAttribute
* *
* @param {string} lcTag Lowercase tag name of containing element. * @param {string} lcTag Lowercase tag name of containing element.
* @param {string} lcName Lowercase attribute name. * @param {string} lcName Lowercase attribute name.
* @param {string} value Attribute value. * @param {string} value Attribute value.
* @return {Boolean} Returns true if `value` is valid, otherwise false. * @return {Boolean} Returns true if `value` is valid, otherwise false.
*/ */
// eslint-disable-next-line complexity // eslint-disable-next-line complexity
var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
/* Make sure attribute cannot clobber */ /* Make sure attribute cannot clobber */
if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in do cument || value in formElement)) { if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in do cument || value in formElement)) {
return false; return false;
} }
/* Allow valid data-* attributes: At least one character after "-" /* Allow valid data-* attributes: At least one character after "-"
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non- visible-data-with-the-data-*-attributes) (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non- visible-data-with-the-data-*-attributes)
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure. html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure. html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
We don't need to check the value; it's always URI safe. */ We don't need to check the value; it's always URI safe. */
if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcN ame)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if ( !ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcNam e)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALL OWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
if ( // First condition does a very basic check if a) it's basically a v alid custom element tagname AND if ( // First condition does a very basic check if a) it's basically a v alid custom element tagname AND
// b) if the tagName passes whatever the user has configured for CUSTOM_ ELEMENT_HANDLING.tagNameCheck // b) if the tagName passes whatever the user has configured for CUSTOM_ ELEMENT_HANDLING.tagNameCheck
// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDL ING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instance of RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || C USTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_ HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND _basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDL ING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instance of RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || C USTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_ HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
// the value passes whatever the user has configured for CUSTOM_ELEMENT_ HANDLING.tagNameCheck // the value passes whatever the user has configured for CUSTOM_ELEMENT_ HANDLING.tagNameCheck
lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElement s && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTO M_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElement s && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTO M_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
return false; return false;
} }
/* Check value is safe. First, is attr inert? If so, is safe */ /* Check value is safe. First, is attr inert? If so, is safe */
} else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_U RI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && strin gIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN _PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESP ACE$1, ''))) ; else if (!value) ; else { } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_U RI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' | | lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringI ndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_P ROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (!value) ; else {
return false; return false;
} }
return true; return true;
}; };
/** /**
* _basicCustomElementCheck * _basicCustomElementCheck
* checks if at least one dash is included in tagName, and it's not the firs t char * checks if at least one dash is included in tagName, and it's not the firs t char
* for more sophisticated checking see https://github.com/sindresorhus/valid ate-element-name * for more sophisticated checking see https://github.com/sindresorhus/valid ate-element-name
* @param {string} tagName name of the tag of the node to sanitize * @param {string} tagName name of the tag of the node to sanitize
*/ */
var _basicCustomElementTest = function _basicCustomElementTest(tagName) { const _basicCustomElementTest = function _basicCustomElementTest(tagName) {
return tagName.indexOf('-') > 0; return tagName.indexOf('-') > 0;
}; };
/** /**
* _sanitizeAttributes * _sanitizeAttributes
* *
* @protect attributes * @protect attributes
* @protect nodeName * @protect nodeName
* @protect removeAttribute * @protect removeAttribute
* @protect setAttribute * @protect setAttribute
* *
* @param {Node} currentNode to sanitize * @param {Node} currentNode to sanitize
*/ */
var _sanitizeAttributes = function _sanitizeAttributes(currentNode) { const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
var attr; let attr;
var value; let value;
var lcName; let lcName;
var l; let l;
/* Execute a hook if present */ /* Execute a hook if present */
_executeHook('beforeSanitizeAttributes', currentNode, null); _executeHook('beforeSanitizeAttributes', currentNode, null);
var attributes = currentNode.attributes; const {
attributes
} = currentNode;
/* Check if we have attributes; if not we might have a text node */ /* Check if we have attributes; if not we might have a text node */
if (!attributes) { if (!attributes) {
return; return;
} }
var hookEvent = { const hookEvent = {
attrName: '', attrName: '',
attrValue: '', attrValue: '',
keepAttr: true, keepAttr: true,
allowedAttributes: ALLOWED_ATTR allowedAttributes: ALLOWED_ATTR
}; };
l = attributes.length; l = attributes.length;
/* Go backwards over all attributes; safely remove bad ones */ /* Go backwards over all attributes; safely remove bad ones */
while (l--) { while (l--) {
attr = attributes[l]; attr = attributes[l];
var _attr = attr, const {
name = _attr.name, name,
namespaceURI = _attr.namespaceURI; namespaceURI
} = attr;
value = name === 'value' ? attr.value : stringTrim(attr.value); value = name === 'value' ? attr.value : stringTrim(attr.value);
lcName = transformCaseFunc(name); lcName = transformCaseFunc(name);
/* Execute a hook if present */ /* Execute a hook if present */
hookEvent.attrName = lcName; hookEvent.attrName = lcName;
hookEvent.attrValue = value; hookEvent.attrValue = value;
hookEvent.keepAttr = true; hookEvent.keepAttr = true;
hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
_executeHook('uponSanitizeAttribute', currentNode, hookEvent); _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
skipping to change at line 1329 skipping to change at line 1164
/* Work around a security issue in jQuery 3.0 */ /* Work around a security issue in jQuery 3.0 */
if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
_removeAttribute(name, currentNode); _removeAttribute(name, currentNode);
continue; continue;
} }
/* Sanitize attribute content to be template-safe */ /* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) { if (SAFE_FOR_TEMPLATES) {
value = stringReplace(value, MUSTACHE_EXPR$1, ' '); value = stringReplace(value, MUSTACHE_EXPR, ' ');
value = stringReplace(value, ERB_EXPR$1, ' '); value = stringReplace(value, ERB_EXPR, ' ');
value = stringReplace(value, TMPLIT_EXPR$1, ' '); value = stringReplace(value, TMPLIT_EXPR, ' ');
} }
/* Is `value` valid for this attribute? */ /* Is `value` valid for this attribute? */
var lcTag = transformCaseFunc(currentNode.nodeName); const lcTag = transformCaseFunc(currentNode.nodeName);
if (!_isValidAttribute(lcTag, lcName, value)) { if (!_isValidAttribute(lcTag, lcName, value)) {
continue; continue;
} }
/* Full DOM Clobbering protection via namespace isolation, /* Full DOM Clobbering protection via namespace isolation,
* Prefix id and name attributes with `user-content-` * Prefix id and name attributes with `user-content-`
*/ */
if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) { if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
// Remove the attribute with this value // Remove the attribute with this value
_removeAttribute(name, currentNode); // Prefix the value and later re- create the attribute with the sanitized value _removeAttribute(name, currentNode); // Prefix the value and later re- create the attribute with the sanitized value
value = SANITIZE_NAMED_PROPS_PREFIX + value; value = SANITIZE_NAMED_PROPS_PREFIX + value;
} }
/* Handle attributes that require Trusted Types */ /* Handle attributes that require Trusted Types */
if (trustedTypesPolicy && _typeof(trustedTypes) === 'object' && typeof t rustedTypes.getAttributeType === 'function') { if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof tru stedTypes.getAttributeType === 'function') {
if (namespaceURI) ; else { if (namespaceURI) ; else {
switch (trustedTypes.getAttributeType(lcTag, lcName)) { switch (trustedTypes.getAttributeType(lcTag, lcName)) {
case 'TrustedHTML': case 'TrustedHTML':
value = trustedTypesPolicy.createHTML(value); value = trustedTypesPolicy.createHTML(value);
break; break;
case 'TrustedScriptURL': case 'TrustedScriptURL':
value = trustedTypesPolicy.createScriptURL(value); value = trustedTypesPolicy.createScriptURL(value);
break; break;
} }
skipping to change at line 1388 skipping to change at line 1223
/* Execute a hook if present */ /* Execute a hook if present */
_executeHook('afterSanitizeAttributes', currentNode, null); _executeHook('afterSanitizeAttributes', currentNode, null);
}; };
/** /**
* _sanitizeShadowDOM * _sanitizeShadowDOM
* *
* @param {DocumentFragment} fragment to iterate over recursively * @param {DocumentFragment} fragment to iterate over recursively
*/ */
var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) { const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
var shadowNode; let shadowNode;
var shadowIterator = _createIterator(fragment); const shadowIterator = _createIterator(fragment);
/* Execute a hook if present */ /* Execute a hook if present */
_executeHook('beforeSanitizeShadowDOM', fragment, null); _executeHook('beforeSanitizeShadowDOM', fragment, null);
while (shadowNode = shadowIterator.nextNode()) { while (shadowNode = shadowIterator.nextNode()) {
/* Execute a hook if present */ /* Execute a hook if present */
_executeHook('uponSanitizeShadowNode', shadowNode, null); _executeHook('uponSanitizeShadowNode', shadowNode, null);
/* Sanitize tags and elements */ /* Sanitize tags and elements */
if (_sanitizeElements(shadowNode)) { if (_sanitizeElements(shadowNode)) {
skipping to change at line 1427 skipping to change at line 1262
/** /**
* Sanitize * Sanitize
* Public method providing core sanitation functionality * Public method providing core sanitation functionality
* *
* @param {String|Node} dirty string or DOM node * @param {String|Node} dirty string or DOM node
* @param {Object} configuration object * @param {Object} configuration object
*/ */
// eslint-disable-next-line complexity // eslint-disable-next-line complexity
DOMPurify.sanitize = function (dirty) { DOMPurify.sanitize = function (dirty) {
var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1 let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1
] : {}; ] : {};
var body; let body;
var importedNode; let importedNode;
var currentNode; let currentNode;
var returnNode; let returnNode;
/* Make sure we have a string to sanitize. /* Make sure we have a string to sanitize.
DO NOT return early, as this will return the wrong type if DO NOT return early, as this will return the wrong type if
the user has requested a DOM object rather than a string */ the user has requested a DOM object rather than a string */
IS_EMPTY_INPUT = !dirty; IS_EMPTY_INPUT = !dirty;
if (IS_EMPTY_INPUT) { if (IS_EMPTY_INPUT) {
dirty = '<!-->'; dirty = '<!-->';
} }
/* Stringify, in case dirty is an object */ /* Stringify, in case dirty is an object */
skipping to change at line 1477 skipping to change at line 1312
DOMPurify.removed = []; DOMPurify.removed = [];
/* Check if dirty is correctly typed for IN_PLACE */ /* Check if dirty is correctly typed for IN_PLACE */
if (typeof dirty === 'string') { if (typeof dirty === 'string') {
IN_PLACE = false; IN_PLACE = false;
} }
if (IN_PLACE) { if (IN_PLACE) {
/* Do some early pre-sanitization to avoid unsafe root nodes */ /* Do some early pre-sanitization to avoid unsafe root nodes */
if (dirty.nodeName) { if (dirty.nodeName) {
var tagName = transformCaseFunc(dirty.nodeName); const tagName = transformCaseFunc(dirty.nodeName);
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
throw typeErrorCreate('root node is forbidden and cannot be sanitize d in-place'); throw typeErrorCreate('root node is forbidden and cannot be sanitize d in-place');
} }
} }
} else if (dirty instanceof Node) { } else if (dirty instanceof Node) {
/* If dirty is a DOM element, append to an empty document to avoid /* If dirty is a DOM element, append to an empty document to avoid
elements being stripped by the parser */ elements being stripped by the parser */
body = _initDocument('<!---->'); body = _initDocument('<!---->');
importedNode = body.ownerDocument.importNode(dirty, true); importedNode = body.ownerDocument.importNode(dirty, true);
skipping to change at line 1520 skipping to change at line 1355
return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
} }
} }
/* Remove first element node (ours) if FORCE_BODY is set */ /* Remove first element node (ours) if FORCE_BODY is set */
if (body && FORCE_BODY) { if (body && FORCE_BODY) {
_forceRemove(body.firstChild); _forceRemove(body.firstChild);
} }
/* Get node iterator */ /* Get node iterator */
var nodeIterator = _createIterator(IN_PLACE ? dirty : body); const nodeIterator = _createIterator(IN_PLACE ? dirty : body);
/* Now start iterating over the created document */ /* Now start iterating over the created document */
while (currentNode = nodeIterator.nextNode()) { while (currentNode = nodeIterator.nextNode()) {
/* Sanitize tags and elements */ /* Sanitize tags and elements */
if (_sanitizeElements(currentNode)) { if (_sanitizeElements(currentNode)) {
continue; continue;
} }
/* Shadow DOM detected, sanitize it */ /* Shadow DOM detected, sanitize it */
if (currentNode.content instanceof DocumentFragment) { if (currentNode.content instanceof DocumentFragment) {
skipping to change at line 1570 skipping to change at line 1405
in theory but we would rather not risk another attack vector. in theory but we would rather not risk another attack vector.
The state that is cloned by importNode() is explicitly defined The state that is cloned by importNode() is explicitly defined
by the specs. by the specs.
*/ */
returnNode = importNode.call(originalDocument, returnNode, true); returnNode = importNode.call(originalDocument, returnNode, true);
} }
return returnNode; return returnNode;
} }
var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
/* Serialize doctype if allowed */ /* Serialize doctype if allowed */
if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && bo dy.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYP E_NAME, body.ownerDocument.doctype.name)) { if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && bo dy.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYP E_NAME, body.ownerDocument.doctype.name)) {
serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML; serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
} }
/* Sanitize final string template-safe */ /* Sanitize final string template-safe */
if (SAFE_FOR_TEMPLATES) { if (SAFE_FOR_TEMPLATES) {
serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' '); serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR, ' ');
serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' '); serializedHTML = stringReplace(serializedHTML, ERB_EXPR, ' ');
serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR$1, ' '); serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR, ' ');
} }
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.crea teHTML(serializedHTML) : serializedHTML; return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.crea teHTML(serializedHTML) : serializedHTML;
}; };
/** /**
* Public method to set the configuration once * Public method to set the configuration once
* setConfig * setConfig
* *
* @param {Object} cfg configuration object * @param {Object} cfg configuration object
*/ */
skipping to change at line 1625 skipping to change at line 1460
* @param {string} value Attribute value. * @param {string} value Attribute value.
* @return {Boolean} Returns true if `value` is valid. Otherwise, returns fa lse. * @return {Boolean} Returns true if `value` is valid. Otherwise, returns fa lse.
*/ */
DOMPurify.isValidAttribute = function (tag, attr, value) { DOMPurify.isValidAttribute = function (tag, attr, value) {
/* Initialize shared config vars if necessary. */ /* Initialize shared config vars if necessary. */
if (!CONFIG) { if (!CONFIG) {
_parseConfig({}); _parseConfig({});
} }
var lcTag = transformCaseFunc(tag); const lcTag = transformCaseFunc(tag);
var lcName = transformCaseFunc(attr); const lcName = transformCaseFunc(attr);
return _isValidAttribute(lcTag, lcName, value); return _isValidAttribute(lcTag, lcName, value);
}; };
/** /**
* AddHook * AddHook
* Public method to add DOMPurify hooks * Public method to add DOMPurify hooks
* *
* @param {String} entryPoint entry point for the hook to add * @param {String} entryPoint entry point for the hook to add
* @param {Function} hookFunction function to execute * @param {Function} hookFunction function to execute
*/ */
 End of changes. 114 change blocks. 
522 lines changed or deleted 344 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)