purify.cjs.js 57 KB

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