purify.es.js 57 KB

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