| 1 | /*! @license DOMPurify 3.4.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.5/LICENSE */ |
| 2 | |
| 3 | (function (global, factory) { |
| 4 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : |
| 5 | typeof define === 'function' && define.amd ? define(factory) : |
| 6 | (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory()); |
| 7 | })(this, (function () { 'use strict'; |
| 8 | |
| 9 | function _arrayLikeToArray(r, a) { |
| 10 | (null == a || a > r.length) && (a = r.length); |
| 11 | for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; |
| 12 | return n; |
| 13 | } |
| 14 | function _arrayWithHoles(r) { |
| 15 | if (Array.isArray(r)) return r; |
| 16 | } |
| 17 | function _iterableToArrayLimit(r, l) { |
| 18 | var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; |
| 19 | if (null != t) { |
| 20 | var e, |
| 21 | n, |
| 22 | i, |
| 23 | u, |
| 24 | a = [], |
| 25 | f = true, |
| 26 | o = false; |
| 27 | try { |
| 28 | if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); |
| 29 | } catch (r) { |
| 30 | o = true, n = r; |
| 31 | } finally { |
| 32 | try { |
| 33 | if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; |
| 34 | } finally { |
| 35 | if (o) throw n; |
| 36 | } |
| 37 | } |
| 38 | return a; |
| 39 | } |
| 40 | } |
| 41 | function _nonIterableRest() { |
| 42 | throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); |
| 43 | } |
| 44 | function _slicedToArray(r, e) { |
| 45 | return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); |
| 46 | } |
| 47 | function _unsupportedIterableToArray(r, a) { |
| 48 | if (r) { |
| 49 | if ("string" == typeof r) return _arrayLikeToArray(r, a); |
| 50 | var t = {}.toString.call(r).slice(8, -1); |
| 51 | return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | const entries = Object.entries, |
| 56 | setPrototypeOf = Object.setPrototypeOf, |
| 57 | isFrozen = Object.isFrozen, |
| 58 | getPrototypeOf = Object.getPrototypeOf, |
| 59 | getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; |
| 60 | let freeze = Object.freeze, |
| 61 | seal = Object.seal, |
| 62 | create = Object.create; // eslint-disable-line import/no-mutable-exports |
| 63 | let _ref = typeof Reflect !== 'undefined' && Reflect, |
| 64 | apply = _ref.apply, |
| 65 | construct = _ref.construct; |
| 66 | if (!freeze) { |
| 67 | freeze = function freeze(x) { |
| 68 | return x; |
| 69 | }; |
| 70 | } |
| 71 | if (!seal) { |
| 72 | seal = function seal(x) { |
| 73 | return x; |
| 74 | }; |
| 75 | } |
| 76 | if (!apply) { |
| 77 | apply = function apply(func, thisArg) { |
| 78 | for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { |
| 79 | args[_key - 2] = arguments[_key]; |
| 80 | } |
| 81 | return func.apply(thisArg, args); |
| 82 | }; |
| 83 | } |
| 84 | if (!construct) { |
| 85 | construct = function construct(Func) { |
| 86 | for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { |
| 87 | args[_key2 - 1] = arguments[_key2]; |
| 88 | } |
| 89 | return new Func(...args); |
| 90 | }; |
| 91 | } |
| 92 | const arrayForEach = unapply(Array.prototype.forEach); |
| 93 | const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); |
| 94 | const arrayPop = unapply(Array.prototype.pop); |
| 95 | const arrayPush = unapply(Array.prototype.push); |
| 96 | const arraySplice = unapply(Array.prototype.splice); |
| 97 | const arrayIsArray = Array.isArray; |
| 98 | const stringToLowerCase = unapply(String.prototype.toLowerCase); |
| 99 | const stringToString = unapply(String.prototype.toString); |
| 100 | const stringMatch = unapply(String.prototype.match); |
| 101 | const stringReplace = unapply(String.prototype.replace); |
| 102 | const stringIndexOf = unapply(String.prototype.indexOf); |
| 103 | const stringTrim = unapply(String.prototype.trim); |
| 104 | const numberToString = unapply(Number.prototype.toString); |
| 105 | const booleanToString = unapply(Boolean.prototype.toString); |
| 106 | const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString); |
| 107 | const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString); |
| 108 | const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); |
| 109 | const objectToString = unapply(Object.prototype.toString); |
| 110 | const regExpTest = unapply(RegExp.prototype.test); |
| 111 | const typeErrorCreate = unconstruct(TypeError); |
| 112 | /** |
| 113 | * Creates a new function that calls the given function with a specified thisArg and arguments. |
| 114 | * |
| 115 | * @param func - The function to be wrapped and called. |
| 116 | * @returns A new function that calls the given function with a specified thisArg and arguments. |
| 117 | */ |
| 118 | function unapply(func) { |
| 119 | return function (thisArg) { |
| 120 | if (thisArg instanceof RegExp) { |
| 121 | thisArg.lastIndex = 0; |
| 122 | } |
| 123 | for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { |
| 124 | args[_key3 - 1] = arguments[_key3]; |
| 125 | } |
| 126 | return apply(func, thisArg, args); |
| 127 | }; |
| 128 | } |
| 129 | /** |
| 130 | * Creates a new function that constructs an instance of the given constructor function with the provided arguments. |
| 131 | * |
| 132 | * @param func - The constructor function to be wrapped and called. |
| 133 | * @returns A new function that constructs an instance of the given constructor function with the provided arguments. |
| 134 | */ |
| 135 | function unconstruct(Func) { |
| 136 | return function () { |
| 137 | for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { |
| 138 | args[_key4] = arguments[_key4]; |
| 139 | } |
| 140 | return construct(Func, args); |
| 141 | }; |
| 142 | } |
| 143 | /** |
| 144 | * Add properties to a lookup table |
| 145 | * |
| 146 | * @param set - The set to which elements will be added. |
| 147 | * @param array - The array containing elements to be added to the set. |
| 148 | * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. |
| 149 | * @returns The modified set with added elements. |
| 150 | */ |
| 151 | function addToSet(set, array) { |
| 152 | let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; |
| 153 | if (setPrototypeOf) { |
| 154 | // Make 'in' and truthy checks like Boolean(set.constructor) |
| 155 | // independent of any properties defined on Object.prototype. |
| 156 | // Prevent prototype setters from intercepting set as a this value. |
| 157 | setPrototypeOf(set, null); |
| 158 | } |
| 159 | if (!arrayIsArray(array)) { |
| 160 | return set; |
| 161 | } |
| 162 | let l = array.length; |
| 163 | while (l--) { |
| 164 | let element = array[l]; |
| 165 | if (typeof element === 'string') { |
| 166 | const lcElement = transformCaseFunc(element); |
| 167 | if (lcElement !== element) { |
| 168 | // Config presets (e.g. tags.js, attrs.js) are immutable. |
| 169 | if (!isFrozen(array)) { |
| 170 | array[l] = lcElement; |
| 171 | } |
| 172 | element = lcElement; |
| 173 | } |
| 174 | } |
| 175 | set[element] = true; |
| 176 | } |
| 177 | return set; |
| 178 | } |
| 179 | /** |
| 180 | * Clean up an array to harden against CSPP |
| 181 | * |
| 182 | * @param array - The array to be cleaned. |
| 183 | * @returns The cleaned version of the array |
| 184 | */ |
| 185 | function cleanArray(array) { |
| 186 | for (let index = 0; index < array.length; index++) { |
| 187 | const isPropertyExist = objectHasOwnProperty(array, index); |
| 188 | if (!isPropertyExist) { |
| 189 | array[index] = null; |
| 190 | } |
| 191 | } |
| 192 | return array; |
| 193 | } |
| 194 | /** |
| 195 | * Shallow clone an object |
| 196 | * |
| 197 | * @param object - The object to be cloned. |
| 198 | * @returns A new object that copies the original. |
| 199 | */ |
| 200 | function clone(object) { |
| 201 | const newObject = create(null); |
| 202 | for (const _ref2 of entries(object)) { |
| 203 | var _ref3 = _slicedToArray(_ref2, 2); |
| 204 | const property = _ref3[0]; |
| 205 | const value = _ref3[1]; |
| 206 | const isPropertyExist = objectHasOwnProperty(object, property); |
| 207 | if (isPropertyExist) { |
| 208 | if (arrayIsArray(value)) { |
| 209 | newObject[property] = cleanArray(value); |
| 210 | } else if (value && typeof value === 'object' && value.constructor === Object) { |
| 211 | newObject[property] = clone(value); |
| 212 | } else { |
| 213 | newObject[property] = value; |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | return newObject; |
| 218 | } |
| 219 | /** |
| 220 | * Convert non-node values into strings without depending on direct property access. |
| 221 | * |
| 222 | * @param value - The value to stringify. |
| 223 | * @returns A string representation of the provided value. |
| 224 | */ |
| 225 | function stringifyValue(value) { |
| 226 | switch (typeof value) { |
| 227 | case 'string': |
| 228 | { |
| 229 | return value; |
| 230 | } |
| 231 | case 'number': |
| 232 | { |
| 233 | return numberToString(value); |
| 234 | } |
| 235 | case 'boolean': |
| 236 | { |
| 237 | return booleanToString(value); |
| 238 | } |
| 239 | case 'bigint': |
| 240 | { |
| 241 | return bigintToString ? bigintToString(value) : '0'; |
| 242 | } |
| 243 | case 'symbol': |
| 244 | { |
| 245 | return symbolToString ? symbolToString(value) : 'Symbol()'; |
| 246 | } |
| 247 | case 'undefined': |
| 248 | { |
| 249 | return objectToString(value); |
| 250 | } |
| 251 | case 'function': |
| 252 | case 'object': |
| 253 | { |
| 254 | if (value === null) { |
| 255 | return objectToString(value); |
| 256 | } |
| 257 | const valueAsRecord = value; |
| 258 | const valueToString = lookupGetter(valueAsRecord, 'toString'); |
| 259 | if (typeof valueToString === 'function') { |
| 260 | const stringified = valueToString(valueAsRecord); |
| 261 | return typeof stringified === 'string' ? stringified : objectToString(stringified); |
| 262 | } |
| 263 | return objectToString(value); |
| 264 | } |
| 265 | default: |
| 266 | { |
| 267 | return objectToString(value); |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | /** |
| 272 | * This method automatically checks if the prop is function or getter and behaves accordingly. |
| 273 | * |
| 274 | * @param object - The object to look up the getter function in its prototype chain. |
| 275 | * @param prop - The property name for which to find the getter function. |
| 276 | * @returns The getter function found in the prototype chain or a fallback function. |
| 277 | */ |
| 278 | function lookupGetter(object, prop) { |
| 279 | while (object !== null) { |
| 280 | const desc = getOwnPropertyDescriptor(object, prop); |
| 281 | if (desc) { |
| 282 | if (desc.get) { |
| 283 | return unapply(desc.get); |
| 284 | } |
| 285 | if (typeof desc.value === 'function') { |
| 286 | return unapply(desc.value); |
| 287 | } |
| 288 | } |
| 289 | object = getPrototypeOf(object); |
| 290 | } |
| 291 | function fallbackValue() { |
| 292 | return null; |
| 293 | } |
| 294 | return fallbackValue; |
| 295 | } |
| 296 | function isRegex(value) { |
| 297 | try { |
| 298 | regExpTest(value, ''); |
| 299 | return true; |
| 300 | } catch (_unused) { |
| 301 | return false; |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | 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', 'content', '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', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', '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']); |
| 306 | const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); |
| 307 | const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); |
| 308 | // List of SVG elements that are disallowed by default. |
| 309 | // We still need to know them so that we can do namespace |
| 310 | // checks properly in case one wants to add them to |
| 311 | // allow-list. |
| 312 | const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); |
| 313 | const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); |
| 314 | // Similarly to SVG, we want to know all MathML elements, |
| 315 | // even those that we disallow by default. |
| 316 | const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); |
| 317 | const text = freeze(['#text']); |
| 318 | |
| 319 | const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']); |
| 320 | const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); |
| 321 | const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); |
| 322 | const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); |
| 323 | |
| 324 | const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g); |
| 325 | const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g); |
| 326 | const TMPLIT_EXPR = seal(/\${[\w\W]*/g); |
| 327 | const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape |
| 328 | const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape |
| 329 | const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape |
| 330 | ); |
| 331 | const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); |
| 332 | const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex |
| 333 | ); |
| 334 | const DOCTYPE_NAME = seal(/^html$/i); |
| 335 | const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); |
| 336 | |
| 337 | /* eslint-disable @typescript-eslint/indent */ |
| 338 | // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType |
| 339 | const NODE_TYPE = { |
| 340 | element: 1, |
| 341 | text: 3, |
| 342 | // Deprecated |
| 343 | progressingInstruction: 7, |
| 344 | comment: 8, |
| 345 | document: 9}; |
| 346 | const getGlobal = function getGlobal() { |
| 347 | return typeof window === 'undefined' ? null : window; |
| 348 | }; |
| 349 | /** |
| 350 | * Creates a no-op policy for internal use only. |
| 351 | * Don't export this function outside this module! |
| 352 | * @param trustedTypes The policy factory. |
| 353 | * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). |
| 354 | * @return The policy created (or null, if Trusted Types |
| 355 | * are not supported or creating the policy failed). |
| 356 | */ |
| 357 | const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { |
| 358 | if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { |
| 359 | return null; |
| 360 | } |
| 361 | // Allow the callers to control the unique policy name |
| 362 | // by adding a data-tt-policy-suffix to the script element with the DOMPurify. |
| 363 | // Policy creation with duplicate names throws in Trusted Types. |
| 364 | let suffix = null; |
| 365 | const ATTR_NAME = 'data-tt-policy-suffix'; |
| 366 | if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { |
| 367 | suffix = purifyHostElement.getAttribute(ATTR_NAME); |
| 368 | } |
| 369 | const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); |
| 370 | try { |
| 371 | return trustedTypes.createPolicy(policyName, { |
| 372 | createHTML(html) { |
| 373 | return html; |
| 374 | }, |
| 375 | createScriptURL(scriptUrl) { |
| 376 | return scriptUrl; |
| 377 | } |
| 378 | }); |
| 379 | } catch (_) { |
| 380 | // Policy creation failed (most likely another DOMPurify script has |
| 381 | // already run). Skip creating the policy, as this will only cause errors |
| 382 | // if TT are enforced. |
| 383 | console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); |
| 384 | return null; |
| 385 | } |
| 386 | }; |
| 387 | const _createHooksMap = function _createHooksMap() { |
| 388 | return { |
| 389 | afterSanitizeAttributes: [], |
| 390 | afterSanitizeElements: [], |
| 391 | afterSanitizeShadowDOM: [], |
| 392 | beforeSanitizeAttributes: [], |
| 393 | beforeSanitizeElements: [], |
| 394 | beforeSanitizeShadowDOM: [], |
| 395 | uponSanitizeAttribute: [], |
| 396 | uponSanitizeElement: [], |
| 397 | uponSanitizeShadowNode: [] |
| 398 | }; |
| 399 | }; |
| 400 | function createDOMPurify() { |
| 401 | let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); |
| 402 | const DOMPurify = root => createDOMPurify(root); |
| 403 | DOMPurify.version = '3.4.5'; |
| 404 | DOMPurify.removed = []; |
| 405 | if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { |
| 406 | // Not running in a browser, provide a factory function |
| 407 | // so that you can pass your own Window |
| 408 | DOMPurify.isSupported = false; |
| 409 | return DOMPurify; |
| 410 | } |
| 411 | let document = window.document; |
| 412 | const originalDocument = document; |
| 413 | const currentScript = originalDocument.currentScript; |
| 414 | const DocumentFragment = window.DocumentFragment, |
| 415 | HTMLTemplateElement = window.HTMLTemplateElement, |
| 416 | Node = window.Node, |
| 417 | Element = window.Element, |
| 418 | NodeFilter = window.NodeFilter, |
| 419 | _window$NamedNodeMap = window.NamedNodeMap, |
| 420 | NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, |
| 421 | HTMLFormElement = window.HTMLFormElement, |
| 422 | DOMParser = window.DOMParser, |
| 423 | trustedTypes = window.trustedTypes; |
| 424 | const ElementPrototype = Element.prototype; |
| 425 | const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); |
| 426 | const remove = lookupGetter(ElementPrototype, 'remove'); |
| 427 | const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); |
| 428 | const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); |
| 429 | const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); |
| 430 | const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null; |
| 431 | // As per issue #47, the web-components registry is inherited by a |
| 432 | // new document created via createHTMLDocument. As per the spec |
| 433 | // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) |
| 434 | // a new empty registry is used when creating a template contents owner |
| 435 | // document, so we use that as our parent document to ensure nothing |
| 436 | // is inherited. |
| 437 | if (typeof HTMLTemplateElement === 'function') { |
| 438 | const template = document.createElement('template'); |
| 439 | if (template.content && template.content.ownerDocument) { |
| 440 | document = template.content.ownerDocument; |
| 441 | } |
| 442 | } |
| 443 | let trustedTypesPolicy; |
| 444 | let emptyHTML = ''; |
| 445 | const _document = document, |
| 446 | implementation = _document.implementation, |
| 447 | createNodeIterator = _document.createNodeIterator, |
| 448 | createDocumentFragment = _document.createDocumentFragment, |
| 449 | getElementsByTagName = _document.getElementsByTagName; |
| 450 | const importNode = originalDocument.importNode; |
| 451 | let hooks = _createHooksMap(); |
| 452 | /** |
| 453 | * Expose whether this browser supports running the full DOMPurify. |
| 454 | */ |
| 455 | DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; |
| 456 | const MUSTACHE_EXPR$1 = MUSTACHE_EXPR, |
| 457 | ERB_EXPR$1 = ERB_EXPR, |
| 458 | TMPLIT_EXPR$1 = TMPLIT_EXPR, |
| 459 | DATA_ATTR$1 = DATA_ATTR, |
| 460 | ARIA_ATTR$1 = ARIA_ATTR, |
| 461 | IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, |
| 462 | ATTR_WHITESPACE$1 = ATTR_WHITESPACE, |
| 463 | CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT; |
| 464 | let IS_ALLOWED_URI$1 = IS_ALLOWED_URI; |
| 465 | /** |
| 466 | * We consider the elements and attributes below to be safe. Ideally |
| 467 | * don't add any new ones but feel free to remove unwanted ones. |
| 468 | */ |
| 469 | /* allowed element names */ |
| 470 | let ALLOWED_TAGS = null; |
| 471 | const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); |
| 472 | /* Allowed attribute names */ |
| 473 | let ALLOWED_ATTR = null; |
| 474 | const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); |
| 475 | /* |
| 476 | * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. |
| 477 | * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) |
| 478 | * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) |
| 479 | * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. |
| 480 | */ |
| 481 | let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { |
| 482 | tagNameCheck: { |
| 483 | writable: true, |
| 484 | configurable: false, |
| 485 | enumerable: true, |
| 486 | value: null |
| 487 | }, |
| 488 | attributeNameCheck: { |
| 489 | writable: true, |
| 490 | configurable: false, |
| 491 | enumerable: true, |
| 492 | value: null |
| 493 | }, |
| 494 | allowCustomizedBuiltInElements: { |
| 495 | writable: true, |
| 496 | configurable: false, |
| 497 | enumerable: true, |
| 498 | value: false |
| 499 | } |
| 500 | })); |
| 501 | /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ |
| 502 | let FORBID_TAGS = null; |
| 503 | /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ |
| 504 | let FORBID_ATTR = null; |
| 505 | /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */ |
| 506 | const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { |
| 507 | tagCheck: { |
| 508 | writable: true, |
| 509 | configurable: false, |
| 510 | enumerable: true, |
| 511 | value: null |
| 512 | }, |
| 513 | attributeCheck: { |
| 514 | writable: true, |
| 515 | configurable: false, |
| 516 | enumerable: true, |
| 517 | value: null |
| 518 | } |
| 519 | })); |
| 520 | /* Decide if ARIA attributes are okay */ |
| 521 | let ALLOW_ARIA_ATTR = true; |
| 522 | /* Decide if custom data attributes are okay */ |
| 523 | let ALLOW_DATA_ATTR = true; |
| 524 | /* Decide if unknown protocols are okay */ |
| 525 | let ALLOW_UNKNOWN_PROTOCOLS = false; |
| 526 | /* Decide if self-closing tags in attributes are allowed. |
| 527 | * Usually removed due to a mXSS issue in jQuery 3.0 */ |
| 528 | let ALLOW_SELF_CLOSE_IN_ATTR = true; |
| 529 | /* Output should be safe for common template engines. |
| 530 | * This means, DOMPurify removes data attributes, mustaches and ERB |
| 531 | */ |
| 532 | let SAFE_FOR_TEMPLATES = false; |
| 533 | /* Output should be safe even for XML used within HTML and alike. |
| 534 | * This means, DOMPurify removes comments when containing risky content. |
| 535 | */ |
| 536 | let SAFE_FOR_XML = true; |
| 537 | /* Decide if document with <html>... should be returned */ |
| 538 | let WHOLE_DOCUMENT = false; |
| 539 | /* Track whether config is already set on this instance of DOMPurify. */ |
| 540 | let SET_CONFIG = false; |
| 541 | /* Decide if all elements (e.g. style, script) must be children of |
| 542 | * document.body. By default, browsers might move them to document.head */ |
| 543 | let FORCE_BODY = false; |
| 544 | /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html |
| 545 | * string (or a TrustedHTML object if Trusted Types are supported). |
| 546 | * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead |
| 547 | */ |
| 548 | let RETURN_DOM = false; |
| 549 | /* Decide if a DOM `DocumentFragment` should be returned, instead of a html |
| 550 | * string (or a TrustedHTML object if Trusted Types are supported) */ |
| 551 | let RETURN_DOM_FRAGMENT = false; |
| 552 | /* Try to return a Trusted Type object instead of a string, return a string in |
| 553 | * case Trusted Types are not supported */ |
| 554 | let RETURN_TRUSTED_TYPE = false; |
| 555 | /* Output should be free from DOM clobbering attacks? |
| 556 | * This sanitizes markups named with colliding, clobberable built-in DOM APIs. |
| 557 | */ |
| 558 | let SANITIZE_DOM = true; |
| 559 | /* Achieve full DOM Clobbering protection by isolating the namespace of named |
| 560 | * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. |
| 561 | * |
| 562 | * HTML/DOM spec rules that enable DOM Clobbering: |
| 563 | * - Named Access on Window (§7.3.3) |
| 564 | * - DOM Tree Accessors (§3.1.5) |
| 565 | * - Form Element Parent-Child Relations (§4.10.3) |
| 566 | * - Iframe srcdoc / Nested WindowProxies (§4.8.5) |
| 567 | * - HTMLCollection (§4.2.10.2) |
| 568 | * |
| 569 | * Namespace isolation is implemented by prefixing `id` and `name` attributes |
| 570 | * with a constant string, i.e., `user-content-` |
| 571 | */ |
| 572 | let SANITIZE_NAMED_PROPS = false; |
| 573 | const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; |
| 574 | /* Keep element content when removing element? */ |
| 575 | let KEEP_CONTENT = true; |
| 576 | /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead |
| 577 | * of importing it into a new Document and returning a sanitized copy */ |
| 578 | let IN_PLACE = false; |
| 579 | /* Allow usage of profiles like html, svg and mathMl */ |
| 580 | let USE_PROFILES = {}; |
| 581 | /* Tags to ignore content of when KEEP_CONTENT is true */ |
| 582 | let FORBID_CONTENTS = null; |
| 583 | const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); |
| 584 | /* Tags that are safe for data: URIs */ |
| 585 | let DATA_URI_TAGS = null; |
| 586 | const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); |
| 587 | /* Attributes safe for values like "javascript:" */ |
| 588 | let URI_SAFE_ATTRIBUTES = null; |
| 589 | const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); |
| 590 | const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; |
| 591 | const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; |
| 592 | const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; |
| 593 | /* Document namespace */ |
| 594 | let NAMESPACE = HTML_NAMESPACE; |
| 595 | let IS_EMPTY_INPUT = false; |
| 596 | /* Allowed XHTML+XML namespaces */ |
| 597 | let ALLOWED_NAMESPACES = null; |
| 598 | const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); |
| 599 | let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); |
| 600 | let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); |
| 601 | // Certain elements are allowed in both SVG and HTML |
| 602 | // namespace. We need to specify them explicitly |
| 603 | // so that they don't get erroneously deleted from |
| 604 | // HTML namespace. |
| 605 | const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); |
| 606 | /* Parsing of strict XHTML documents */ |
| 607 | let PARSER_MEDIA_TYPE = null; |
| 608 | const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; |
| 609 | const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; |
| 610 | let transformCaseFunc = null; |
| 611 | /* Keep a reference to config to pass to hooks */ |
| 612 | let CONFIG = null; |
| 613 | /* Ideally, do not touch anything below this line */ |
| 614 | /* ______________________________________________ */ |
| 615 | const formElement = document.createElement('form'); |
| 616 | const isRegexOrFunction = function isRegexOrFunction(testValue) { |
| 617 | return testValue instanceof RegExp || testValue instanceof Function; |
| 618 | }; |
| 619 | /** |
| 620 | * _parseConfig |
| 621 | * |
| 622 | * @param cfg optional config literal |
| 623 | */ |
| 624 | // eslint-disable-next-line complexity |
| 625 | const _parseConfig = function _parseConfig() { |
| 626 | let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; |
| 627 | if (CONFIG && CONFIG === cfg) { |
| 628 | return; |
| 629 | } |
| 630 | /* Shield configuration object from tampering */ |
| 631 | if (!cfg || typeof cfg !== 'object') { |
| 632 | cfg = {}; |
| 633 | } |
| 634 | /* Shield configuration object from prototype pollution */ |
| 635 | cfg = clone(cfg); |
| 636 | PARSER_MEDIA_TYPE = |
| 637 | // eslint-disable-next-line unicorn/prefer-includes |
| 638 | SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; |
| 639 | // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. |
| 640 | transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; |
| 641 | /* Set configuration parameters */ |
| 642 | ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; |
| 643 | ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; |
| 644 | ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; |
| 645 | URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; |
| 646 | DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; |
| 647 | FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; |
| 648 | FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({}); |
| 649 | FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({}); |
| 650 | USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false; |
| 651 | ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true |
| 652 | ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true |
| 653 | ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false |
| 654 | ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true |
| 655 | SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false |
| 656 | SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true |
| 657 | WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false |
| 658 | RETURN_DOM = cfg.RETURN_DOM || false; // Default false |
| 659 | RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false |
| 660 | RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false |
| 661 | FORCE_BODY = cfg.FORCE_BODY || false; // Default false |
| 662 | SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true |
| 663 | SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false |
| 664 | KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true |
| 665 | IN_PLACE = cfg.IN_PLACE || false; // Default false |
| 666 | IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp |
| 667 | NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace |
| 668 | MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map |
| 669 | HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map |
| 670 | const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null); |
| 671 | CUSTOM_ELEMENT_HANDLING = create(null); |
| 672 | if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) { |
| 673 | CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined |
| 674 | } |
| 675 | if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) { |
| 676 | CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined |
| 677 | } |
| 678 | if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') { |
| 679 | CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined |
| 680 | } |
| 681 | if (SAFE_FOR_TEMPLATES) { |
| 682 | ALLOW_DATA_ATTR = false; |
| 683 | } |
| 684 | if (RETURN_DOM_FRAGMENT) { |
| 685 | RETURN_DOM = true; |
| 686 | } |
| 687 | /* Parse profile info */ |
| 688 | if (USE_PROFILES) { |
| 689 | ALLOWED_TAGS = addToSet({}, text); |
| 690 | ALLOWED_ATTR = create(null); |
| 691 | if (USE_PROFILES.html === true) { |
| 692 | addToSet(ALLOWED_TAGS, html$1); |
| 693 | addToSet(ALLOWED_ATTR, html); |
| 694 | } |
| 695 | if (USE_PROFILES.svg === true) { |
| 696 | addToSet(ALLOWED_TAGS, svg$1); |
| 697 | addToSet(ALLOWED_ATTR, svg); |
| 698 | addToSet(ALLOWED_ATTR, xml); |
| 699 | } |
| 700 | if (USE_PROFILES.svgFilters === true) { |
| 701 | addToSet(ALLOWED_TAGS, svgFilters); |
| 702 | addToSet(ALLOWED_ATTR, svg); |
| 703 | addToSet(ALLOWED_ATTR, xml); |
| 704 | } |
| 705 | if (USE_PROFILES.mathMl === true) { |
| 706 | addToSet(ALLOWED_TAGS, mathMl$1); |
| 707 | addToSet(ALLOWED_ATTR, mathMl); |
| 708 | addToSet(ALLOWED_ATTR, xml); |
| 709 | } |
| 710 | } |
| 711 | /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent |
| 712 | * leaking across calls when switching from function to array config */ |
| 713 | EXTRA_ELEMENT_HANDLING.tagCheck = null; |
| 714 | EXTRA_ELEMENT_HANDLING.attributeCheck = null; |
| 715 | /* Merge configuration parameters */ |
| 716 | if (objectHasOwnProperty(cfg, 'ADD_TAGS')) { |
| 717 | if (typeof cfg.ADD_TAGS === 'function') { |
| 718 | EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS; |
| 719 | } else if (arrayIsArray(cfg.ADD_TAGS)) { |
| 720 | if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { |
| 721 | ALLOWED_TAGS = clone(ALLOWED_TAGS); |
| 722 | } |
| 723 | addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); |
| 724 | } |
| 725 | } |
| 726 | if (objectHasOwnProperty(cfg, 'ADD_ATTR')) { |
| 727 | if (typeof cfg.ADD_ATTR === 'function') { |
| 728 | EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR; |
| 729 | } else if (arrayIsArray(cfg.ADD_ATTR)) { |
| 730 | if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { |
| 731 | ALLOWED_ATTR = clone(ALLOWED_ATTR); |
| 732 | } |
| 733 | addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); |
| 734 | } |
| 735 | } |
| 736 | if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) { |
| 737 | addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); |
| 738 | } |
| 739 | if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) { |
| 740 | if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { |
| 741 | FORBID_CONTENTS = clone(FORBID_CONTENTS); |
| 742 | } |
| 743 | addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); |
| 744 | } |
| 745 | if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) { |
| 746 | if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { |
| 747 | FORBID_CONTENTS = clone(FORBID_CONTENTS); |
| 748 | } |
| 749 | addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc); |
| 750 | } |
| 751 | /* Add #text in case KEEP_CONTENT is set to true */ |
| 752 | if (KEEP_CONTENT) { |
| 753 | ALLOWED_TAGS['#text'] = true; |
| 754 | } |
| 755 | /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ |
| 756 | if (WHOLE_DOCUMENT) { |
| 757 | addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); |
| 758 | } |
| 759 | /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ |
| 760 | if (ALLOWED_TAGS.table) { |
| 761 | addToSet(ALLOWED_TAGS, ['tbody']); |
| 762 | delete FORBID_TAGS.tbody; |
| 763 | } |
| 764 | if (cfg.TRUSTED_TYPES_POLICY) { |
| 765 | if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { |
| 766 | throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); |
| 767 | } |
| 768 | if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { |
| 769 | throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); |
| 770 | } |
| 771 | // Overwrite existing TrustedTypes policy. |
| 772 | trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; |
| 773 | // Sign local variables required by `sanitize`. |
| 774 | emptyHTML = trustedTypesPolicy.createHTML(''); |
| 775 | } else { |
| 776 | // Uninitialized policy, attempt to initialize the internal dompurify policy. |
| 777 | if (trustedTypesPolicy === undefined) { |
| 778 | trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); |
| 779 | } |
| 780 | // If creating the internal policy succeeded sign internal variables. |
| 781 | if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { |
| 782 | emptyHTML = trustedTypesPolicy.createHTML(''); |
| 783 | } |
| 784 | } |
| 785 | // Prevent further manipulation of configuration. |
| 786 | // Not available in IE8, Safari 5, etc. |
| 787 | if (freeze) { |
| 788 | freeze(cfg); |
| 789 | } |
| 790 | CONFIG = cfg; |
| 791 | }; |
| 792 | /* Keep track of all possible SVG and MathML tags |
| 793 | * so that we can perform the namespace checks |
| 794 | * correctly. */ |
| 795 | const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); |
| 796 | const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); |
| 797 | /** |
| 798 | * @param element a DOM element whose namespace is being checked |
| 799 | * @returns Return false if the element has a |
| 800 | * namespace that a spec-compliant parser would never |
| 801 | * return. Return true otherwise. |
| 802 | */ |
| 803 | const _checkValidNamespace = function _checkValidNamespace(element) { |
| 804 | let parent = getParentNode(element); |
| 805 | // In JSDOM, if we're inside shadow DOM, then parentNode |
| 806 | // can be null. We just simulate parent in this case. |
| 807 | if (!parent || !parent.tagName) { |
| 808 | parent = { |
| 809 | namespaceURI: NAMESPACE, |
| 810 | tagName: 'template' |
| 811 | }; |
| 812 | } |
| 813 | const tagName = stringToLowerCase(element.tagName); |
| 814 | const parentTagName = stringToLowerCase(parent.tagName); |
| 815 | if (!ALLOWED_NAMESPACES[element.namespaceURI]) { |
| 816 | return false; |
| 817 | } |
| 818 | if (element.namespaceURI === SVG_NAMESPACE) { |
| 819 | // The only way to switch from HTML namespace to SVG |
| 820 | // is via <svg>. If it happens via any other tag, then |
| 821 | // it should be killed. |
| 822 | if (parent.namespaceURI === HTML_NAMESPACE) { |
| 823 | return tagName === 'svg'; |
| 824 | } |
| 825 | // The only way to switch from MathML to SVG is via` |
| 826 | // svg if parent is either <annotation-xml> or MathML |
| 827 | // text integration points. |
| 828 | if (parent.namespaceURI === MATHML_NAMESPACE) { |
| 829 | return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); |
| 830 | } |
| 831 | // We only allow elements that are defined in SVG |
| 832 | // spec. All others are disallowed in SVG namespace. |
| 833 | return Boolean(ALL_SVG_TAGS[tagName]); |
| 834 | } |
| 835 | if (element.namespaceURI === MATHML_NAMESPACE) { |
| 836 | // The only way to switch from HTML namespace to MathML |
| 837 | // is via <math>. If it happens via any other tag, then |
| 838 | // it should be killed. |
| 839 | if (parent.namespaceURI === HTML_NAMESPACE) { |
| 840 | return tagName === 'math'; |
| 841 | } |
| 842 | // The only way to switch from SVG to MathML is via |
| 843 | // <math> and HTML integration points |
| 844 | if (parent.namespaceURI === SVG_NAMESPACE) { |
| 845 | return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; |
| 846 | } |
| 847 | // We only allow elements that are defined in MathML |
| 848 | // spec. All others are disallowed in MathML namespace. |
| 849 | return Boolean(ALL_MATHML_TAGS[tagName]); |
| 850 | } |
| 851 | if (element.namespaceURI === HTML_NAMESPACE) { |
| 852 | // The only way to switch from SVG to HTML is via |
| 853 | // HTML integration points, and from MathML to HTML |
| 854 | // is via MathML text integration points |
| 855 | if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { |
| 856 | return false; |
| 857 | } |
| 858 | if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { |
| 859 | return false; |
| 860 | } |
| 861 | // We disallow tags that are specific for MathML |
| 862 | // or SVG and should never appear in HTML namespace |
| 863 | return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); |
| 864 | } |
| 865 | // For XHTML and XML documents that support custom namespaces |
| 866 | if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { |
| 867 | return true; |
| 868 | } |
| 869 | // The code should never reach this place (this means |
| 870 | // that the element somehow got namespace that is not |
| 871 | // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). |
| 872 | // Return false just in case. |
| 873 | return false; |
| 874 | }; |
| 875 | /** |
| 876 | * _forceRemove |
| 877 | * |
| 878 | * @param node a DOM node |
| 879 | */ |
| 880 | const _forceRemove = function _forceRemove(node) { |
| 881 | arrayPush(DOMPurify.removed, { |
| 882 | element: node |
| 883 | }); |
| 884 | try { |
| 885 | // eslint-disable-next-line unicorn/prefer-dom-node-remove |
| 886 | getParentNode(node).removeChild(node); |
| 887 | } catch (_) { |
| 888 | remove(node); |
| 889 | } |
| 890 | }; |
| 891 | /** |
| 892 | * _removeAttribute |
| 893 | * |
| 894 | * @param name an Attribute name |
| 895 | * @param element a DOM node |
| 896 | */ |
| 897 | const _removeAttribute = function _removeAttribute(name, element) { |
| 898 | try { |
| 899 | arrayPush(DOMPurify.removed, { |
| 900 | attribute: element.getAttributeNode(name), |
| 901 | from: element |
| 902 | }); |
| 903 | } catch (_) { |
| 904 | arrayPush(DOMPurify.removed, { |
| 905 | attribute: null, |
| 906 | from: element |
| 907 | }); |
| 908 | } |
| 909 | element.removeAttribute(name); |
| 910 | // We void attribute values for unremovable "is" attributes |
| 911 | if (name === 'is') { |
| 912 | if (RETURN_DOM || RETURN_DOM_FRAGMENT) { |
| 913 | try { |
| 914 | _forceRemove(element); |
| 915 | } catch (_) {} |
| 916 | } else { |
| 917 | try { |
| 918 | element.setAttribute(name, ''); |
| 919 | } catch (_) {} |
| 920 | } |
| 921 | } |
| 922 | }; |
| 923 | /** |
| 924 | * _initDocument |
| 925 | * |
| 926 | * @param dirty - a string of dirty markup |
| 927 | * @return a DOM, filled with the dirty markup |
| 928 | */ |
| 929 | const _initDocument = function _initDocument(dirty) { |
| 930 | /* Create a HTML document */ |
| 931 | let doc = null; |
| 932 | let leadingWhitespace = null; |
| 933 | if (FORCE_BODY) { |
| 934 | dirty = '<remove></remove>' + dirty; |
| 935 | } else { |
| 936 | /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ |
| 937 | const matches = stringMatch(dirty, /^[\r\n\t ]+/); |
| 938 | leadingWhitespace = matches && matches[0]; |
| 939 | } |
| 940 | if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { |
| 941 | // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) |
| 942 | dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>'; |
| 943 | } |
| 944 | const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; |
| 945 | /* |
| 946 | * Use the DOMParser API by default, fallback later if needs be |
| 947 | * DOMParser not work for svg when has multiple root element. |
| 948 | */ |
| 949 | if (NAMESPACE === HTML_NAMESPACE) { |
| 950 | try { |
| 951 | doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); |
| 952 | } catch (_) {} |
| 953 | } |
| 954 | /* Use createHTMLDocument in case DOMParser is not available */ |
| 955 | if (!doc || !doc.documentElement) { |
| 956 | doc = implementation.createDocument(NAMESPACE, 'template', null); |
| 957 | try { |
| 958 | doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; |
| 959 | } catch (_) { |
| 960 | // Syntax error if dirtyPayload is invalid xml |
| 961 | } |
| 962 | } |
| 963 | const body = doc.body || doc.documentElement; |
| 964 | if (dirty && leadingWhitespace) { |
| 965 | body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); |
| 966 | } |
| 967 | /* Work on whole document or just its body */ |
| 968 | if (NAMESPACE === HTML_NAMESPACE) { |
| 969 | return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; |
| 970 | } |
| 971 | return WHOLE_DOCUMENT ? doc.documentElement : body; |
| 972 | }; |
| 973 | /** |
| 974 | * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. |
| 975 | * |
| 976 | * @param root The root element or node to start traversing on. |
| 977 | * @return The created NodeIterator |
| 978 | */ |
| 979 | const _createNodeIterator = function _createNodeIterator(root) { |
| 980 | return createNodeIterator.call(root.ownerDocument || root, root, |
| 981 | // eslint-disable-next-line no-bitwise |
| 982 | NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); |
| 983 | }; |
| 984 | /** |
| 985 | * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the |
| 986 | * character data of an element subtree. Used as the final safety net for |
| 987 | * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions |
| 988 | * which only form after text-node normalization (e.g. fragments split across |
| 989 | * stripped elements) cannot survive into a template-evaluating framework. |
| 990 | * |
| 991 | * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data` |
| 992 | * in place rather than round-tripping through innerHTML. This preserves |
| 993 | * descendant node references (important for IN_PLACE callers), avoids a |
| 994 | * serialize/reparse cycle, and reads literal character data — which means |
| 995 | * `<%...%>` in text content matches the ERB regex against its real bytes |
| 996 | * instead of the HTML-entity-escaped form innerHTML would produce. |
| 997 | * |
| 998 | * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for |
| 999 | * attributes is performed during the per-node `_sanitizeAttributes` pass. |
| 1000 | * |
| 1001 | * @param node The root element whose character data should be scrubbed. |
| 1002 | */ |
| 1003 | const _scrubTemplateExpressions = function _scrubTemplateExpressions(node) { |
| 1004 | node.normalize(); |
| 1005 | const walker = createNodeIterator.call(node.ownerDocument || node, node, |
| 1006 | // eslint-disable-next-line no-bitwise |
| 1007 | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null); |
| 1008 | let currentNode = walker.nextNode(); |
| 1009 | while (currentNode) { |
| 1010 | let data = currentNode.data; |
| 1011 | arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { |
| 1012 | data = stringReplace(data, expr, ' '); |
| 1013 | }); |
| 1014 | currentNode.data = data; |
| 1015 | currentNode = walker.nextNode(); |
| 1016 | } |
| 1017 | }; |
| 1018 | /** |
| 1019 | * _isClobbered |
| 1020 | * |
| 1021 | * @param element element to check for clobbering attacks |
| 1022 | * @return true if clobbered, false if safe |
| 1023 | */ |
| 1024 | const _isClobbered = function _isClobbered(element) { |
| 1025 | return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); |
| 1026 | }; |
| 1027 | /** |
| 1028 | * Checks whether the given object is a DOM node, including nodes that |
| 1029 | * originate from a different window/realm (e.g. an iframe's |
| 1030 | * contentDocument). The previous `value instanceof Node` check was |
| 1031 | * realm-bound: nodes from a different window failed it, causing |
| 1032 | * sanitize() to silently stringify them and reset IN_PLACE to false, |
| 1033 | * returning the original node unsanitized. See GHSA-4w3q-35jp-p934. |
| 1034 | * |
| 1035 | * Implementation: call the cached `nodeType` getter from Node.prototype |
| 1036 | * directly on the value. This bypasses any clobbered instance property |
| 1037 | * (e.g. a child element named "nodeType") and works across realms |
| 1038 | * because the WebIDL `nodeType` getter reads an internal slot that |
| 1039 | * every real Node has, regardless of which window minted it. |
| 1040 | * |
| 1041 | * @param value object to check whether it's a DOM node |
| 1042 | * @return true if value is a DOM node from any realm |
| 1043 | */ |
| 1044 | const _isNode = function _isNode(value) { |
| 1045 | if (!getNodeType || typeof value !== 'object' || value === null) { |
| 1046 | return false; |
| 1047 | } |
| 1048 | try { |
| 1049 | return typeof getNodeType(value) === 'number'; |
| 1050 | } catch (_) { |
| 1051 | return false; |
| 1052 | } |
| 1053 | }; |
| 1054 | function _executeHooks(hooks, currentNode, data) { |
| 1055 | arrayForEach(hooks, hook => { |
| 1056 | hook.call(DOMPurify, currentNode, data, CONFIG); |
| 1057 | }); |
| 1058 | } |
| 1059 | /** |
| 1060 | * _sanitizeElements |
| 1061 | * |
| 1062 | * @protect nodeName |
| 1063 | * @protect textContent |
| 1064 | * @protect removeChild |
| 1065 | * @param currentNode to check for permission to exist |
| 1066 | * @return true if node was killed, false if left alive |
| 1067 | */ |
| 1068 | const _sanitizeElements = function _sanitizeElements(currentNode) { |
| 1069 | let content = null; |
| 1070 | /* Execute a hook if present */ |
| 1071 | _executeHooks(hooks.beforeSanitizeElements, currentNode, null); |
| 1072 | /* Check if element is clobbered or can clobber */ |
| 1073 | if (_isClobbered(currentNode)) { |
| 1074 | _forceRemove(currentNode); |
| 1075 | return true; |
| 1076 | } |
| 1077 | /* Now let's check the element's type and name */ |
| 1078 | const tagName = transformCaseFunc(currentNode.nodeName); |
| 1079 | /* Execute a hook if present */ |
| 1080 | _executeHooks(hooks.uponSanitizeElement, currentNode, { |
| 1081 | tagName, |
| 1082 | allowedTags: ALLOWED_TAGS |
| 1083 | }); |
| 1084 | /* Detect mXSS attempts abusing namespace confusion */ |
| 1085 | if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) { |
| 1086 | _forceRemove(currentNode); |
| 1087 | return true; |
| 1088 | } |
| 1089 | /* Remove risky CSS construction leading to mXSS */ |
| 1090 | if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) { |
| 1091 | _forceRemove(currentNode); |
| 1092 | return true; |
| 1093 | } |
| 1094 | /* Remove any occurrence of processing instructions */ |
| 1095 | if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { |
| 1096 | _forceRemove(currentNode); |
| 1097 | return true; |
| 1098 | } |
| 1099 | /* Remove any kind of possibly harmful comments */ |
| 1100 | if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { |
| 1101 | _forceRemove(currentNode); |
| 1102 | return true; |
| 1103 | } |
| 1104 | /* Remove element if anything forbids its presence */ |
| 1105 | if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) { |
| 1106 | /* Check if we have a custom element to handle */ |
| 1107 | if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { |
| 1108 | if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { |
| 1109 | return false; |
| 1110 | } |
| 1111 | if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { |
| 1112 | return false; |
| 1113 | } |
| 1114 | } |
| 1115 | /* Keep content except for bad-listed elements */ |
| 1116 | if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { |
| 1117 | const parentNode = getParentNode(currentNode) || currentNode.parentNode; |
| 1118 | const childNodes = getChildNodes(currentNode) || currentNode.childNodes; |
| 1119 | if (childNodes && parentNode) { |
| 1120 | const childCount = childNodes.length; |
| 1121 | for (let i = childCount - 1; i >= 0; --i) { |
| 1122 | const childClone = cloneNode(childNodes[i], true); |
| 1123 | parentNode.insertBefore(childClone, getNextSibling(currentNode)); |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | _forceRemove(currentNode); |
| 1128 | return true; |
| 1129 | } |
| 1130 | /* Check whether element has a valid namespace */ |
| 1131 | if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { |
| 1132 | _forceRemove(currentNode); |
| 1133 | return true; |
| 1134 | } |
| 1135 | /* Make sure that older browsers don't get fallback-tag mXSS */ |
| 1136 | if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { |
| 1137 | _forceRemove(currentNode); |
| 1138 | return true; |
| 1139 | } |
| 1140 | /* Sanitize element content to be template-safe */ |
| 1141 | if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { |
| 1142 | /* Get the element's text content */ |
| 1143 | content = currentNode.textContent; |
| 1144 | arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { |
| 1145 | content = stringReplace(content, expr, ' '); |
| 1146 | }); |
| 1147 | if (currentNode.textContent !== content) { |
| 1148 | arrayPush(DOMPurify.removed, { |
| 1149 | element: currentNode.cloneNode() |
| 1150 | }); |
| 1151 | currentNode.textContent = content; |
| 1152 | } |
| 1153 | } |
| 1154 | /* Execute a hook if present */ |
| 1155 | _executeHooks(hooks.afterSanitizeElements, currentNode, null); |
| 1156 | return false; |
| 1157 | }; |
| 1158 | /** |
| 1159 | * _isValidAttribute |
| 1160 | * |
| 1161 | * @param lcTag Lowercase tag name of containing element. |
| 1162 | * @param lcName Lowercase attribute name. |
| 1163 | * @param value Attribute value. |
| 1164 | * @return Returns true if `value` is valid, otherwise false. |
| 1165 | */ |
| 1166 | // eslint-disable-next-line complexity |
| 1167 | const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { |
| 1168 | /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */ |
| 1169 | if (FORBID_ATTR[lcName]) { |
| 1170 | return false; |
| 1171 | } |
| 1172 | /* Make sure attribute cannot clobber */ |
| 1173 | if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { |
| 1174 | return false; |
| 1175 | } |
| 1176 | const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag); |
| 1177 | /* Allow valid data-* attributes: At least one character after "-" |
| 1178 | (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) |
| 1179 | XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) |
| 1180 | We don't need to check the value; it's always URI safe. */ |
| 1181 | if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) { |
| 1182 | if ( |
| 1183 | // First condition does a very basic check if a) it's basically a valid custom element tagname AND |
| 1184 | // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck |
| 1185 | // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck |
| 1186 | _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) || |
| 1187 | // Alternative, second condition checks if it's an `is`-attribute, AND |
| 1188 | // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck |
| 1189 | lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { |
| 1190 | return false; |
| 1191 | } |
| 1192 | /* Check value is safe. First, is attr inert? If so, is safe */ |
| 1193 | } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) { |
| 1194 | return false; |
| 1195 | } else ; |
| 1196 | return true; |
| 1197 | }; |
| 1198 | /* Names the HTML spec reserves from valid-custom-element-name; these must |
| 1199 | * never be treated as basic custom elements even when a permissive |
| 1200 | * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */ |
| 1201 | const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']); |
| 1202 | /** |
| 1203 | * _isBasicCustomElement |
| 1204 | * checks if at least one dash is included in tagName, and it's not the first char |
| 1205 | * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name |
| 1206 | * |
| 1207 | * @param tagName name of the tag of the node to sanitize |
| 1208 | * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. |
| 1209 | */ |
| 1210 | const _isBasicCustomElement = function _isBasicCustomElement(tagName) { |
| 1211 | return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName); |
| 1212 | }; |
| 1213 | /** |
| 1214 | * _sanitizeAttributes |
| 1215 | * |
| 1216 | * @protect attributes |
| 1217 | * @protect nodeName |
| 1218 | * @protect removeAttribute |
| 1219 | * @protect setAttribute |
| 1220 | * |
| 1221 | * @param currentNode to sanitize |
| 1222 | */ |
| 1223 | const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { |
| 1224 | /* Execute a hook if present */ |
| 1225 | _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); |
| 1226 | const attributes = currentNode.attributes; |
| 1227 | /* Check if we have attributes; if not we might have a text node */ |
| 1228 | if (!attributes || _isClobbered(currentNode)) { |
| 1229 | return; |
| 1230 | } |
| 1231 | const hookEvent = { |
| 1232 | attrName: '', |
| 1233 | attrValue: '', |
| 1234 | keepAttr: true, |
| 1235 | allowedAttributes: ALLOWED_ATTR, |
| 1236 | forceKeepAttr: undefined |
| 1237 | }; |
| 1238 | let l = attributes.length; |
| 1239 | /* Go backwards over all attributes; safely remove bad ones */ |
| 1240 | while (l--) { |
| 1241 | const attr = attributes[l]; |
| 1242 | const name = attr.name, |
| 1243 | namespaceURI = attr.namespaceURI, |
| 1244 | attrValue = attr.value; |
| 1245 | const lcName = transformCaseFunc(name); |
| 1246 | const initValue = attrValue; |
| 1247 | let value = name === 'value' ? initValue : stringTrim(initValue); |
| 1248 | /* Execute a hook if present */ |
| 1249 | hookEvent.attrName = lcName; |
| 1250 | hookEvent.attrValue = value; |
| 1251 | hookEvent.keepAttr = true; |
| 1252 | hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set |
| 1253 | _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); |
| 1254 | value = hookEvent.attrValue; |
| 1255 | /* Full DOM Clobbering protection via namespace isolation, |
| 1256 | * Prefix id and name attributes with `user-content-` |
| 1257 | */ |
| 1258 | if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) { |
| 1259 | // Remove the attribute with this value |
| 1260 | _removeAttribute(name, currentNode); |
| 1261 | // Prefix the value and later re-create the attribute with the sanitized value |
| 1262 | value = SANITIZE_NAMED_PROPS_PREFIX + value; |
| 1263 | } |
| 1264 | // Else: already prefixed, leave the attribute alone — the prefix is |
| 1265 | // itself the clobbering protection, and re-applying it is incorrect. |
| 1266 | /* Work around a security issue with comments inside attributes */ |
| 1267 | if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) { |
| 1268 | _removeAttribute(name, currentNode); |
| 1269 | continue; |
| 1270 | } |
| 1271 | /* Make sure we cannot easily use animated hrefs, even if animations are allowed */ |
| 1272 | if (lcName === 'attributename' && stringMatch(value, 'href')) { |
| 1273 | _removeAttribute(name, currentNode); |
| 1274 | continue; |
| 1275 | } |
| 1276 | /* Did the hooks approve of the attribute? */ |
| 1277 | if (hookEvent.forceKeepAttr) { |
| 1278 | continue; |
| 1279 | } |
| 1280 | /* Did the hooks approve of the attribute? */ |
| 1281 | if (!hookEvent.keepAttr) { |
| 1282 | _removeAttribute(name, currentNode); |
| 1283 | continue; |
| 1284 | } |
| 1285 | /* Work around a security issue in jQuery 3.0 */ |
| 1286 | if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { |
| 1287 | _removeAttribute(name, currentNode); |
| 1288 | continue; |
| 1289 | } |
| 1290 | /* Sanitize attribute content to be template-safe */ |
| 1291 | if (SAFE_FOR_TEMPLATES) { |
| 1292 | arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { |
| 1293 | value = stringReplace(value, expr, ' '); |
| 1294 | }); |
| 1295 | } |
| 1296 | /* Is `value` valid for this attribute? */ |
| 1297 | const lcTag = transformCaseFunc(currentNode.nodeName); |
| 1298 | if (!_isValidAttribute(lcTag, lcName, value)) { |
| 1299 | _removeAttribute(name, currentNode); |
| 1300 | continue; |
| 1301 | } |
| 1302 | /* Handle attributes that require Trusted Types */ |
| 1303 | if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { |
| 1304 | if (namespaceURI) ; else { |
| 1305 | switch (trustedTypes.getAttributeType(lcTag, lcName)) { |
| 1306 | case 'TrustedHTML': |
| 1307 | { |
| 1308 | value = trustedTypesPolicy.createHTML(value); |
| 1309 | break; |
| 1310 | } |
| 1311 | case 'TrustedScriptURL': |
| 1312 | { |
| 1313 | value = trustedTypesPolicy.createScriptURL(value); |
| 1314 | break; |
| 1315 | } |
| 1316 | } |
| 1317 | } |
| 1318 | } |
| 1319 | /* Handle invalid data-* attribute set by try-catching it */ |
| 1320 | if (value !== initValue) { |
| 1321 | try { |
| 1322 | if (namespaceURI) { |
| 1323 | currentNode.setAttributeNS(namespaceURI, name, value); |
| 1324 | } else { |
| 1325 | /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ |
| 1326 | currentNode.setAttribute(name, value); |
| 1327 | } |
| 1328 | if (_isClobbered(currentNode)) { |
| 1329 | _forceRemove(currentNode); |
| 1330 | } else { |
| 1331 | arrayPop(DOMPurify.removed); |
| 1332 | } |
| 1333 | } catch (_) { |
| 1334 | _removeAttribute(name, currentNode); |
| 1335 | } |
| 1336 | } |
| 1337 | } |
| 1338 | /* Execute a hook if present */ |
| 1339 | _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); |
| 1340 | }; |
| 1341 | /** |
| 1342 | * _sanitizeShadowDOM |
| 1343 | * |
| 1344 | * @param fragment to iterate over recursively |
| 1345 | */ |
| 1346 | const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) { |
| 1347 | let shadowNode = null; |
| 1348 | const shadowIterator = _createNodeIterator(fragment); |
| 1349 | /* Execute a hook if present */ |
| 1350 | _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); |
| 1351 | while (shadowNode = shadowIterator.nextNode()) { |
| 1352 | /* Execute a hook if present */ |
| 1353 | _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); |
| 1354 | /* Sanitize tags and elements */ |
| 1355 | _sanitizeElements(shadowNode); |
| 1356 | /* Check attributes next */ |
| 1357 | _sanitizeAttributes(shadowNode); |
| 1358 | /* Deep shadow DOM detected */ |
| 1359 | if (shadowNode.content instanceof DocumentFragment) { |
| 1360 | _sanitizeShadowDOM2(shadowNode.content); |
| 1361 | } |
| 1362 | } |
| 1363 | /* Execute a hook if present */ |
| 1364 | _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); |
| 1365 | }; |
| 1366 | /** |
| 1367 | * _sanitizeAttachedShadowRoots |
| 1368 | * |
| 1369 | * Walks `root` and feeds every attached shadow root we encounter into |
| 1370 | * the existing _sanitizeShadowDOM pipeline. The default node iterator |
| 1371 | * does not descend into shadow trees, so nodes inside an attached |
| 1372 | * shadow root would otherwise be skipped entirely. |
| 1373 | * |
| 1374 | * Two real input paths put attached shadow roots in front of us: |
| 1375 | * 1. IN_PLACE on a DOM node that already has shadow roots attached. |
| 1376 | * 2. DOM-node input where importNode(dirty, true) deep-clones the |
| 1377 | * shadow root because it was created with `clonable: true`. |
| 1378 | * |
| 1379 | * This pass runs once, up front, so the main iteration loop (and the |
| 1380 | * existing _sanitizeShadowDOM template-content recursion) stay |
| 1381 | * untouched — string-input paths are not affected. |
| 1382 | * |
| 1383 | * @param root the subtree root to walk for attached shadow roots |
| 1384 | */ |
| 1385 | const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) { |
| 1386 | if (root.nodeType === NODE_TYPE.element && root.shadowRoot instanceof DocumentFragment) { |
| 1387 | const sr = root.shadowRoot; |
| 1388 | // Recurse first so that nested shadow roots are reached even if |
| 1389 | // _sanitizeShadowDOM removes hosts at this level. |
| 1390 | _sanitizeAttachedShadowRoots2(sr); |
| 1391 | _sanitizeShadowDOM2(sr); |
| 1392 | } |
| 1393 | // Snapshot children before recursing. Sanitization of one subtree |
| 1394 | // (e.g. via an uponSanitizeShadowNode hook) may detach siblings, |
| 1395 | // and naive nextSibling traversal would silently skip the rest of |
| 1396 | // the list once a node is detached. |
| 1397 | const childNodes = root.childNodes; |
| 1398 | if (!childNodes) { |
| 1399 | return; |
| 1400 | } |
| 1401 | const snapshot = []; |
| 1402 | arrayForEach(childNodes, child => { |
| 1403 | arrayPush(snapshot, child); |
| 1404 | }); |
| 1405 | for (const child of snapshot) { |
| 1406 | _sanitizeAttachedShadowRoots2(child); |
| 1407 | } |
| 1408 | }; |
| 1409 | // eslint-disable-next-line complexity |
| 1410 | DOMPurify.sanitize = function (dirty) { |
| 1411 | let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; |
| 1412 | let body = null; |
| 1413 | let importedNode = null; |
| 1414 | let currentNode = null; |
| 1415 | let returnNode = null; |
| 1416 | /* Make sure we have a string to sanitize. |
| 1417 | DO NOT return early, as this will return the wrong type if |
| 1418 | the user has requested a DOM object rather than a string */ |
| 1419 | IS_EMPTY_INPUT = !dirty; |
| 1420 | if (IS_EMPTY_INPUT) { |
| 1421 | dirty = '<!-->'; |
| 1422 | } |
| 1423 | /* Stringify, in case dirty is an object */ |
| 1424 | if (typeof dirty !== 'string' && !_isNode(dirty)) { |
| 1425 | dirty = stringifyValue(dirty); |
| 1426 | if (typeof dirty !== 'string') { |
| 1427 | throw typeErrorCreate('dirty is not a string, aborting'); |
| 1428 | } |
| 1429 | } |
| 1430 | /* Return dirty HTML if DOMPurify cannot run */ |
| 1431 | if (!DOMPurify.isSupported) { |
| 1432 | return dirty; |
| 1433 | } |
| 1434 | /* Assign config vars */ |
| 1435 | if (!SET_CONFIG) { |
| 1436 | _parseConfig(cfg); |
| 1437 | } |
| 1438 | /* Clean up removed elements */ |
| 1439 | DOMPurify.removed = []; |
| 1440 | /* Check if dirty is correctly typed for IN_PLACE */ |
| 1441 | if (typeof dirty === 'string') { |
| 1442 | IN_PLACE = false; |
| 1443 | } |
| 1444 | if (IN_PLACE) { |
| 1445 | /* Do some early pre-sanitization to avoid unsafe root nodes */ |
| 1446 | const nn = dirty.nodeName; |
| 1447 | if (typeof nn === 'string') { |
| 1448 | const tagName = transformCaseFunc(nn); |
| 1449 | if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { |
| 1450 | throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); |
| 1451 | } |
| 1452 | } |
| 1453 | /* Sanitize attached shadow roots before the main iterator runs. |
| 1454 | The iterator does not descend into shadow trees. */ |
| 1455 | _sanitizeAttachedShadowRoots2(dirty); |
| 1456 | } else if (_isNode(dirty)) { |
| 1457 | /* If dirty is a DOM element, append to an empty document to avoid |
| 1458 | elements being stripped by the parser */ |
| 1459 | body = _initDocument('<!---->'); |
| 1460 | importedNode = body.ownerDocument.importNode(dirty, true); |
| 1461 | if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { |
| 1462 | /* Node is already a body, use as is */ |
| 1463 | body = importedNode; |
| 1464 | } else if (importedNode.nodeName === 'HTML') { |
| 1465 | body = importedNode; |
| 1466 | } else { |
| 1467 | // eslint-disable-next-line unicorn/prefer-dom-node-append |
| 1468 | body.appendChild(importedNode); |
| 1469 | } |
| 1470 | /* Clonable shadow roots are deep-cloned by importNode(); sanitize |
| 1471 | them before the main iterator runs, since the iterator does not |
| 1472 | descend into shadow trees. */ |
| 1473 | _sanitizeAttachedShadowRoots2(importedNode); |
| 1474 | } else { |
| 1475 | /* Exit directly if we have nothing to do */ |
| 1476 | if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && |
| 1477 | // eslint-disable-next-line unicorn/prefer-includes |
| 1478 | dirty.indexOf('<') === -1) { |
| 1479 | return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; |
| 1480 | } |
| 1481 | /* Initialize the document to work on */ |
| 1482 | body = _initDocument(dirty); |
| 1483 | /* Check we have a DOM node from the data */ |
| 1484 | if (!body) { |
| 1485 | return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; |
| 1486 | } |
| 1487 | } |
| 1488 | /* Remove first element node (ours) if FORCE_BODY is set */ |
| 1489 | if (body && FORCE_BODY) { |
| 1490 | _forceRemove(body.firstChild); |
| 1491 | } |
| 1492 | /* Get node iterator */ |
| 1493 | const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); |
| 1494 | /* Now start iterating over the created document */ |
| 1495 | while (currentNode = nodeIterator.nextNode()) { |
| 1496 | /* Sanitize tags and elements */ |
| 1497 | _sanitizeElements(currentNode); |
| 1498 | /* Check attributes next */ |
| 1499 | _sanitizeAttributes(currentNode); |
| 1500 | /* Shadow DOM detected, sanitize it */ |
| 1501 | if (currentNode.content instanceof DocumentFragment) { |
| 1502 | _sanitizeShadowDOM2(currentNode.content); |
| 1503 | } |
| 1504 | } |
| 1505 | /* If we sanitized `dirty` in-place, return it. */ |
| 1506 | if (IN_PLACE) { |
| 1507 | if (SAFE_FOR_TEMPLATES) { |
| 1508 | _scrubTemplateExpressions(dirty); |
| 1509 | } |
| 1510 | return dirty; |
| 1511 | } |
| 1512 | /* Return sanitized string or DOM */ |
| 1513 | if (RETURN_DOM) { |
| 1514 | if (SAFE_FOR_TEMPLATES) { |
| 1515 | _scrubTemplateExpressions(body); |
| 1516 | } |
| 1517 | if (RETURN_DOM_FRAGMENT) { |
| 1518 | returnNode = createDocumentFragment.call(body.ownerDocument); |
| 1519 | while (body.firstChild) { |
| 1520 | // eslint-disable-next-line unicorn/prefer-dom-node-append |
| 1521 | returnNode.appendChild(body.firstChild); |
| 1522 | } |
| 1523 | } else { |
| 1524 | returnNode = body; |
| 1525 | } |
| 1526 | if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { |
| 1527 | /* |
| 1528 | AdoptNode() is not used because internal state is not reset |
| 1529 | (e.g. the past names map of a HTMLFormElement), this is safe |
| 1530 | in theory but we would rather not risk another attack vector. |
| 1531 | The state that is cloned by importNode() is explicitly defined |
| 1532 | by the specs. |
| 1533 | */ |
| 1534 | returnNode = importNode.call(originalDocument, returnNode, true); |
| 1535 | } |
| 1536 | return returnNode; |
| 1537 | } |
| 1538 | let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; |
| 1539 | /* Serialize doctype if allowed */ |
| 1540 | if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { |
| 1541 | serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML; |
| 1542 | } |
| 1543 | /* Sanitize final string template-safe */ |
| 1544 | if (SAFE_FOR_TEMPLATES) { |
| 1545 | arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { |
| 1546 | serializedHTML = stringReplace(serializedHTML, expr, ' '); |
| 1547 | }); |
| 1548 | } |
| 1549 | return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; |
| 1550 | }; |
| 1551 | DOMPurify.setConfig = function () { |
| 1552 | let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; |
| 1553 | _parseConfig(cfg); |
| 1554 | SET_CONFIG = true; |
| 1555 | }; |
| 1556 | DOMPurify.clearConfig = function () { |
| 1557 | CONFIG = null; |
| 1558 | SET_CONFIG = false; |
| 1559 | }; |
| 1560 | DOMPurify.isValidAttribute = function (tag, attr, value) { |
| 1561 | /* Initialize shared config vars if necessary. */ |
| 1562 | if (!CONFIG) { |
| 1563 | _parseConfig({}); |
| 1564 | } |
| 1565 | const lcTag = transformCaseFunc(tag); |
| 1566 | const lcName = transformCaseFunc(attr); |
| 1567 | return _isValidAttribute(lcTag, lcName, value); |
| 1568 | }; |
| 1569 | DOMPurify.addHook = function (entryPoint, hookFunction) { |
| 1570 | if (typeof hookFunction !== 'function') { |
| 1571 | return; |
| 1572 | } |
| 1573 | arrayPush(hooks[entryPoint], hookFunction); |
| 1574 | }; |
| 1575 | DOMPurify.removeHook = function (entryPoint, hookFunction) { |
| 1576 | if (hookFunction !== undefined) { |
| 1577 | const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); |
| 1578 | return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; |
| 1579 | } |
| 1580 | return arrayPop(hooks[entryPoint]); |
| 1581 | }; |
| 1582 | DOMPurify.removeHooks = function (entryPoint) { |
| 1583 | hooks[entryPoint] = []; |
| 1584 | }; |
| 1585 | DOMPurify.removeAllHooks = function () { |
| 1586 | hooks = _createHooksMap(); |
| 1587 | }; |
| 1588 | return DOMPurify; |
| 1589 | } |
| 1590 | var purify = createDOMPurify(); |
| 1591 | |
| 1592 | return purify; |
| 1593 | |
| 1594 | })); |
| 1595 | //# sourceMappingURL=purify.js.map |