purify.js 60 KB

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