purify.cjs.js 60 KB

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