dompurify.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. /*! @license DOMPurify 2.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.1/LICENSE */
  2. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  3. var hasOwnProperty = Object.hasOwnProperty,
  4. setPrototypeOf = Object.setPrototypeOf,
  5. isFrozen = Object.isFrozen,
  6. getPrototypeOf = Object.getPrototypeOf,
  7. getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  8. var freeze = Object.freeze,
  9. seal = Object.seal,
  10. create = Object.create; // eslint-disable-line import/no-mutable-exports
  11. var _ref = typeof Reflect !== 'undefined' && Reflect,
  12. apply = _ref.apply,
  13. construct = _ref.construct;
  14. if (!apply) {
  15. apply = function apply(fun, thisValue, args) {
  16. return fun.apply(thisValue, args);
  17. };
  18. }
  19. if (!freeze) {
  20. freeze = function freeze(x) {
  21. return x;
  22. };
  23. }
  24. if (!seal) {
  25. seal = function seal(x) {
  26. return x;
  27. };
  28. }
  29. if (!construct) {
  30. construct = function construct(Func, args) {
  31. return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
  32. };
  33. }
  34. var arrayForEach = unapply(Array.prototype.forEach);
  35. var arrayPop = unapply(Array.prototype.pop);
  36. var arrayPush = unapply(Array.prototype.push);
  37. var stringToLowerCase = unapply(String.prototype.toLowerCase);
  38. var stringMatch = unapply(String.prototype.match);
  39. var stringReplace = unapply(String.prototype.replace);
  40. var stringIndexOf = unapply(String.prototype.indexOf);
  41. var stringTrim = unapply(String.prototype.trim);
  42. var regExpTest = unapply(RegExp.prototype.test);
  43. var typeErrorCreate = unconstruct(TypeError);
  44. function unapply(func) {
  45. return function (thisArg) {
  46. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  47. args[_key - 1] = arguments[_key];
  48. }
  49. return apply(func, thisArg, args);
  50. };
  51. }
  52. function unconstruct(func) {
  53. return function () {
  54. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  55. args[_key2] = arguments[_key2];
  56. }
  57. return construct(func, args);
  58. };
  59. }
  60. /* Add properties to a lookup table */
  61. function addToSet(set, array) {
  62. if (setPrototypeOf) {
  63. // Make 'in' and truthy checks like Boolean(set.constructor)
  64. // independent of any properties defined on Object.prototype.
  65. // Prevent prototype setters from intercepting set as a this value.
  66. setPrototypeOf(set, null);
  67. }
  68. var l = array.length;
  69. while (l--) {
  70. var element = array[l];
  71. if (typeof element === 'string') {
  72. var lcElement = stringToLowerCase(element);
  73. if (lcElement !== element) {
  74. // Config presets (e.g. tags.js, attrs.js) are immutable.
  75. if (!isFrozen(array)) {
  76. array[l] = lcElement;
  77. }
  78. element = lcElement;
  79. }
  80. }
  81. set[element] = true;
  82. }
  83. return set;
  84. }
  85. /* Shallow clone an object */
  86. function clone(object) {
  87. var newObject = create(null);
  88. var property = void 0;
  89. for (property in object) {
  90. if (apply(hasOwnProperty, object, [property])) {
  91. newObject[property] = object[property];
  92. }
  93. }
  94. return newObject;
  95. }
  96. /* IE10 doesn't support __lookupGetter__ so lets'
  97. * simulate it. It also automatically checks
  98. * if the prop is function or getter and behaves
  99. * accordingly. */
  100. function lookupGetter(object, prop) {
  101. while (object !== null) {
  102. var desc = getOwnPropertyDescriptor(object, prop);
  103. if (desc) {
  104. if (desc.get) {
  105. return unapply(desc.get);
  106. }
  107. if (typeof desc.value === 'function') {
  108. return unapply(desc.value);
  109. }
  110. }
  111. object = getPrototypeOf(object);
  112. }
  113. function fallbackValue(element) {
  114. console.warn('fallback value for', element);
  115. return null;
  116. }
  117. return fallbackValue;
  118. }
  119. var html = 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', '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']);
  120. // SVG
  121. var svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
  122. var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
  123. // List of SVG elements that are disallowed by default.
  124. // We still need to know them so that we can do namespace
  125. // checks properly in case one wants to add them to
  126. // allow-list.
  127. var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'feimage', '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']);
  128. var mathMl = 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']);
  129. // Similarly to SVG, we want to know all MathML elements,
  130. // even those that we disallow by default.
  131. var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
  132. var text = freeze(['#text']);
  133. var html$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
  134. var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', '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', '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', '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', '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', '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', 'targetx', 'targety', 'transform', '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']);
  135. var mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', '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']);
  136. var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
  137. // eslint-disable-next-line unicorn/better-regex
  138. var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
  139. var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
  140. var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
  141. var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
  142. 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
  143. );
  144. var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  145. var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
  146. );
  147. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  148. function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  149. var getGlobal = function getGlobal() {
  150. return typeof window === 'undefined' ? null : window;
  151. };
  152. /**
  153. * Creates a no-op policy for internal use only.
  154. * Don't export this function outside this module!
  155. * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
  156. * @param {Document} document The document object (to determine policy name suffix)
  157. * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
  158. * are not supported).
  159. */
  160. var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  161. if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  162. return null;
  163. }
  164. // Allow the callers to control the unique policy name
  165. // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
  166. // Policy creation with duplicate names throws in Trusted Types.
  167. var suffix = null;
  168. var ATTR_NAME = 'data-tt-policy-suffix';
  169. if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
  170. suffix = document.currentScript.getAttribute(ATTR_NAME);
  171. }
  172. var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  173. try {
  174. return trustedTypes.createPolicy(policyName, {
  175. createHTML: function createHTML(html$$1) {
  176. return html$$1;
  177. }
  178. });
  179. } catch (_) {
  180. // Policy creation failed (most likely another DOMPurify script has
  181. // already run). Skip creating the policy, as this will only cause errors
  182. // if TT are enforced.
  183. console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  184. return null;
  185. }
  186. };
  187. function createDOMPurify() {
  188. var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  189. var DOMPurify = function DOMPurify(root) {
  190. return createDOMPurify(root);
  191. };
  192. /**
  193. * Version label, exposed for easier checks
  194. * if DOMPurify is up to date or not
  195. */
  196. DOMPurify.version = '2.3.1';
  197. /**
  198. * Array of elements that DOMPurify removed during sanitation.
  199. * Empty if nothing was removed.
  200. */
  201. DOMPurify.removed = [];
  202. if (!window || !window.document || window.document.nodeType !== 9) {
  203. // Not running in a browser, provide a factory function
  204. // so that you can pass your own Window
  205. DOMPurify.isSupported = false;
  206. return DOMPurify;
  207. }
  208. var originalDocument = window.document;
  209. var document = window.document;
  210. var DocumentFragment = window.DocumentFragment,
  211. HTMLTemplateElement = window.HTMLTemplateElement,
  212. Node = window.Node,
  213. Element = window.Element,
  214. NodeFilter = window.NodeFilter,
  215. _window$NamedNodeMap = window.NamedNodeMap,
  216. NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
  217. Text = window.Text,
  218. Comment = window.Comment,
  219. DOMParser = window.DOMParser,
  220. trustedTypes = window.trustedTypes;
  221. var ElementPrototype = Element.prototype;
  222. var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  223. var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  224. var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  225. var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  226. // As per issue #47, the web-components registry is inherited by a
  227. // new document created via createHTMLDocument. As per the spec
  228. // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
  229. // a new empty registry is used when creating a template contents owner
  230. // document, so we use that as our parent document to ensure nothing
  231. // is inherited.
  232. if (typeof HTMLTemplateElement === 'function') {
  233. var template = document.createElement('template');
  234. if (template.content && template.content.ownerDocument) {
  235. document = template.content.ownerDocument;
  236. }
  237. }
  238. var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  239. var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : '';
  240. var _document = document,
  241. implementation = _document.implementation,
  242. createNodeIterator = _document.createNodeIterator,
  243. createDocumentFragment = _document.createDocumentFragment,
  244. getElementsByTagName = _document.getElementsByTagName;
  245. var importNode = originalDocument.importNode;
  246. var documentMode = {};
  247. try {
  248. documentMode = clone(document).documentMode ? document.documentMode : {};
  249. } catch (_) {}
  250. var hooks = {};
  251. /**
  252. * Expose whether this browser supports running the full DOMPurify.
  253. */
  254. DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  255. var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,
  256. ERB_EXPR$$1 = ERB_EXPR,
  257. DATA_ATTR$$1 = DATA_ATTR,
  258. ARIA_ATTR$$1 = ARIA_ATTR,
  259. IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,
  260. ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
  261. var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
  262. /**
  263. * We consider the elements and attributes below to be safe. Ideally
  264. * don't add any new ones but feel free to remove unwanted ones.
  265. */
  266. /* allowed element names */
  267. var ALLOWED_TAGS = null;
  268. var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));
  269. /* Allowed attribute names */
  270. var ALLOWED_ATTR = null;
  271. var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));
  272. /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
  273. var FORBID_TAGS = null;
  274. /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
  275. var FORBID_ATTR = null;
  276. /* Decide if ARIA attributes are okay */
  277. var ALLOW_ARIA_ATTR = true;
  278. /* Decide if custom data attributes are okay */
  279. var ALLOW_DATA_ATTR = true;
  280. /* Decide if unknown protocols are okay */
  281. var ALLOW_UNKNOWN_PROTOCOLS = false;
  282. /* Output should be safe for common template engines.
  283. * This means, DOMPurify removes data attributes, mustaches and ERB
  284. */
  285. var SAFE_FOR_TEMPLATES = false;
  286. /* Decide if document with <html>... should be returned */
  287. var WHOLE_DOCUMENT = false;
  288. /* Track whether config is already set on this instance of DOMPurify. */
  289. var SET_CONFIG = false;
  290. /* Decide if all elements (e.g. style, script) must be children of
  291. * document.body. By default, browsers might move them to document.head */
  292. var FORCE_BODY = false;
  293. /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
  294. * string (or a TrustedHTML object if Trusted Types are supported).
  295. * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
  296. */
  297. var RETURN_DOM = false;
  298. /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
  299. * string (or a TrustedHTML object if Trusted Types are supported) */
  300. var RETURN_DOM_FRAGMENT = false;
  301. /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM
  302. * `Node` is imported into the current `Document`. If this flag is not enabled the
  303. * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by
  304. * DOMPurify.
  305. *
  306. * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false`
  307. * might cause XSS from attacks hidden in closed shadowroots in case the browser
  308. * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/
  309. */
  310. var RETURN_DOM_IMPORT = true;
  311. /* Try to return a Trusted Type object instead of a string, return a string in
  312. * case Trusted Types are not supported */
  313. var RETURN_TRUSTED_TYPE = false;
  314. /* Output should be free from DOM clobbering attacks? */
  315. var SANITIZE_DOM = true;
  316. /* Keep element content when removing element? */
  317. var KEEP_CONTENT = true;
  318. /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
  319. * of importing it into a new Document and returning a sanitized copy */
  320. var IN_PLACE = false;
  321. /* Allow usage of profiles like html, svg and mathMl */
  322. var USE_PROFILES = {};
  323. /* Tags to ignore content of when KEEP_CONTENT is true */
  324. var FORBID_CONTENTS = null;
  325. var 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']);
  326. /* Tags that are safe for data: URIs */
  327. var DATA_URI_TAGS = null;
  328. var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
  329. /* Attributes safe for values like "javascript:" */
  330. var URI_SAFE_ATTRIBUTES = null;
  331. var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
  332. var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  333. var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  334. var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  335. /* Document namespace */
  336. var NAMESPACE = HTML_NAMESPACE;
  337. var IS_EMPTY_INPUT = false;
  338. /* Keep a reference to config to pass to hooks */
  339. var CONFIG = null;
  340. /* Ideally, do not touch anything below this line */
  341. /* ______________________________________________ */
  342. var formElement = document.createElement('form');
  343. /**
  344. * _parseConfig
  345. *
  346. * @param {Object} cfg optional config literal
  347. */
  348. // eslint-disable-next-line complexity
  349. var _parseConfig = function _parseConfig(cfg) {
  350. if (CONFIG && CONFIG === cfg) {
  351. return;
  352. }
  353. /* Shield configuration object from tampering */
  354. if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
  355. cfg = {};
  356. }
  357. /* Shield configuration object from prototype pollution */
  358. cfg = clone(cfg);
  359. /* Set configuration parameters */
  360. ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
  361. ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
  362. URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
  363. DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
  364. FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
  365. FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
  366. FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
  367. USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
  368. ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
  369. ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
  370. ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
  371. SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
  372. WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
  373. RETURN_DOM = cfg.RETURN_DOM || false; // Default false
  374. RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
  375. RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false; // Default true
  376. RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
  377. FORCE_BODY = cfg.FORCE_BODY || false; // Default false
  378. SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
  379. KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
  380. IN_PLACE = cfg.IN_PLACE || false; // Default false
  381. IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
  382. NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
  383. if (SAFE_FOR_TEMPLATES) {
  384. ALLOW_DATA_ATTR = false;
  385. }
  386. if (RETURN_DOM_FRAGMENT) {
  387. RETURN_DOM = true;
  388. }
  389. /* Parse profile info */
  390. if (USE_PROFILES) {
  391. ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
  392. ALLOWED_ATTR = [];
  393. if (USE_PROFILES.html === true) {
  394. addToSet(ALLOWED_TAGS, html);
  395. addToSet(ALLOWED_ATTR, html$1);
  396. }
  397. if (USE_PROFILES.svg === true) {
  398. addToSet(ALLOWED_TAGS, svg);
  399. addToSet(ALLOWED_ATTR, svg$1);
  400. addToSet(ALLOWED_ATTR, xml);
  401. }
  402. if (USE_PROFILES.svgFilters === true) {
  403. addToSet(ALLOWED_TAGS, svgFilters);
  404. addToSet(ALLOWED_ATTR, svg$1);
  405. addToSet(ALLOWED_ATTR, xml);
  406. }
  407. if (USE_PROFILES.mathMl === true) {
  408. addToSet(ALLOWED_TAGS, mathMl);
  409. addToSet(ALLOWED_ATTR, mathMl$1);
  410. addToSet(ALLOWED_ATTR, xml);
  411. }
  412. }
  413. /* Merge configuration parameters */
  414. if (cfg.ADD_TAGS) {
  415. if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  416. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  417. }
  418. addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
  419. }
  420. if (cfg.ADD_ATTR) {
  421. if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  422. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  423. }
  424. addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
  425. }
  426. if (cfg.ADD_URI_SAFE_ATTR) {
  427. addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
  428. }
  429. if (cfg.FORBID_CONTENTS) {
  430. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  431. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  432. }
  433. addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
  434. }
  435. /* Add #text in case KEEP_CONTENT is set to true */
  436. if (KEEP_CONTENT) {
  437. ALLOWED_TAGS['#text'] = true;
  438. }
  439. /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
  440. if (WHOLE_DOCUMENT) {
  441. addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
  442. }
  443. /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
  444. if (ALLOWED_TAGS.table) {
  445. addToSet(ALLOWED_TAGS, ['tbody']);
  446. delete FORBID_TAGS.tbody;
  447. }
  448. // Prevent further manipulation of configuration.
  449. // Not available in IE8, Safari 5, etc.
  450. if (freeze) {
  451. freeze(cfg);
  452. }
  453. CONFIG = cfg;
  454. };
  455. var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
  456. var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']);
  457. /* Keep track of all possible SVG and MathML tags
  458. * so that we can perform the namespace checks
  459. * correctly. */
  460. var ALL_SVG_TAGS = addToSet({}, svg);
  461. addToSet(ALL_SVG_TAGS, svgFilters);
  462. addToSet(ALL_SVG_TAGS, svgDisallowed);
  463. var ALL_MATHML_TAGS = addToSet({}, mathMl);
  464. addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  465. /**
  466. *
  467. *
  468. * @param {Element} element a DOM element whose namespace is being checked
  469. * @returns {boolean} Return false if the element has a
  470. * namespace that a spec-compliant parser would never
  471. * return. Return true otherwise.
  472. */
  473. var _checkValidNamespace = function _checkValidNamespace(element) {
  474. var parent = getParentNode(element);
  475. // In JSDOM, if we're inside shadow DOM, then parentNode
  476. // can be null. We just simulate parent in this case.
  477. if (!parent || !parent.tagName) {
  478. parent = {
  479. namespaceURI: HTML_NAMESPACE,
  480. tagName: 'template'
  481. };
  482. }
  483. var tagName = stringToLowerCase(element.tagName);
  484. var parentTagName = stringToLowerCase(parent.tagName);
  485. if (element.namespaceURI === SVG_NAMESPACE) {
  486. // The only way to switch from HTML namespace to SVG
  487. // is via <svg>. If it happens via any other tag, then
  488. // it should be killed.
  489. if (parent.namespaceURI === HTML_NAMESPACE) {
  490. return tagName === 'svg';
  491. }
  492. // The only way to switch from MathML to SVG is via
  493. // svg if parent is either <annotation-xml> or MathML
  494. // text integration points.
  495. if (parent.namespaceURI === MATHML_NAMESPACE) {
  496. return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  497. }
  498. // We only allow elements that are defined in SVG
  499. // spec. All others are disallowed in SVG namespace.
  500. return Boolean(ALL_SVG_TAGS[tagName]);
  501. }
  502. if (element.namespaceURI === MATHML_NAMESPACE) {
  503. // The only way to switch from HTML namespace to MathML
  504. // is via <math>. If it happens via any other tag, then
  505. // it should be killed.
  506. if (parent.namespaceURI === HTML_NAMESPACE) {
  507. return tagName === 'math';
  508. }
  509. // The only way to switch from SVG to MathML is via
  510. // <math> and HTML integration points
  511. if (parent.namespaceURI === SVG_NAMESPACE) {
  512. return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  513. }
  514. // We only allow elements that are defined in MathML
  515. // spec. All others are disallowed in MathML namespace.
  516. return Boolean(ALL_MATHML_TAGS[tagName]);
  517. }
  518. if (element.namespaceURI === HTML_NAMESPACE) {
  519. // The only way to switch from SVG to HTML is via
  520. // HTML integration points, and from MathML to HTML
  521. // is via MathML text integration points
  522. if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  523. return false;
  524. }
  525. if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  526. return false;
  527. }
  528. // Certain elements are allowed in both SVG and HTML
  529. // namespace. We need to specify them explicitly
  530. // so that they don't get erronously deleted from
  531. // HTML namespace.
  532. var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
  533. // We disallow tags that are specific for MathML
  534. // or SVG and should never appear in HTML namespace
  535. return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);
  536. }
  537. // The code should never reach this place (this means
  538. // that the element somehow got namespace that is not
  539. // HTML, SVG or MathML). Return false just in case.
  540. return false;
  541. };
  542. /**
  543. * _forceRemove
  544. *
  545. * @param {Node} node a DOM node
  546. */
  547. var _forceRemove = function _forceRemove(node) {
  548. arrayPush(DOMPurify.removed, { element: node });
  549. try {
  550. // eslint-disable-next-line unicorn/prefer-dom-node-remove
  551. node.parentNode.removeChild(node);
  552. } catch (_) {
  553. try {
  554. node.outerHTML = emptyHTML;
  555. } catch (_) {
  556. node.remove();
  557. }
  558. }
  559. };
  560. /**
  561. * _removeAttribute
  562. *
  563. * @param {String} name an Attribute name
  564. * @param {Node} node a DOM node
  565. */
  566. var _removeAttribute = function _removeAttribute(name, node) {
  567. try {
  568. arrayPush(DOMPurify.removed, {
  569. attribute: node.getAttributeNode(name),
  570. from: node
  571. });
  572. } catch (_) {
  573. arrayPush(DOMPurify.removed, {
  574. attribute: null,
  575. from: node
  576. });
  577. }
  578. node.removeAttribute(name);
  579. // We void attribute values for unremovable "is"" attributes
  580. if (name === 'is' && !ALLOWED_ATTR[name]) {
  581. if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  582. try {
  583. _forceRemove(node);
  584. } catch (_) {}
  585. } else {
  586. try {
  587. node.setAttribute(name, '');
  588. } catch (_) {}
  589. }
  590. }
  591. };
  592. /**
  593. * _initDocument
  594. *
  595. * @param {String} dirty a string of dirty markup
  596. * @return {Document} a DOM, filled with the dirty markup
  597. */
  598. var _initDocument = function _initDocument(dirty) {
  599. /* Create a HTML document */
  600. var doc = void 0;
  601. var leadingWhitespace = void 0;
  602. if (FORCE_BODY) {
  603. dirty = '<remove></remove>' + dirty;
  604. } else {
  605. /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
  606. var matches = stringMatch(dirty, /^[\r\n\t ]+/);
  607. leadingWhitespace = matches && matches[0];
  608. }
  609. var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
  610. /*
  611. * Use the DOMParser API by default, fallback later if needs be
  612. * DOMParser not work for svg when has multiple root element.
  613. */
  614. if (NAMESPACE === HTML_NAMESPACE) {
  615. try {
  616. doc = new DOMParser().parseFromString(dirtyPayload, 'text/html');
  617. } catch (_) {}
  618. }
  619. /* Use createHTMLDocument in case DOMParser is not available */
  620. if (!doc || !doc.documentElement) {
  621. doc = implementation.createDocument(NAMESPACE, 'template', null);
  622. try {
  623. doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
  624. } catch (_) {
  625. // Syntax error if dirtyPayload is invalid xml
  626. }
  627. }
  628. var body = doc.body || doc.documentElement;
  629. if (dirty && leadingWhitespace) {
  630. body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  631. }
  632. /* Work on whole document or just its body */
  633. if (NAMESPACE === HTML_NAMESPACE) {
  634. return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  635. }
  636. return WHOLE_DOCUMENT ? doc.documentElement : body;
  637. };
  638. /**
  639. * _createIterator
  640. *
  641. * @param {Document} root document/fragment to create iterator for
  642. * @return {Iterator} iterator instance
  643. */
  644. var _createIterator = function _createIterator(root) {
  645. return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  646. };
  647. /**
  648. * _isClobbered
  649. *
  650. * @param {Node} elm element to check for clobbering attacks
  651. * @return {Boolean} true if clobbered, false if safe
  652. */
  653. var _isClobbered = function _isClobbered(elm) {
  654. if (elm instanceof Text || elm instanceof Comment) {
  655. return false;
  656. }
  657. if (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') {
  658. return true;
  659. }
  660. return false;
  661. };
  662. /**
  663. * _isNode
  664. *
  665. * @param {Node} obj object to check whether it's a DOM node
  666. * @return {Boolean} true is object is a DOM node
  667. */
  668. var _isNode = function _isNode(object) {
  669. return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  670. };
  671. /**
  672. * _executeHook
  673. * Execute user configurable hooks
  674. *
  675. * @param {String} entryPoint Name of the hook's entry point
  676. * @param {Node} currentNode node to work on with the hook
  677. * @param {Object} data additional hook parameters
  678. */
  679. var _executeHook = function _executeHook(entryPoint, currentNode, data) {
  680. if (!hooks[entryPoint]) {
  681. return;
  682. }
  683. arrayForEach(hooks[entryPoint], function (hook) {
  684. hook.call(DOMPurify, currentNode, data, CONFIG);
  685. });
  686. };
  687. /**
  688. * _sanitizeElements
  689. *
  690. * @protect nodeName
  691. * @protect textContent
  692. * @protect removeChild
  693. *
  694. * @param {Node} currentNode to check for permission to exist
  695. * @return {Boolean} true if node was killed, false if left alive
  696. */
  697. var _sanitizeElements = function _sanitizeElements(currentNode) {
  698. var content = void 0;
  699. /* Execute a hook if present */
  700. _executeHook('beforeSanitizeElements', currentNode, null);
  701. /* Check if element is clobbered or can clobber */
  702. if (_isClobbered(currentNode)) {
  703. _forceRemove(currentNode);
  704. return true;
  705. }
  706. /* Check if tagname contains Unicode */
  707. if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
  708. _forceRemove(currentNode);
  709. return true;
  710. }
  711. /* Now let's check the element's type and name */
  712. var tagName = stringToLowerCase(currentNode.nodeName);
  713. /* Execute a hook if present */
  714. _executeHook('uponSanitizeElement', currentNode, {
  715. tagName: tagName,
  716. allowedTags: ALLOWED_TAGS
  717. });
  718. /* Detect mXSS attempts abusing namespace confusion */
  719. if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
  720. _forceRemove(currentNode);
  721. return true;
  722. }
  723. /* Mitigate a problem with templates inside select */
  724. if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
  725. _forceRemove(currentNode);
  726. return true;
  727. }
  728. /* Remove element if anything forbids its presence */
  729. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  730. /* Keep content except for bad-listed elements */
  731. if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  732. var parentNode = getParentNode(currentNode) || currentNode.parentNode;
  733. var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  734. if (childNodes && parentNode) {
  735. var childCount = childNodes.length;
  736. for (var i = childCount - 1; i >= 0; --i) {
  737. parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
  738. }
  739. }
  740. }
  741. _forceRemove(currentNode);
  742. return true;
  743. }
  744. /* Check whether element has a valid namespace */
  745. if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
  746. _forceRemove(currentNode);
  747. return true;
  748. }
  749. if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
  750. _forceRemove(currentNode);
  751. return true;
  752. }
  753. /* Sanitize element content to be template-safe */
  754. if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
  755. /* Get the element's text content */
  756. content = currentNode.textContent;
  757. content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');
  758. content = stringReplace(content, ERB_EXPR$$1, ' ');
  759. if (currentNode.textContent !== content) {
  760. arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
  761. currentNode.textContent = content;
  762. }
  763. }
  764. /* Execute a hook if present */
  765. _executeHook('afterSanitizeElements', currentNode, null);
  766. return false;
  767. };
  768. /**
  769. * _isValidAttribute
  770. *
  771. * @param {string} lcTag Lowercase tag name of containing element.
  772. * @param {string} lcName Lowercase attribute name.
  773. * @param {string} value Attribute value.
  774. * @return {Boolean} Returns true if `value` is valid, otherwise false.
  775. */
  776. // eslint-disable-next-line complexity
  777. var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  778. /* Make sure attribute cannot clobber */
  779. if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  780. return false;
  781. }
  782. /* Allow valid data-* attributes: At least one character after "-"
  783. (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
  784. XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
  785. We don't need to check the value; it's always URI safe. */
  786. if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
  787. return false;
  788. /* Check value is safe. First, is attr inert? If so, is safe */
  789. } 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) ; else {
  790. return false;
  791. }
  792. return true;
  793. };
  794. /**
  795. * _sanitizeAttributes
  796. *
  797. * @protect attributes
  798. * @protect nodeName
  799. * @protect removeAttribute
  800. * @protect setAttribute
  801. *
  802. * @param {Node} currentNode to sanitize
  803. */
  804. var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  805. var attr = void 0;
  806. var value = void 0;
  807. var lcName = void 0;
  808. var l = void 0;
  809. /* Execute a hook if present */
  810. _executeHook('beforeSanitizeAttributes', currentNode, null);
  811. var attributes = currentNode.attributes;
  812. /* Check if we have attributes; if not we might have a text node */
  813. if (!attributes) {
  814. return;
  815. }
  816. var hookEvent = {
  817. attrName: '',
  818. attrValue: '',
  819. keepAttr: true,
  820. allowedAttributes: ALLOWED_ATTR
  821. };
  822. l = attributes.length;
  823. /* Go backwards over all attributes; safely remove bad ones */
  824. while (l--) {
  825. attr = attributes[l];
  826. var _attr = attr,
  827. name = _attr.name,
  828. namespaceURI = _attr.namespaceURI;
  829. value = stringTrim(attr.value);
  830. lcName = stringToLowerCase(name);
  831. /* Execute a hook if present */
  832. hookEvent.attrName = lcName;
  833. hookEvent.attrValue = value;
  834. hookEvent.keepAttr = true;
  835. hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
  836. _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
  837. value = hookEvent.attrValue;
  838. /* Did the hooks approve of the attribute? */
  839. if (hookEvent.forceKeepAttr) {
  840. continue;
  841. }
  842. /* Remove attribute */
  843. _removeAttribute(name, currentNode);
  844. /* Did the hooks approve of the attribute? */
  845. if (!hookEvent.keepAttr) {
  846. continue;
  847. }
  848. /* Work around a security issue in jQuery 3.0 */
  849. if (regExpTest(/\/>/i, value)) {
  850. _removeAttribute(name, currentNode);
  851. continue;
  852. }
  853. /* Sanitize attribute content to be template-safe */
  854. if (SAFE_FOR_TEMPLATES) {
  855. value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');
  856. value = stringReplace(value, ERB_EXPR$$1, ' ');
  857. }
  858. /* Is `value` valid for this attribute? */
  859. var lcTag = currentNode.nodeName.toLowerCase();
  860. if (!_isValidAttribute(lcTag, lcName, value)) {
  861. continue;
  862. }
  863. /* Handle invalid data-* attribute set by try-catching it */
  864. try {
  865. if (namespaceURI) {
  866. currentNode.setAttributeNS(namespaceURI, name, value);
  867. } else {
  868. /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
  869. currentNode.setAttribute(name, value);
  870. }
  871. arrayPop(DOMPurify.removed);
  872. } catch (_) {}
  873. }
  874. /* Execute a hook if present */
  875. _executeHook('afterSanitizeAttributes', currentNode, null);
  876. };
  877. /**
  878. * _sanitizeShadowDOM
  879. *
  880. * @param {DocumentFragment} fragment to iterate over recursively
  881. */
  882. var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
  883. var shadowNode = void 0;
  884. var shadowIterator = _createIterator(fragment);
  885. /* Execute a hook if present */
  886. _executeHook('beforeSanitizeShadowDOM', fragment, null);
  887. while (shadowNode = shadowIterator.nextNode()) {
  888. /* Execute a hook if present */
  889. _executeHook('uponSanitizeShadowNode', shadowNode, null);
  890. /* Sanitize tags and elements */
  891. if (_sanitizeElements(shadowNode)) {
  892. continue;
  893. }
  894. /* Deep shadow DOM detected */
  895. if (shadowNode.content instanceof DocumentFragment) {
  896. _sanitizeShadowDOM(shadowNode.content);
  897. }
  898. /* Check attributes, sanitize if necessary */
  899. _sanitizeAttributes(shadowNode);
  900. }
  901. /* Execute a hook if present */
  902. _executeHook('afterSanitizeShadowDOM', fragment, null);
  903. };
  904. /**
  905. * Sanitize
  906. * Public method providing core sanitation functionality
  907. *
  908. * @param {String|Node} dirty string or DOM node
  909. * @param {Object} configuration object
  910. */
  911. // eslint-disable-next-line complexity
  912. DOMPurify.sanitize = function (dirty, cfg) {
  913. var body = void 0;
  914. var importedNode = void 0;
  915. var currentNode = void 0;
  916. var oldNode = void 0;
  917. var returnNode = void 0;
  918. /* Make sure we have a string to sanitize.
  919. DO NOT return early, as this will return the wrong type if
  920. the user has requested a DOM object rather than a string */
  921. IS_EMPTY_INPUT = !dirty;
  922. if (IS_EMPTY_INPUT) {
  923. dirty = '<!-->';
  924. }
  925. /* Stringify, in case dirty is an object */
  926. if (typeof dirty !== 'string' && !_isNode(dirty)) {
  927. // eslint-disable-next-line no-negated-condition
  928. if (typeof dirty.toString !== 'function') {
  929. throw typeErrorCreate('toString is not a function');
  930. } else {
  931. dirty = dirty.toString();
  932. if (typeof dirty !== 'string') {
  933. throw typeErrorCreate('dirty is not a string, aborting');
  934. }
  935. }
  936. }
  937. /* Check we can run. Otherwise fall back or ignore */
  938. if (!DOMPurify.isSupported) {
  939. if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
  940. if (typeof dirty === 'string') {
  941. return window.toStaticHTML(dirty);
  942. }
  943. if (_isNode(dirty)) {
  944. return window.toStaticHTML(dirty.outerHTML);
  945. }
  946. }
  947. return dirty;
  948. }
  949. /* Assign config vars */
  950. if (!SET_CONFIG) {
  951. _parseConfig(cfg);
  952. }
  953. /* Clean up removed elements */
  954. DOMPurify.removed = [];
  955. /* Check if dirty is correctly typed for IN_PLACE */
  956. if (typeof dirty === 'string') {
  957. IN_PLACE = false;
  958. }
  959. if (IN_PLACE) ; else if (dirty instanceof Node) {
  960. /* If dirty is a DOM element, append to an empty document to avoid
  961. elements being stripped by the parser */
  962. body = _initDocument('<!---->');
  963. importedNode = body.ownerDocument.importNode(dirty, true);
  964. if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
  965. /* Node is already a body, use as is */
  966. body = importedNode;
  967. } else if (importedNode.nodeName === 'HTML') {
  968. body = importedNode;
  969. } else {
  970. // eslint-disable-next-line unicorn/prefer-dom-node-append
  971. body.appendChild(importedNode);
  972. }
  973. } else {
  974. /* Exit directly if we have nothing to do */
  975. if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
  976. // eslint-disable-next-line unicorn/prefer-includes
  977. dirty.indexOf('<') === -1) {
  978. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
  979. }
  980. /* Initialize the document to work on */
  981. body = _initDocument(dirty);
  982. /* Check we have a DOM node from the data */
  983. if (!body) {
  984. return RETURN_DOM ? null : emptyHTML;
  985. }
  986. }
  987. /* Remove first element node (ours) if FORCE_BODY is set */
  988. if (body && FORCE_BODY) {
  989. _forceRemove(body.firstChild);
  990. }
  991. /* Get node iterator */
  992. var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  993. /* Now start iterating over the created document */
  994. while (currentNode = nodeIterator.nextNode()) {
  995. /* Fix IE's strange behavior with manipulated textNodes #89 */
  996. if (currentNode.nodeType === 3 && currentNode === oldNode) {
  997. continue;
  998. }
  999. /* Sanitize tags and elements */
  1000. if (_sanitizeElements(currentNode)) {
  1001. continue;
  1002. }
  1003. /* Shadow DOM detected, sanitize it */
  1004. if (currentNode.content instanceof DocumentFragment) {
  1005. _sanitizeShadowDOM(currentNode.content);
  1006. }
  1007. /* Check attributes, sanitize if necessary */
  1008. _sanitizeAttributes(currentNode);
  1009. oldNode = currentNode;
  1010. }
  1011. oldNode = null;
  1012. /* If we sanitized `dirty` in-place, return it. */
  1013. if (IN_PLACE) {
  1014. return dirty;
  1015. }
  1016. /* Return sanitized string or DOM */
  1017. if (RETURN_DOM) {
  1018. if (RETURN_DOM_FRAGMENT) {
  1019. returnNode = createDocumentFragment.call(body.ownerDocument);
  1020. while (body.firstChild) {
  1021. // eslint-disable-next-line unicorn/prefer-dom-node-append
  1022. returnNode.appendChild(body.firstChild);
  1023. }
  1024. } else {
  1025. returnNode = body;
  1026. }
  1027. if (RETURN_DOM_IMPORT) {
  1028. /*
  1029. AdoptNode() is not used because internal state is not reset
  1030. (e.g. the past names map of a HTMLFormElement), this is safe
  1031. in theory but we would rather not risk another attack vector.
  1032. The state that is cloned by importNode() is explicitly defined
  1033. by the specs.
  1034. */
  1035. returnNode = importNode.call(originalDocument, returnNode, true);
  1036. }
  1037. return returnNode;
  1038. }
  1039. var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  1040. /* Sanitize final string template-safe */
  1041. if (SAFE_FOR_TEMPLATES) {
  1042. serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');
  1043. serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');
  1044. }
  1045. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  1046. };
  1047. /**
  1048. * Public method to set the configuration once
  1049. * setConfig
  1050. *
  1051. * @param {Object} cfg configuration object
  1052. */
  1053. DOMPurify.setConfig = function (cfg) {
  1054. _parseConfig(cfg);
  1055. SET_CONFIG = true;
  1056. };
  1057. /**
  1058. * Public method to remove the configuration
  1059. * clearConfig
  1060. *
  1061. */
  1062. DOMPurify.clearConfig = function () {
  1063. CONFIG = null;
  1064. SET_CONFIG = false;
  1065. };
  1066. /**
  1067. * Public method to check if an attribute value is valid.
  1068. * Uses last set config, if any. Otherwise, uses config defaults.
  1069. * isValidAttribute
  1070. *
  1071. * @param {string} tag Tag name of containing element.
  1072. * @param {string} attr Attribute name.
  1073. * @param {string} value Attribute value.
  1074. * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
  1075. */
  1076. DOMPurify.isValidAttribute = function (tag, attr, value) {
  1077. /* Initialize shared config vars if necessary. */
  1078. if (!CONFIG) {
  1079. _parseConfig({});
  1080. }
  1081. var lcTag = stringToLowerCase(tag);
  1082. var lcName = stringToLowerCase(attr);
  1083. return _isValidAttribute(lcTag, lcName, value);
  1084. };
  1085. /**
  1086. * AddHook
  1087. * Public method to add DOMPurify hooks
  1088. *
  1089. * @param {String} entryPoint entry point for the hook to add
  1090. * @param {Function} hookFunction function to execute
  1091. */
  1092. DOMPurify.addHook = function (entryPoint, hookFunction) {
  1093. if (typeof hookFunction !== 'function') {
  1094. return;
  1095. }
  1096. hooks[entryPoint] = hooks[entryPoint] || [];
  1097. arrayPush(hooks[entryPoint], hookFunction);
  1098. };
  1099. /**
  1100. * RemoveHook
  1101. * Public method to remove a DOMPurify hook at a given entryPoint
  1102. * (pops it from the stack of hooks if more are present)
  1103. *
  1104. * @param {String} entryPoint entry point for the hook to remove
  1105. */
  1106. DOMPurify.removeHook = function (entryPoint) {
  1107. if (hooks[entryPoint]) {
  1108. arrayPop(hooks[entryPoint]);
  1109. }
  1110. };
  1111. /**
  1112. * RemoveHooks
  1113. * Public method to remove all DOMPurify hooks at a given entryPoint
  1114. *
  1115. * @param {String} entryPoint entry point for the hooks to remove
  1116. */
  1117. DOMPurify.removeHooks = function (entryPoint) {
  1118. if (hooks[entryPoint]) {
  1119. hooks[entryPoint] = [];
  1120. }
  1121. };
  1122. /**
  1123. * RemoveAllHooks
  1124. * Public method to remove all DOMPurify hooks
  1125. *
  1126. */
  1127. DOMPurify.removeAllHooks = function () {
  1128. hooks = {};
  1129. };
  1130. return DOMPurify;
  1131. }
  1132. var purify = createDOMPurify();
  1133. // ESM-comment-begin
  1134. // define(function () { return purify; });
  1135. // ESM-comment-end
  1136. // ESM-uncomment-begin
  1137. export default purify;
  1138. export const version = purify.version;
  1139. export const isSupported = purify.isSupported;
  1140. export const sanitize = purify.sanitize;
  1141. export const setConfig = purify.setConfig;
  1142. export const clearConfig = purify.clearConfig;
  1143. export const isValidAttribute = purify.isValidAttribute;
  1144. export const addHook = purify.addHook;
  1145. export const removeHook = purify.removeHook;
  1146. export const removeHooks = purify.removeHooks;
  1147. export const removeAllHooks = purify.removeAllHooks;
  1148. // ESM-uncomment-end