purify.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. /*! @license DOMPurify 2.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/2.4.5/LICENSE */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  4. typeof define === 'function' && define.amd ? define(factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
  6. })(this, (function () { 'use strict';
  7. function _typeof(obj) {
  8. "@babel/helpers - typeof";
  9. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
  10. return typeof obj;
  11. } : function (obj) {
  12. return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  13. }, _typeof(obj);
  14. }
  15. function _setPrototypeOf(o, p) {
  16. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  17. o.__proto__ = p;
  18. return o;
  19. };
  20. return _setPrototypeOf(o, p);
  21. }
  22. function _isNativeReflectConstruct() {
  23. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  24. if (Reflect.construct.sham) return false;
  25. if (typeof Proxy === "function") return true;
  26. try {
  27. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  28. return true;
  29. } catch (e) {
  30. return false;
  31. }
  32. }
  33. function _construct(Parent, args, Class) {
  34. if (_isNativeReflectConstruct()) {
  35. _construct = Reflect.construct;
  36. } else {
  37. _construct = function _construct(Parent, args, Class) {
  38. var a = [null];
  39. a.push.apply(a, args);
  40. var Constructor = Function.bind.apply(Parent, a);
  41. var instance = new Constructor();
  42. if (Class) _setPrototypeOf(instance, Class.prototype);
  43. return instance;
  44. };
  45. }
  46. return _construct.apply(null, arguments);
  47. }
  48. function _toConsumableArray(arr) {
  49. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  50. }
  51. function _arrayWithoutHoles(arr) {
  52. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  53. }
  54. function _iterableToArray(iter) {
  55. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  56. }
  57. function _unsupportedIterableToArray(o, minLen) {
  58. if (!o) return;
  59. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  60. var n = Object.prototype.toString.call(o).slice(8, -1);
  61. if (n === "Object" && o.constructor) n = o.constructor.name;
  62. if (n === "Map" || n === "Set") return Array.from(o);
  63. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  64. }
  65. function _arrayLikeToArray(arr, len) {
  66. if (len == null || len > arr.length) len = arr.length;
  67. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  68. return arr2;
  69. }
  70. function _nonIterableSpread() {
  71. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  72. }
  73. var hasOwnProperty = Object.hasOwnProperty,
  74. setPrototypeOf = Object.setPrototypeOf,
  75. isFrozen = Object.isFrozen,
  76. getPrototypeOf = Object.getPrototypeOf,
  77. getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  78. var freeze = Object.freeze,
  79. seal = Object.seal,
  80. create = Object.create; // eslint-disable-line import/no-mutable-exports
  81. var _ref = typeof Reflect !== 'undefined' && Reflect,
  82. apply = _ref.apply,
  83. construct = _ref.construct;
  84. if (!apply) {
  85. apply = function apply(fun, thisValue, args) {
  86. return fun.apply(thisValue, args);
  87. };
  88. }
  89. if (!freeze) {
  90. freeze = function freeze(x) {
  91. return x;
  92. };
  93. }
  94. if (!seal) {
  95. seal = function seal(x) {
  96. return x;
  97. };
  98. }
  99. if (!construct) {
  100. construct = function construct(Func, args) {
  101. return _construct(Func, _toConsumableArray(args));
  102. };
  103. }
  104. var arrayForEach = unapply(Array.prototype.forEach);
  105. var arrayPop = unapply(Array.prototype.pop);
  106. var arrayPush = unapply(Array.prototype.push);
  107. var stringToLowerCase = unapply(String.prototype.toLowerCase);
  108. var stringToString = unapply(String.prototype.toString);
  109. var stringMatch = unapply(String.prototype.match);
  110. var stringReplace = unapply(String.prototype.replace);
  111. var stringIndexOf = unapply(String.prototype.indexOf);
  112. var stringTrim = unapply(String.prototype.trim);
  113. var regExpTest = unapply(RegExp.prototype.test);
  114. var typeErrorCreate = unconstruct(TypeError);
  115. function unapply(func) {
  116. return function (thisArg) {
  117. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  118. args[_key - 1] = arguments[_key];
  119. }
  120. return apply(func, thisArg, args);
  121. };
  122. }
  123. function unconstruct(func) {
  124. return function () {
  125. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  126. args[_key2] = arguments[_key2];
  127. }
  128. return construct(func, args);
  129. };
  130. }
  131. /* Add properties to a lookup table */
  132. function addToSet(set, array, transformCaseFunc) {
  133. transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
  134. if (setPrototypeOf) {
  135. // Make 'in' and truthy checks like Boolean(set.constructor)
  136. // independent of any properties defined on Object.prototype.
  137. // Prevent prototype setters from intercepting set as a this value.
  138. setPrototypeOf(set, null);
  139. }
  140. var l = array.length;
  141. while (l--) {
  142. var element = array[l];
  143. if (typeof element === 'string') {
  144. var lcElement = transformCaseFunc(element);
  145. if (lcElement !== element) {
  146. // Config presets (e.g. tags.js, attrs.js) are immutable.
  147. if (!isFrozen(array)) {
  148. array[l] = lcElement;
  149. }
  150. element = lcElement;
  151. }
  152. }
  153. set[element] = true;
  154. }
  155. return set;
  156. }
  157. /* Shallow clone an object */
  158. function clone(object) {
  159. var newObject = create(null);
  160. var property;
  161. for (property in object) {
  162. if (apply(hasOwnProperty, object, [property]) === true) {
  163. newObject[property] = object[property];
  164. }
  165. }
  166. return newObject;
  167. }
  168. /* IE10 doesn't support __lookupGetter__ so lets'
  169. * simulate it. It also automatically checks
  170. * if the prop is function or getter and behaves
  171. * accordingly. */
  172. function lookupGetter(object, prop) {
  173. while (object !== null) {
  174. var desc = getOwnPropertyDescriptor(object, prop);
  175. if (desc) {
  176. if (desc.get) {
  177. return unapply(desc.get);
  178. }
  179. if (typeof desc.value === 'function') {
  180. return unapply(desc.value);
  181. }
  182. }
  183. object = getPrototypeOf(object);
  184. }
  185. function fallbackValue(element) {
  186. console.warn('fallback value for', element);
  187. return null;
  188. }
  189. return fallbackValue;
  190. }
  191. var 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', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG
  192. var svg$1 = 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']);
  193. var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
  194. // We still need to know them so that we can do namespace
  195. // checks properly in case one wants to add them to
  196. // allow-list.
  197. var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', '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']);
  198. var 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']); // Similarly to SVG, we want to know all MathML elements,
  199. // even those that we disallow by default.
  200. var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
  201. var text = freeze(['#text']);
  202. var html = 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', 'nonce', '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']);
  203. var svg = 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', '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']);
  204. var mathMl = 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']);
  205. var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
  206. var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
  207. var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  208. var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
  209. var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
  210. var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
  211. 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
  212. );
  213. var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  214. var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
  215. );
  216. var DOCTYPE_NAME = seal(/^html$/i);
  217. var getGlobal = function getGlobal() {
  218. return typeof window === 'undefined' ? null : window;
  219. };
  220. /**
  221. * Creates a no-op policy for internal use only.
  222. * Don't export this function outside this module!
  223. * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
  224. * @param {Document} document The document object (to determine policy name suffix)
  225. * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
  226. * are not supported).
  227. */
  228. var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  229. if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  230. return null;
  231. } // Allow the callers to control the unique policy name
  232. // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
  233. // Policy creation with duplicate names throws in Trusted Types.
  234. var suffix = null;
  235. var ATTR_NAME = 'data-tt-policy-suffix';
  236. if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
  237. suffix = document.currentScript.getAttribute(ATTR_NAME);
  238. }
  239. var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  240. try {
  241. return trustedTypes.createPolicy(policyName, {
  242. createHTML: function createHTML(html) {
  243. return html;
  244. },
  245. createScriptURL: function createScriptURL(scriptUrl) {
  246. return scriptUrl;
  247. }
  248. });
  249. } catch (_) {
  250. // Policy creation failed (most likely another DOMPurify script has
  251. // already run). Skip creating the policy, as this will only cause errors
  252. // if TT are enforced.
  253. console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  254. return null;
  255. }
  256. };
  257. function createDOMPurify() {
  258. var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  259. var DOMPurify = function DOMPurify(root) {
  260. return createDOMPurify(root);
  261. };
  262. /**
  263. * Version label, exposed for easier checks
  264. * if DOMPurify is up to date or not
  265. */
  266. DOMPurify.version = '2.4.5';
  267. /**
  268. * Array of elements that DOMPurify removed during sanitation.
  269. * Empty if nothing was removed.
  270. */
  271. DOMPurify.removed = [];
  272. if (!window || !window.document || window.document.nodeType !== 9) {
  273. // Not running in a browser, provide a factory function
  274. // so that you can pass your own Window
  275. DOMPurify.isSupported = false;
  276. return DOMPurify;
  277. }
  278. var originalDocument = window.document;
  279. var document = window.document;
  280. var DocumentFragment = window.DocumentFragment,
  281. HTMLTemplateElement = window.HTMLTemplateElement,
  282. Node = window.Node,
  283. Element = window.Element,
  284. NodeFilter = window.NodeFilter,
  285. _window$NamedNodeMap = window.NamedNodeMap,
  286. NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
  287. HTMLFormElement = window.HTMLFormElement,
  288. DOMParser = window.DOMParser,
  289. trustedTypes = window.trustedTypes;
  290. var ElementPrototype = Element.prototype;
  291. var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  292. var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  293. var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  294. var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
  295. // new document created via createHTMLDocument. As per the spec
  296. // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
  297. // a new empty registry is used when creating a template contents owner
  298. // document, so we use that as our parent document to ensure nothing
  299. // is inherited.
  300. if (typeof HTMLTemplateElement === 'function') {
  301. var template = document.createElement('template');
  302. if (template.content && template.content.ownerDocument) {
  303. document = template.content.ownerDocument;
  304. }
  305. }
  306. var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  307. var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
  308. var _document = document,
  309. implementation = _document.implementation,
  310. createNodeIterator = _document.createNodeIterator,
  311. createDocumentFragment = _document.createDocumentFragment,
  312. getElementsByTagName = _document.getElementsByTagName;
  313. var importNode = originalDocument.importNode;
  314. var documentMode = {};
  315. try {
  316. documentMode = clone(document).documentMode ? document.documentMode : {};
  317. } catch (_) {}
  318. var hooks = {};
  319. /**
  320. * Expose whether this browser supports running the full DOMPurify.
  321. */
  322. DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  323. var MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
  324. ERB_EXPR$1 = ERB_EXPR,
  325. TMPLIT_EXPR$1 = TMPLIT_EXPR,
  326. DATA_ATTR$1 = DATA_ATTR,
  327. ARIA_ATTR$1 = ARIA_ATTR,
  328. IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
  329. ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
  330. var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
  331. /**
  332. * We consider the elements and attributes below to be safe. Ideally
  333. * don't add any new ones but feel free to remove unwanted ones.
  334. */
  335. /* allowed element names */
  336. var ALLOWED_TAGS = null;
  337. var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
  338. /* Allowed attribute names */
  339. var ALLOWED_ATTR = null;
  340. var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
  341. /*
  342. * Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
  343. * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
  344. * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
  345. * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
  346. */
  347. var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
  348. tagNameCheck: {
  349. writable: true,
  350. configurable: false,
  351. enumerable: true,
  352. value: null
  353. },
  354. attributeNameCheck: {
  355. writable: true,
  356. configurable: false,
  357. enumerable: true,
  358. value: null
  359. },
  360. allowCustomizedBuiltInElements: {
  361. writable: true,
  362. configurable: false,
  363. enumerable: true,
  364. value: false
  365. }
  366. }));
  367. /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
  368. var FORBID_TAGS = null;
  369. /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
  370. var FORBID_ATTR = null;
  371. /* Decide if ARIA attributes are okay */
  372. var ALLOW_ARIA_ATTR = true;
  373. /* Decide if custom data attributes are okay */
  374. var ALLOW_DATA_ATTR = true;
  375. /* Decide if unknown protocols are okay */
  376. var ALLOW_UNKNOWN_PROTOCOLS = false;
  377. /* Decide if self-closing tags in attributes are allowed.
  378. * Usually removed due to a mXSS issue in jQuery 3.0 */
  379. var ALLOW_SELF_CLOSE_IN_ATTR = true;
  380. /* Output should be safe for common template engines.
  381. * This means, DOMPurify removes data attributes, mustaches and ERB
  382. */
  383. var SAFE_FOR_TEMPLATES = false;
  384. /* Decide if document with <html>... should be returned */
  385. var WHOLE_DOCUMENT = false;
  386. /* Track whether config is already set on this instance of DOMPurify. */
  387. var SET_CONFIG = false;
  388. /* Decide if all elements (e.g. style, script) must be children of
  389. * document.body. By default, browsers might move them to document.head */
  390. var FORCE_BODY = false;
  391. /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
  392. * string (or a TrustedHTML object if Trusted Types are supported).
  393. * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
  394. */
  395. var RETURN_DOM = false;
  396. /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
  397. * string (or a TrustedHTML object if Trusted Types are supported) */
  398. var RETURN_DOM_FRAGMENT = false;
  399. /* Try to return a Trusted Type object instead of a string, return a string in
  400. * case Trusted Types are not supported */
  401. var RETURN_TRUSTED_TYPE = false;
  402. /* Output should be free from DOM clobbering attacks?
  403. * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
  404. */
  405. var SANITIZE_DOM = true;
  406. /* Achieve full DOM Clobbering protection by isolating the namespace of named
  407. * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
  408. *
  409. * HTML/DOM spec rules that enable DOM Clobbering:
  410. * - Named Access on Window (§7.3.3)
  411. * - DOM Tree Accessors (§3.1.5)
  412. * - Form Element Parent-Child Relations (§4.10.3)
  413. * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
  414. * - HTMLCollection (§4.2.10.2)
  415. *
  416. * Namespace isolation is implemented by prefixing `id` and `name` attributes
  417. * with a constant string, i.e., `user-content-`
  418. */
  419. var SANITIZE_NAMED_PROPS = false;
  420. var SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
  421. /* Keep element content when removing element? */
  422. var KEEP_CONTENT = true;
  423. /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
  424. * of importing it into a new Document and returning a sanitized copy */
  425. var IN_PLACE = false;
  426. /* Allow usage of profiles like html, svg and mathMl */
  427. var USE_PROFILES = {};
  428. /* Tags to ignore content of when KEEP_CONTENT is true */
  429. var FORBID_CONTENTS = null;
  430. 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']);
  431. /* Tags that are safe for data: URIs */
  432. var DATA_URI_TAGS = null;
  433. var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
  434. /* Attributes safe for values like "javascript:" */
  435. var URI_SAFE_ATTRIBUTES = null;
  436. var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
  437. var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  438. var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  439. var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  440. /* Document namespace */
  441. var NAMESPACE = HTML_NAMESPACE;
  442. var IS_EMPTY_INPUT = false;
  443. /* Allowed XHTML+XML namespaces */
  444. var ALLOWED_NAMESPACES = null;
  445. var DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
  446. /* Parsing of strict XHTML documents */
  447. var PARSER_MEDIA_TYPE;
  448. var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
  449. var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  450. var transformCaseFunc;
  451. /* Keep a reference to config to pass to hooks */
  452. var CONFIG = null;
  453. /* Ideally, do not touch anything below this line */
  454. /* ______________________________________________ */
  455. var formElement = document.createElement('form');
  456. var isRegexOrFunction = function isRegexOrFunction(testValue) {
  457. return testValue instanceof RegExp || testValue instanceof Function;
  458. };
  459. /**
  460. * _parseConfig
  461. *
  462. * @param {Object} cfg optional config literal
  463. */
  464. // eslint-disable-next-line complexity
  465. var _parseConfig = function _parseConfig(cfg) {
  466. if (CONFIG && CONFIG === cfg) {
  467. return;
  468. }
  469. /* Shield configuration object from tampering */
  470. if (!cfg || _typeof(cfg) !== 'object') {
  471. cfg = {};
  472. }
  473. /* Shield configuration object from prototype pollution */
  474. cfg = clone(cfg);
  475. PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
  476. SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
  477. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
  478. /* Set configuration parameters */
  479. ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
  480. ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
  481. ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
  482. URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent
  483. cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent
  484. transformCaseFunc // eslint-disable-line indent
  485. ) // eslint-disable-line indent
  486. : DEFAULT_URI_SAFE_ATTRIBUTES;
  487. DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent
  488. cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent
  489. transformCaseFunc // eslint-disable-line indent
  490. ) // eslint-disable-line indent
  491. : DEFAULT_DATA_URI_TAGS;
  492. FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
  493. FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
  494. FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
  495. USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
  496. ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
  497. ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
  498. ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
  499. ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
  500. SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
  501. WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
  502. RETURN_DOM = cfg.RETURN_DOM || false; // Default false
  503. RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
  504. RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
  505. FORCE_BODY = cfg.FORCE_BODY || false; // Default false
  506. SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
  507. SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
  508. KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
  509. IN_PLACE = cfg.IN_PLACE || false; // Default false
  510. IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
  511. NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
  512. CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
  513. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
  514. CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
  515. }
  516. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
  517. CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
  518. }
  519. if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
  520. CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
  521. }
  522. if (SAFE_FOR_TEMPLATES) {
  523. ALLOW_DATA_ATTR = false;
  524. }
  525. if (RETURN_DOM_FRAGMENT) {
  526. RETURN_DOM = true;
  527. }
  528. /* Parse profile info */
  529. if (USE_PROFILES) {
  530. ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
  531. ALLOWED_ATTR = [];
  532. if (USE_PROFILES.html === true) {
  533. addToSet(ALLOWED_TAGS, html$1);
  534. addToSet(ALLOWED_ATTR, html);
  535. }
  536. if (USE_PROFILES.svg === true) {
  537. addToSet(ALLOWED_TAGS, svg$1);
  538. addToSet(ALLOWED_ATTR, svg);
  539. addToSet(ALLOWED_ATTR, xml);
  540. }
  541. if (USE_PROFILES.svgFilters === true) {
  542. addToSet(ALLOWED_TAGS, svgFilters);
  543. addToSet(ALLOWED_ATTR, svg);
  544. addToSet(ALLOWED_ATTR, xml);
  545. }
  546. if (USE_PROFILES.mathMl === true) {
  547. addToSet(ALLOWED_TAGS, mathMl$1);
  548. addToSet(ALLOWED_ATTR, mathMl);
  549. addToSet(ALLOWED_ATTR, xml);
  550. }
  551. }
  552. /* Merge configuration parameters */
  553. if (cfg.ADD_TAGS) {
  554. if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  555. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  556. }
  557. addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
  558. }
  559. if (cfg.ADD_ATTR) {
  560. if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  561. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  562. }
  563. addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
  564. }
  565. if (cfg.ADD_URI_SAFE_ATTR) {
  566. addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
  567. }
  568. if (cfg.FORBID_CONTENTS) {
  569. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  570. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  571. }
  572. addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
  573. }
  574. /* Add #text in case KEEP_CONTENT is set to true */
  575. if (KEEP_CONTENT) {
  576. ALLOWED_TAGS['#text'] = true;
  577. }
  578. /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
  579. if (WHOLE_DOCUMENT) {
  580. addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
  581. }
  582. /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
  583. if (ALLOWED_TAGS.table) {
  584. addToSet(ALLOWED_TAGS, ['tbody']);
  585. delete FORBID_TAGS.tbody;
  586. } // Prevent further manipulation of configuration.
  587. // Not available in IE8, Safari 5, etc.
  588. if (freeze) {
  589. freeze(cfg);
  590. }
  591. CONFIG = cfg;
  592. };
  593. var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
  594. var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
  595. // namespace. We need to specify them explicitly
  596. // so that they don't get erroneously deleted from
  597. // HTML namespace.
  598. var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
  599. /* Keep track of all possible SVG and MathML tags
  600. * so that we can perform the namespace checks
  601. * correctly. */
  602. var ALL_SVG_TAGS = addToSet({}, svg$1);
  603. addToSet(ALL_SVG_TAGS, svgFilters);
  604. addToSet(ALL_SVG_TAGS, svgDisallowed);
  605. var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
  606. addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  607. /**
  608. *
  609. *
  610. * @param {Element} element a DOM element whose namespace is being checked
  611. * @returns {boolean} Return false if the element has a
  612. * namespace that a spec-compliant parser would never
  613. * return. Return true otherwise.
  614. */
  615. var _checkValidNamespace = function _checkValidNamespace(element) {
  616. var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
  617. // can be null. We just simulate parent in this case.
  618. if (!parent || !parent.tagName) {
  619. parent = {
  620. namespaceURI: NAMESPACE,
  621. tagName: 'template'
  622. };
  623. }
  624. var tagName = stringToLowerCase(element.tagName);
  625. var parentTagName = stringToLowerCase(parent.tagName);
  626. if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
  627. return false;
  628. }
  629. if (element.namespaceURI === SVG_NAMESPACE) {
  630. // The only way to switch from HTML namespace to SVG
  631. // is via <svg>. If it happens via any other tag, then
  632. // it should be killed.
  633. if (parent.namespaceURI === HTML_NAMESPACE) {
  634. return tagName === 'svg';
  635. } // The only way to switch from MathML to SVG is via`
  636. // svg if parent is either <annotation-xml> or MathML
  637. // text integration points.
  638. if (parent.namespaceURI === MATHML_NAMESPACE) {
  639. return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  640. } // We only allow elements that are defined in SVG
  641. // spec. All others are disallowed in SVG namespace.
  642. return Boolean(ALL_SVG_TAGS[tagName]);
  643. }
  644. if (element.namespaceURI === MATHML_NAMESPACE) {
  645. // The only way to switch from HTML namespace to MathML
  646. // is via <math>. If it happens via any other tag, then
  647. // it should be killed.
  648. if (parent.namespaceURI === HTML_NAMESPACE) {
  649. return tagName === 'math';
  650. } // The only way to switch from SVG to MathML is via
  651. // <math> and HTML integration points
  652. if (parent.namespaceURI === SVG_NAMESPACE) {
  653. return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  654. } // We only allow elements that are defined in MathML
  655. // spec. All others are disallowed in MathML namespace.
  656. return Boolean(ALL_MATHML_TAGS[tagName]);
  657. }
  658. if (element.namespaceURI === HTML_NAMESPACE) {
  659. // The only way to switch from SVG to HTML is via
  660. // HTML integration points, and from MathML to HTML
  661. // is via MathML text integration points
  662. if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  663. return false;
  664. }
  665. if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  666. return false;
  667. } // We disallow tags that are specific for MathML
  668. // or SVG and should never appear in HTML namespace
  669. return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
  670. } // For XHTML and XML documents that support custom namespaces
  671. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
  672. return true;
  673. } // The code should never reach this place (this means
  674. // that the element somehow got namespace that is not
  675. // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
  676. // Return false just in case.
  677. return false;
  678. };
  679. /**
  680. * _forceRemove
  681. *
  682. * @param {Node} node a DOM node
  683. */
  684. var _forceRemove = function _forceRemove(node) {
  685. arrayPush(DOMPurify.removed, {
  686. element: node
  687. });
  688. try {
  689. // eslint-disable-next-line unicorn/prefer-dom-node-remove
  690. node.parentNode.removeChild(node);
  691. } catch (_) {
  692. try {
  693. node.outerHTML = emptyHTML;
  694. } catch (_) {
  695. node.remove();
  696. }
  697. }
  698. };
  699. /**
  700. * _removeAttribute
  701. *
  702. * @param {String} name an Attribute name
  703. * @param {Node} node a DOM node
  704. */
  705. var _removeAttribute = function _removeAttribute(name, node) {
  706. try {
  707. arrayPush(DOMPurify.removed, {
  708. attribute: node.getAttributeNode(name),
  709. from: node
  710. });
  711. } catch (_) {
  712. arrayPush(DOMPurify.removed, {
  713. attribute: null,
  714. from: node
  715. });
  716. }
  717. node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes
  718. if (name === 'is' && !ALLOWED_ATTR[name]) {
  719. if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  720. try {
  721. _forceRemove(node);
  722. } catch (_) {}
  723. } else {
  724. try {
  725. node.setAttribute(name, '');
  726. } catch (_) {}
  727. }
  728. }
  729. };
  730. /**
  731. * _initDocument
  732. *
  733. * @param {String} dirty a string of dirty markup
  734. * @return {Document} a DOM, filled with the dirty markup
  735. */
  736. var _initDocument = function _initDocument(dirty) {
  737. /* Create a HTML document */
  738. var doc;
  739. var leadingWhitespace;
  740. if (FORCE_BODY) {
  741. dirty = '<remove></remove>' + dirty;
  742. } else {
  743. /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
  744. var matches = stringMatch(dirty, /^[\r\n\t ]+/);
  745. leadingWhitespace = matches && matches[0];
  746. }
  747. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
  748. // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
  749. dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
  750. }
  751. var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
  752. /*
  753. * Use the DOMParser API by default, fallback later if needs be
  754. * DOMParser not work for svg when has multiple root element.
  755. */
  756. if (NAMESPACE === HTML_NAMESPACE) {
  757. try {
  758. doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
  759. } catch (_) {}
  760. }
  761. /* Use createHTMLDocument in case DOMParser is not available */
  762. if (!doc || !doc.documentElement) {
  763. doc = implementation.createDocument(NAMESPACE, 'template', null);
  764. try {
  765. doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
  766. } catch (_) {// Syntax error if dirtyPayload is invalid xml
  767. }
  768. }
  769. var body = doc.body || doc.documentElement;
  770. if (dirty && leadingWhitespace) {
  771. body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  772. }
  773. /* Work on whole document or just its body */
  774. if (NAMESPACE === HTML_NAMESPACE) {
  775. return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  776. }
  777. return WHOLE_DOCUMENT ? doc.documentElement : body;
  778. };
  779. /**
  780. * _createIterator
  781. *
  782. * @param {Document} root document/fragment to create iterator for
  783. * @return {Iterator} iterator instance
  784. */
  785. var _createIterator = function _createIterator(root) {
  786. return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
  787. NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  788. };
  789. /**
  790. * _isClobbered
  791. *
  792. * @param {Node} elm element to check for clobbering attacks
  793. * @return {Boolean} true if clobbered, false if safe
  794. */
  795. var _isClobbered = function _isClobbered(elm) {
  796. return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function');
  797. };
  798. /**
  799. * _isNode
  800. *
  801. * @param {Node} obj object to check whether it's a DOM node
  802. * @return {Boolean} true is object is a DOM node
  803. */
  804. var _isNode = function _isNode(object) {
  805. return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  806. };
  807. /**
  808. * _executeHook
  809. * Execute user configurable hooks
  810. *
  811. * @param {String} entryPoint Name of the hook's entry point
  812. * @param {Node} currentNode node to work on with the hook
  813. * @param {Object} data additional hook parameters
  814. */
  815. var _executeHook = function _executeHook(entryPoint, currentNode, data) {
  816. if (!hooks[entryPoint]) {
  817. return;
  818. }
  819. arrayForEach(hooks[entryPoint], function (hook) {
  820. hook.call(DOMPurify, currentNode, data, CONFIG);
  821. });
  822. };
  823. /**
  824. * _sanitizeElements
  825. *
  826. * @protect nodeName
  827. * @protect textContent
  828. * @protect removeChild
  829. *
  830. * @param {Node} currentNode to check for permission to exist
  831. * @return {Boolean} true if node was killed, false if left alive
  832. */
  833. var _sanitizeElements = function _sanitizeElements(currentNode) {
  834. var content;
  835. /* Execute a hook if present */
  836. _executeHook('beforeSanitizeElements', currentNode, null);
  837. /* Check if element is clobbered or can clobber */
  838. if (_isClobbered(currentNode)) {
  839. _forceRemove(currentNode);
  840. return true;
  841. }
  842. /* Check if tagname contains Unicode */
  843. if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
  844. _forceRemove(currentNode);
  845. return true;
  846. }
  847. /* Now let's check the element's type and name */
  848. var tagName = transformCaseFunc(currentNode.nodeName);
  849. /* Execute a hook if present */
  850. _executeHook('uponSanitizeElement', currentNode, {
  851. tagName: tagName,
  852. allowedTags: ALLOWED_TAGS
  853. });
  854. /* Detect mXSS attempts abusing namespace confusion */
  855. if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
  856. _forceRemove(currentNode);
  857. return true;
  858. }
  859. /* Mitigate a problem with templates inside select */
  860. if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
  861. _forceRemove(currentNode);
  862. return true;
  863. }
  864. /* Remove element if anything forbids its presence */
  865. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  866. /* Check if we have a custom element to handle */
  867. if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
  868. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
  869. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
  870. }
  871. /* Keep content except for bad-listed elements */
  872. if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  873. var parentNode = getParentNode(currentNode) || currentNode.parentNode;
  874. var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  875. if (childNodes && parentNode) {
  876. var childCount = childNodes.length;
  877. for (var i = childCount - 1; i >= 0; --i) {
  878. parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
  879. }
  880. }
  881. }
  882. _forceRemove(currentNode);
  883. return true;
  884. }
  885. /* Check whether element has a valid namespace */
  886. if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
  887. _forceRemove(currentNode);
  888. return true;
  889. }
  890. if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
  891. _forceRemove(currentNode);
  892. return true;
  893. }
  894. /* Sanitize element content to be template-safe */
  895. if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
  896. /* Get the element's text content */
  897. content = currentNode.textContent;
  898. content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
  899. content = stringReplace(content, ERB_EXPR$1, ' ');
  900. content = stringReplace(content, TMPLIT_EXPR$1, ' ');
  901. if (currentNode.textContent !== content) {
  902. arrayPush(DOMPurify.removed, {
  903. element: currentNode.cloneNode()
  904. });
  905. currentNode.textContent = content;
  906. }
  907. }
  908. /* Execute a hook if present */
  909. _executeHook('afterSanitizeElements', currentNode, null);
  910. return false;
  911. };
  912. /**
  913. * _isValidAttribute
  914. *
  915. * @param {string} lcTag Lowercase tag name of containing element.
  916. * @param {string} lcName Lowercase attribute name.
  917. * @param {string} value Attribute value.
  918. * @return {Boolean} Returns true if `value` is valid, otherwise false.
  919. */
  920. // eslint-disable-next-line complexity
  921. var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  922. /* Make sure attribute cannot clobber */
  923. if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  924. return false;
  925. }
  926. /* Allow valid data-* attributes: At least one character after "-"
  927. (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
  928. XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
  929. We don't need to check the value; it's always URI safe. */
  930. 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]) {
  931. if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
  932. // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
  933. // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
  934. _basicCustomElementTest(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)) || // Alternative, second condition checks if it's an `is`-attribute, AND
  935. // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
  936. 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 {
  937. return false;
  938. }
  939. /* Check value is safe. First, is attr inert? If so, is safe */
  940. } 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 {
  941. return false;
  942. }
  943. return true;
  944. };
  945. /**
  946. * _basicCustomElementCheck
  947. * checks if at least one dash is included in tagName, and it's not the first char
  948. * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
  949. * @param {string} tagName name of the tag of the node to sanitize
  950. */
  951. var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
  952. return tagName.indexOf('-') > 0;
  953. };
  954. /**
  955. * _sanitizeAttributes
  956. *
  957. * @protect attributes
  958. * @protect nodeName
  959. * @protect removeAttribute
  960. * @protect setAttribute
  961. *
  962. * @param {Node} currentNode to sanitize
  963. */
  964. var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  965. var attr;
  966. var value;
  967. var lcName;
  968. var l;
  969. /* Execute a hook if present */
  970. _executeHook('beforeSanitizeAttributes', currentNode, null);
  971. var attributes = currentNode.attributes;
  972. /* Check if we have attributes; if not we might have a text node */
  973. if (!attributes) {
  974. return;
  975. }
  976. var hookEvent = {
  977. attrName: '',
  978. attrValue: '',
  979. keepAttr: true,
  980. allowedAttributes: ALLOWED_ATTR
  981. };
  982. l = attributes.length;
  983. /* Go backwards over all attributes; safely remove bad ones */
  984. while (l--) {
  985. attr = attributes[l];
  986. var _attr = attr,
  987. name = _attr.name,
  988. namespaceURI = _attr.namespaceURI;
  989. value = name === 'value' ? attr.value : stringTrim(attr.value);
  990. lcName = transformCaseFunc(name);
  991. /* Execute a hook if present */
  992. hookEvent.attrName = lcName;
  993. hookEvent.attrValue = value;
  994. hookEvent.keepAttr = true;
  995. hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
  996. _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
  997. value = hookEvent.attrValue;
  998. /* Did the hooks approve of the attribute? */
  999. if (hookEvent.forceKeepAttr) {
  1000. continue;
  1001. }
  1002. /* Remove attribute */
  1003. _removeAttribute(name, currentNode);
  1004. /* Did the hooks approve of the attribute? */
  1005. if (!hookEvent.keepAttr) {
  1006. continue;
  1007. }
  1008. /* Work around a security issue in jQuery 3.0 */
  1009. if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
  1010. _removeAttribute(name, currentNode);
  1011. continue;
  1012. }
  1013. /* Sanitize attribute content to be template-safe */
  1014. if (SAFE_FOR_TEMPLATES) {
  1015. value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
  1016. value = stringReplace(value, ERB_EXPR$1, ' ');
  1017. value = stringReplace(value, TMPLIT_EXPR$1, ' ');
  1018. }
  1019. /* Is `value` valid for this attribute? */
  1020. var lcTag = transformCaseFunc(currentNode.nodeName);
  1021. if (!_isValidAttribute(lcTag, lcName, value)) {
  1022. continue;
  1023. }
  1024. /* Full DOM Clobbering protection via namespace isolation,
  1025. * Prefix id and name attributes with `user-content-`
  1026. */
  1027. if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
  1028. // Remove the attribute with this value
  1029. _removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value
  1030. value = SANITIZE_NAMED_PROPS_PREFIX + value;
  1031. }
  1032. /* Handle attributes that require Trusted Types */
  1033. if (trustedTypesPolicy && _typeof(trustedTypes) === 'object' && typeof trustedTypes.getAttributeType === 'function') {
  1034. if (namespaceURI) ; else {
  1035. switch (trustedTypes.getAttributeType(lcTag, lcName)) {
  1036. case 'TrustedHTML':
  1037. value = trustedTypesPolicy.createHTML(value);
  1038. break;
  1039. case 'TrustedScriptURL':
  1040. value = trustedTypesPolicy.createScriptURL(value);
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. /* Handle invalid data-* attribute set by try-catching it */
  1046. try {
  1047. if (namespaceURI) {
  1048. currentNode.setAttributeNS(namespaceURI, name, value);
  1049. } else {
  1050. /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
  1051. currentNode.setAttribute(name, value);
  1052. }
  1053. arrayPop(DOMPurify.removed);
  1054. } catch (_) {}
  1055. }
  1056. /* Execute a hook if present */
  1057. _executeHook('afterSanitizeAttributes', currentNode, null);
  1058. };
  1059. /**
  1060. * _sanitizeShadowDOM
  1061. *
  1062. * @param {DocumentFragment} fragment to iterate over recursively
  1063. */
  1064. var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
  1065. var shadowNode;
  1066. var shadowIterator = _createIterator(fragment);
  1067. /* Execute a hook if present */
  1068. _executeHook('beforeSanitizeShadowDOM', fragment, null);
  1069. while (shadowNode = shadowIterator.nextNode()) {
  1070. /* Execute a hook if present */
  1071. _executeHook('uponSanitizeShadowNode', shadowNode, null);
  1072. /* Sanitize tags and elements */
  1073. if (_sanitizeElements(shadowNode)) {
  1074. continue;
  1075. }
  1076. /* Deep shadow DOM detected */
  1077. if (shadowNode.content instanceof DocumentFragment) {
  1078. _sanitizeShadowDOM(shadowNode.content);
  1079. }
  1080. /* Check attributes, sanitize if necessary */
  1081. _sanitizeAttributes(shadowNode);
  1082. }
  1083. /* Execute a hook if present */
  1084. _executeHook('afterSanitizeShadowDOM', fragment, null);
  1085. };
  1086. /**
  1087. * Sanitize
  1088. * Public method providing core sanitation functionality
  1089. *
  1090. * @param {String|Node} dirty string or DOM node
  1091. * @param {Object} configuration object
  1092. */
  1093. // eslint-disable-next-line complexity
  1094. DOMPurify.sanitize = function (dirty) {
  1095. var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1096. var body;
  1097. var importedNode;
  1098. var currentNode;
  1099. var oldNode;
  1100. var returnNode;
  1101. /* Make sure we have a string to sanitize.
  1102. DO NOT return early, as this will return the wrong type if
  1103. the user has requested a DOM object rather than a string */
  1104. IS_EMPTY_INPUT = !dirty;
  1105. if (IS_EMPTY_INPUT) {
  1106. dirty = '<!-->';
  1107. }
  1108. /* Stringify, in case dirty is an object */
  1109. if (typeof dirty !== 'string' && !_isNode(dirty)) {
  1110. // eslint-disable-next-line no-negated-condition
  1111. if (typeof dirty.toString !== 'function') {
  1112. throw typeErrorCreate('toString is not a function');
  1113. } else {
  1114. dirty = dirty.toString();
  1115. if (typeof dirty !== 'string') {
  1116. throw typeErrorCreate('dirty is not a string, aborting');
  1117. }
  1118. }
  1119. }
  1120. /* Check we can run. Otherwise fall back or ignore */
  1121. if (!DOMPurify.isSupported) {
  1122. if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
  1123. if (typeof dirty === 'string') {
  1124. return window.toStaticHTML(dirty);
  1125. }
  1126. if (_isNode(dirty)) {
  1127. return window.toStaticHTML(dirty.outerHTML);
  1128. }
  1129. }
  1130. return dirty;
  1131. }
  1132. /* Assign config vars */
  1133. if (!SET_CONFIG) {
  1134. _parseConfig(cfg);
  1135. }
  1136. /* Clean up removed elements */
  1137. DOMPurify.removed = [];
  1138. /* Check if dirty is correctly typed for IN_PLACE */
  1139. if (typeof dirty === 'string') {
  1140. IN_PLACE = false;
  1141. }
  1142. if (IN_PLACE) {
  1143. /* Do some early pre-sanitization to avoid unsafe root nodes */
  1144. if (dirty.nodeName) {
  1145. var tagName = transformCaseFunc(dirty.nodeName);
  1146. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  1147. throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
  1148. }
  1149. }
  1150. } else if (dirty instanceof Node) {
  1151. /* If dirty is a DOM element, append to an empty document to avoid
  1152. elements being stripped by the parser */
  1153. body = _initDocument('<!---->');
  1154. importedNode = body.ownerDocument.importNode(dirty, true);
  1155. if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
  1156. /* Node is already a body, use as is */
  1157. body = importedNode;
  1158. } else if (importedNode.nodeName === 'HTML') {
  1159. body = importedNode;
  1160. } else {
  1161. // eslint-disable-next-line unicorn/prefer-dom-node-append
  1162. body.appendChild(importedNode);
  1163. }
  1164. } else {
  1165. /* Exit directly if we have nothing to do */
  1166. if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
  1167. dirty.indexOf('<') === -1) {
  1168. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
  1169. }
  1170. /* Initialize the document to work on */
  1171. body = _initDocument(dirty);
  1172. /* Check we have a DOM node from the data */
  1173. if (!body) {
  1174. return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
  1175. }
  1176. }
  1177. /* Remove first element node (ours) if FORCE_BODY is set */
  1178. if (body && FORCE_BODY) {
  1179. _forceRemove(body.firstChild);
  1180. }
  1181. /* Get node iterator */
  1182. var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  1183. /* Now start iterating over the created document */
  1184. while (currentNode = nodeIterator.nextNode()) {
  1185. /* Fix IE's strange behavior with manipulated textNodes #89 */
  1186. if (currentNode.nodeType === 3 && currentNode === oldNode) {
  1187. continue;
  1188. }
  1189. /* Sanitize tags and elements */
  1190. if (_sanitizeElements(currentNode)) {
  1191. continue;
  1192. }
  1193. /* Shadow DOM detected, sanitize it */
  1194. if (currentNode.content instanceof DocumentFragment) {
  1195. _sanitizeShadowDOM(currentNode.content);
  1196. }
  1197. /* Check attributes, sanitize if necessary */
  1198. _sanitizeAttributes(currentNode);
  1199. oldNode = currentNode;
  1200. }
  1201. oldNode = null;
  1202. /* If we sanitized `dirty` in-place, return it. */
  1203. if (IN_PLACE) {
  1204. return dirty;
  1205. }
  1206. /* Return sanitized string or DOM */
  1207. if (RETURN_DOM) {
  1208. if (RETURN_DOM_FRAGMENT) {
  1209. returnNode = createDocumentFragment.call(body.ownerDocument);
  1210. while (body.firstChild) {
  1211. // eslint-disable-next-line unicorn/prefer-dom-node-append
  1212. returnNode.appendChild(body.firstChild);
  1213. }
  1214. } else {
  1215. returnNode = body;
  1216. }
  1217. if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmod) {
  1218. /*
  1219. AdoptNode() is not used because internal state is not reset
  1220. (e.g. the past names map of a HTMLFormElement), this is safe
  1221. in theory but we would rather not risk another attack vector.
  1222. The state that is cloned by importNode() is explicitly defined
  1223. by the specs.
  1224. */
  1225. returnNode = importNode.call(originalDocument, returnNode, true);
  1226. }
  1227. return returnNode;
  1228. }
  1229. var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  1230. /* Serialize doctype if allowed */
  1231. if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
  1232. serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
  1233. }
  1234. /* Sanitize final string template-safe */
  1235. if (SAFE_FOR_TEMPLATES) {
  1236. serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
  1237. serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
  1238. serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR$1, ' ');
  1239. }
  1240. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  1241. };
  1242. /**
  1243. * Public method to set the configuration once
  1244. * setConfig
  1245. *
  1246. * @param {Object} cfg configuration object
  1247. */
  1248. DOMPurify.setConfig = function (cfg) {
  1249. _parseConfig(cfg);
  1250. SET_CONFIG = true;
  1251. };
  1252. /**
  1253. * Public method to remove the configuration
  1254. * clearConfig
  1255. *
  1256. */
  1257. DOMPurify.clearConfig = function () {
  1258. CONFIG = null;
  1259. SET_CONFIG = false;
  1260. };
  1261. /**
  1262. * Public method to check if an attribute value is valid.
  1263. * Uses last set config, if any. Otherwise, uses config defaults.
  1264. * isValidAttribute
  1265. *
  1266. * @param {string} tag Tag name of containing element.
  1267. * @param {string} attr Attribute name.
  1268. * @param {string} value Attribute value.
  1269. * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
  1270. */
  1271. DOMPurify.isValidAttribute = function (tag, attr, value) {
  1272. /* Initialize shared config vars if necessary. */
  1273. if (!CONFIG) {
  1274. _parseConfig({});
  1275. }
  1276. var lcTag = transformCaseFunc(tag);
  1277. var lcName = transformCaseFunc(attr);
  1278. return _isValidAttribute(lcTag, lcName, value);
  1279. };
  1280. /**
  1281. * AddHook
  1282. * Public method to add DOMPurify hooks
  1283. *
  1284. * @param {String} entryPoint entry point for the hook to add
  1285. * @param {Function} hookFunction function to execute
  1286. */
  1287. DOMPurify.addHook = function (entryPoint, hookFunction) {
  1288. if (typeof hookFunction !== 'function') {
  1289. return;
  1290. }
  1291. hooks[entryPoint] = hooks[entryPoint] || [];
  1292. arrayPush(hooks[entryPoint], hookFunction);
  1293. };
  1294. /**
  1295. * RemoveHook
  1296. * Public method to remove a DOMPurify hook at a given entryPoint
  1297. * (pops it from the stack of hooks if more are present)
  1298. *
  1299. * @param {String} entryPoint entry point for the hook to remove
  1300. * @return {Function} removed(popped) hook
  1301. */
  1302. DOMPurify.removeHook = function (entryPoint) {
  1303. if (hooks[entryPoint]) {
  1304. return arrayPop(hooks[entryPoint]);
  1305. }
  1306. };
  1307. /**
  1308. * RemoveHooks
  1309. * Public method to remove all DOMPurify hooks at a given entryPoint
  1310. *
  1311. * @param {String} entryPoint entry point for the hooks to remove
  1312. */
  1313. DOMPurify.removeHooks = function (entryPoint) {
  1314. if (hooks[entryPoint]) {
  1315. hooks[entryPoint] = [];
  1316. }
  1317. };
  1318. /**
  1319. * RemoveAllHooks
  1320. * Public method to remove all DOMPurify hooks
  1321. *
  1322. */
  1323. DOMPurify.removeAllHooks = function () {
  1324. hooks = {};
  1325. };
  1326. return DOMPurify;
  1327. }
  1328. var purify = createDOMPurify();
  1329. return purify;
  1330. }));
  1331. //# sourceMappingURL=purify.js.map