Path: blob/main/assets/js/dompurify/purify.es.js
1678 views
/*! @license DOMPurify 3.0.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.6/LICENSE */12const {3entries,4setPrototypeOf,5isFrozen,6getPrototypeOf,7getOwnPropertyDescriptor8} = Object;9let {10freeze,11seal,12create13} = Object; // eslint-disable-line import/no-mutable-exports1415let {16apply,17construct18} = typeof Reflect !== 'undefined' && Reflect;1920if (!freeze) {21freeze = function freeze(x) {22return x;23};24}2526if (!seal) {27seal = function seal(x) {28return x;29};30}3132if (!apply) {33apply = function apply(fun, thisValue, args) {34return fun.apply(thisValue, args);35};36}3738if (!construct) {39construct = function construct(Func, args) {40return new Func(...args);41};42}4344const arrayForEach = unapply(Array.prototype.forEach);45const arrayPop = unapply(Array.prototype.pop);46const arrayPush = unapply(Array.prototype.push);47const stringToLowerCase = unapply(String.prototype.toLowerCase);48const stringToString = unapply(String.prototype.toString);49const stringMatch = unapply(String.prototype.match);50const stringReplace = unapply(String.prototype.replace);51const stringIndexOf = unapply(String.prototype.indexOf);52const stringTrim = unapply(String.prototype.trim);53const regExpTest = unapply(RegExp.prototype.test);54const typeErrorCreate = unconstruct(TypeError);55/**56* Creates a new function that calls the given function with a specified thisArg and arguments.57*58* @param {Function} func - The function to be wrapped and called.59* @returns {Function} A new function that calls the given function with a specified thisArg and arguments.60*/6162function unapply(func) {63return function (thisArg) {64for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {65args[_key - 1] = arguments[_key];66}6768return apply(func, thisArg, args);69};70}71/**72* Creates a new function that constructs an instance of the given constructor function with the provided arguments.73*74* @param {Function} func - The constructor function to be wrapped and called.75* @returns {Function} A new function that constructs an instance of the given constructor function with the provided arguments.76*/777879function unconstruct(func) {80return function () {81for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {82args[_key2] = arguments[_key2];83}8485return construct(func, args);86};87}88/**89* Add properties to a lookup table90*91* @param {Object} set - The set to which elements will be added.92* @param {Array} array - The array containing elements to be added to the set.93* @param {Function} transformCaseFunc - An optional function to transform the case of each element before adding to the set.94* @returns {Object} The modified set with added elements.95*/969798function addToSet(set, array) {99let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;100101if (setPrototypeOf) {102// Make 'in' and truthy checks like Boolean(set.constructor)103// independent of any properties defined on Object.prototype.104// Prevent prototype setters from intercepting set as a this value.105setPrototypeOf(set, null);106}107108let l = array.length;109110while (l--) {111let element = array[l];112113if (typeof element === 'string') {114const lcElement = transformCaseFunc(element);115116if (lcElement !== element) {117// Config presets (e.g. tags.js, attrs.js) are immutable.118if (!isFrozen(array)) {119array[l] = lcElement;120}121122element = lcElement;123}124}125126set[element] = true;127}128129return set;130}131/**132* Shallow clone an object133*134* @param {Object} object - The object to be cloned.135* @returns {Object} A new object that copies the original.136*/137138139function clone(object) {140const newObject = create(null);141142for (const [property, value] of entries(object)) {143if (getOwnPropertyDescriptor(object, property) !== undefined) {144newObject[property] = value;145}146}147148return newObject;149}150/**151* This method automatically checks if the prop is function or getter and behaves accordingly.152*153* @param {Object} object - The object to look up the getter function in its prototype chain.154* @param {String} prop - The property name for which to find the getter function.155* @returns {Function} The getter function found in the prototype chain or a fallback function.156*/157158function lookupGetter(object, prop) {159while (object !== null) {160const desc = getOwnPropertyDescriptor(object, prop);161162if (desc) {163if (desc.get) {164return unapply(desc.get);165}166167if (typeof desc.value === 'function') {168return unapply(desc.value);169}170}171172object = getPrototypeOf(object);173}174175function fallbackValue(element) {176console.warn('fallback value for', element);177return null;178}179180return fallbackValue;181}182183const 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']); // SVG184185const 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']);186const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.187// We still need to know them so that we can do namespace188// checks properly in case one wants to add them to189// allow-list.190191const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);192const 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,193// even those that we disallow by default.194195const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);196const text = freeze(['#text']);197198const 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']);199const 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']);200const 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']);201const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);202203const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode204205const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);206const TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);207const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape208209const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape210211const 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-escape212);213const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);214const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex215);216const DOCTYPE_NAME = seal(/^html$/i);217218var EXPRESSIONS = /*#__PURE__*/Object.freeze({219__proto__: null,220MUSTACHE_EXPR: MUSTACHE_EXPR,221ERB_EXPR: ERB_EXPR,222TMPLIT_EXPR: TMPLIT_EXPR,223DATA_ATTR: DATA_ATTR,224ARIA_ATTR: ARIA_ATTR,225IS_ALLOWED_URI: IS_ALLOWED_URI,226IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,227ATTR_WHITESPACE: ATTR_WHITESPACE,228DOCTYPE_NAME: DOCTYPE_NAME229});230231const getGlobal = function getGlobal() {232return typeof window === 'undefined' ? null : window;233};234/**235* Creates a no-op policy for internal use only.236* Don't export this function outside this module!237* @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.238* @param {HTMLScriptElement} purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).239* @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types240* are not supported or creating the policy failed).241*/242243244const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {245if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {246return null;247} // Allow the callers to control the unique policy name248// by adding a data-tt-policy-suffix to the script element with the DOMPurify.249// Policy creation with duplicate names throws in Trusted Types.250251252let suffix = null;253const ATTR_NAME = 'data-tt-policy-suffix';254255if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {256suffix = purifyHostElement.getAttribute(ATTR_NAME);257}258259const policyName = 'dompurify' + (suffix ? '#' + suffix : '');260261try {262return trustedTypes.createPolicy(policyName, {263createHTML(html) {264return html;265},266267createScriptURL(scriptUrl) {268return scriptUrl;269}270271});272} catch (_) {273// Policy creation failed (most likely another DOMPurify script has274// already run). Skip creating the policy, as this will only cause errors275// if TT are enforced.276console.warn('TrustedTypes policy ' + policyName + ' could not be created.');277return null;278}279};280281function createDOMPurify() {282let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();283284const DOMPurify = root => createDOMPurify(root);285/**286* Version label, exposed for easier checks287* if DOMPurify is up to date or not288*/289290291DOMPurify.version = '3.0.6';292/**293* Array of elements that DOMPurify removed during sanitation.294* Empty if nothing was removed.295*/296297DOMPurify.removed = [];298299if (!window || !window.document || window.document.nodeType !== 9) {300// Not running in a browser, provide a factory function301// so that you can pass your own Window302DOMPurify.isSupported = false;303return DOMPurify;304}305306let {307document308} = window;309const originalDocument = document;310const currentScript = originalDocument.currentScript;311const {312DocumentFragment,313HTMLTemplateElement,314Node,315Element,316NodeFilter,317NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,318HTMLFormElement,319DOMParser,320trustedTypes321} = window;322const ElementPrototype = Element.prototype;323const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');324const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');325const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');326const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a327// new document created via createHTMLDocument. As per the spec328// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)329// a new empty registry is used when creating a template contents owner330// document, so we use that as our parent document to ensure nothing331// is inherited.332333if (typeof HTMLTemplateElement === 'function') {334const template = document.createElement('template');335336if (template.content && template.content.ownerDocument) {337document = template.content.ownerDocument;338}339}340341let trustedTypesPolicy;342let emptyHTML = '';343const {344implementation,345createNodeIterator,346createDocumentFragment,347getElementsByTagName348} = document;349const {350importNode351} = originalDocument;352let hooks = {};353/**354* Expose whether this browser supports running the full DOMPurify.355*/356357DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;358const {359MUSTACHE_EXPR,360ERB_EXPR,361TMPLIT_EXPR,362DATA_ATTR,363ARIA_ATTR,364IS_SCRIPT_OR_DATA,365ATTR_WHITESPACE366} = EXPRESSIONS;367let {368IS_ALLOWED_URI: IS_ALLOWED_URI$1369} = EXPRESSIONS;370/**371* We consider the elements and attributes below to be safe. Ideally372* don't add any new ones but feel free to remove unwanted ones.373*/374375/* allowed element names */376377let ALLOWED_TAGS = null;378const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);379/* Allowed attribute names */380381let ALLOWED_ATTR = null;382const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);383/*384* Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.385* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)386* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)387* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.388*/389390let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {391tagNameCheck: {392writable: true,393configurable: false,394enumerable: true,395value: null396},397attributeNameCheck: {398writable: true,399configurable: false,400enumerable: true,401value: null402},403allowCustomizedBuiltInElements: {404writable: true,405configurable: false,406enumerable: true,407value: false408}409}));410/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */411412let FORBID_TAGS = null;413/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */414415let FORBID_ATTR = null;416/* Decide if ARIA attributes are okay */417418let ALLOW_ARIA_ATTR = true;419/* Decide if custom data attributes are okay */420421let ALLOW_DATA_ATTR = true;422/* Decide if unknown protocols are okay */423424let ALLOW_UNKNOWN_PROTOCOLS = false;425/* Decide if self-closing tags in attributes are allowed.426* Usually removed due to a mXSS issue in jQuery 3.0 */427428let ALLOW_SELF_CLOSE_IN_ATTR = true;429/* Output should be safe for common template engines.430* This means, DOMPurify removes data attributes, mustaches and ERB431*/432433let SAFE_FOR_TEMPLATES = false;434/* Decide if document with <html>... should be returned */435436let WHOLE_DOCUMENT = false;437/* Track whether config is already set on this instance of DOMPurify. */438439let SET_CONFIG = false;440/* Decide if all elements (e.g. style, script) must be children of441* document.body. By default, browsers might move them to document.head */442443let FORCE_BODY = false;444/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html445* string (or a TrustedHTML object if Trusted Types are supported).446* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead447*/448449let RETURN_DOM = false;450/* Decide if a DOM `DocumentFragment` should be returned, instead of a html451* string (or a TrustedHTML object if Trusted Types are supported) */452453let RETURN_DOM_FRAGMENT = false;454/* Try to return a Trusted Type object instead of a string, return a string in455* case Trusted Types are not supported */456457let RETURN_TRUSTED_TYPE = false;458/* Output should be free from DOM clobbering attacks?459* This sanitizes markups named with colliding, clobberable built-in DOM APIs.460*/461462let SANITIZE_DOM = true;463/* Achieve full DOM Clobbering protection by isolating the namespace of named464* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.465*466* HTML/DOM spec rules that enable DOM Clobbering:467* - Named Access on Window (§7.3.3)468* - DOM Tree Accessors (§3.1.5)469* - Form Element Parent-Child Relations (§4.10.3)470* - Iframe srcdoc / Nested WindowProxies (§4.8.5)471* - HTMLCollection (§4.2.10.2)472*473* Namespace isolation is implemented by prefixing `id` and `name` attributes474* with a constant string, i.e., `user-content-`475*/476477let SANITIZE_NAMED_PROPS = false;478const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';479/* Keep element content when removing element? */480481let KEEP_CONTENT = true;482/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead483* of importing it into a new Document and returning a sanitized copy */484485let IN_PLACE = false;486/* Allow usage of profiles like html, svg and mathMl */487488let USE_PROFILES = {};489/* Tags to ignore content of when KEEP_CONTENT is true */490491let FORBID_CONTENTS = null;492const 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']);493/* Tags that are safe for data: URIs */494495let DATA_URI_TAGS = null;496const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);497/* Attributes safe for values like "javascript:" */498499let URI_SAFE_ATTRIBUTES = null;500const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);501const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';502const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';503const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';504/* Document namespace */505506let NAMESPACE = HTML_NAMESPACE;507let IS_EMPTY_INPUT = false;508/* Allowed XHTML+XML namespaces */509510let ALLOWED_NAMESPACES = null;511const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);512/* Parsing of strict XHTML documents */513514let PARSER_MEDIA_TYPE = null;515const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];516const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';517let transformCaseFunc = null;518/* Keep a reference to config to pass to hooks */519520let CONFIG = null;521/* Ideally, do not touch anything below this line */522523/* ______________________________________________ */524525const formElement = document.createElement('form');526527const isRegexOrFunction = function isRegexOrFunction(testValue) {528return testValue instanceof RegExp || testValue instanceof Function;529};530/**531* _parseConfig532*533* @param {Object} cfg optional config literal534*/535// eslint-disable-next-line complexity536537538const _parseConfig = function _parseConfig() {539let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};540541if (CONFIG && CONFIG === cfg) {542return;543}544/* Shield configuration object from tampering */545546547if (!cfg || typeof cfg !== 'object') {548cfg = {};549}550/* Shield configuration object from prototype pollution */551552553cfg = clone(cfg);554PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes555SUPPORTED_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.556557transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;558/* Set configuration parameters */559560ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;561ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;562ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;563URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent564cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent565transformCaseFunc // eslint-disable-line indent566) // eslint-disable-line indent567: DEFAULT_URI_SAFE_ATTRIBUTES;568DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent569cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent570transformCaseFunc // eslint-disable-line indent571) // eslint-disable-line indent572: DEFAULT_DATA_URI_TAGS;573FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;574FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};575FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};576USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;577ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true578579ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true580581ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false582583ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true584585SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false586587WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false588589RETURN_DOM = cfg.RETURN_DOM || false; // Default false590591RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false592593RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false594595FORCE_BODY = cfg.FORCE_BODY || false; // Default false596597SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true598599SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false600601KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true602603IN_PLACE = cfg.IN_PLACE || false; // Default false604605IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;606NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;607CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};608609if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {610CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;611}612613if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {614CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;615}616617if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {618CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;619}620621if (SAFE_FOR_TEMPLATES) {622ALLOW_DATA_ATTR = false;623}624625if (RETURN_DOM_FRAGMENT) {626RETURN_DOM = true;627}628/* Parse profile info */629630631if (USE_PROFILES) {632ALLOWED_TAGS = addToSet({}, [...text]);633ALLOWED_ATTR = [];634635if (USE_PROFILES.html === true) {636addToSet(ALLOWED_TAGS, html$1);637addToSet(ALLOWED_ATTR, html);638}639640if (USE_PROFILES.svg === true) {641addToSet(ALLOWED_TAGS, svg$1);642addToSet(ALLOWED_ATTR, svg);643addToSet(ALLOWED_ATTR, xml);644}645646if (USE_PROFILES.svgFilters === true) {647addToSet(ALLOWED_TAGS, svgFilters);648addToSet(ALLOWED_ATTR, svg);649addToSet(ALLOWED_ATTR, xml);650}651652if (USE_PROFILES.mathMl === true) {653addToSet(ALLOWED_TAGS, mathMl$1);654addToSet(ALLOWED_ATTR, mathMl);655addToSet(ALLOWED_ATTR, xml);656}657}658/* Merge configuration parameters */659660661if (cfg.ADD_TAGS) {662if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {663ALLOWED_TAGS = clone(ALLOWED_TAGS);664}665666addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);667}668669if (cfg.ADD_ATTR) {670if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {671ALLOWED_ATTR = clone(ALLOWED_ATTR);672}673674addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);675}676677if (cfg.ADD_URI_SAFE_ATTR) {678addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);679}680681if (cfg.FORBID_CONTENTS) {682if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {683FORBID_CONTENTS = clone(FORBID_CONTENTS);684}685686addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);687}688/* Add #text in case KEEP_CONTENT is set to true */689690691if (KEEP_CONTENT) {692ALLOWED_TAGS['#text'] = true;693}694/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */695696697if (WHOLE_DOCUMENT) {698addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);699}700/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */701702703if (ALLOWED_TAGS.table) {704addToSet(ALLOWED_TAGS, ['tbody']);705delete FORBID_TAGS.tbody;706}707708if (cfg.TRUSTED_TYPES_POLICY) {709if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {710throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');711}712713if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {714throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');715} // Overwrite existing TrustedTypes policy.716717718trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; // Sign local variables required by `sanitize`.719720emptyHTML = trustedTypesPolicy.createHTML('');721} else {722// Uninitialized policy, attempt to initialize the internal dompurify policy.723if (trustedTypesPolicy === undefined) {724trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);725} // If creating the internal policy succeeded sign internal variables.726727728if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {729emptyHTML = trustedTypesPolicy.createHTML('');730}731} // Prevent further manipulation of configuration.732// Not available in IE8, Safari 5, etc.733734735if (freeze) {736freeze(cfg);737}738739CONFIG = cfg;740};741742const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);743const HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML744// namespace. We need to specify them explicitly745// so that they don't get erroneously deleted from746// HTML namespace.747748const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);749/* Keep track of all possible SVG and MathML tags750* so that we can perform the namespace checks751* correctly. */752753const ALL_SVG_TAGS = addToSet({}, svg$1);754addToSet(ALL_SVG_TAGS, svgFilters);755addToSet(ALL_SVG_TAGS, svgDisallowed);756const ALL_MATHML_TAGS = addToSet({}, mathMl$1);757addToSet(ALL_MATHML_TAGS, mathMlDisallowed);758/**759* @param {Element} element a DOM element whose namespace is being checked760* @returns {boolean} Return false if the element has a761* namespace that a spec-compliant parser would never762* return. Return true otherwise.763*/764765const _checkValidNamespace = function _checkValidNamespace(element) {766let parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode767// can be null. We just simulate parent in this case.768769if (!parent || !parent.tagName) {770parent = {771namespaceURI: NAMESPACE,772tagName: 'template'773};774}775776const tagName = stringToLowerCase(element.tagName);777const parentTagName = stringToLowerCase(parent.tagName);778779if (!ALLOWED_NAMESPACES[element.namespaceURI]) {780return false;781}782783if (element.namespaceURI === SVG_NAMESPACE) {784// The only way to switch from HTML namespace to SVG785// is via <svg>. If it happens via any other tag, then786// it should be killed.787if (parent.namespaceURI === HTML_NAMESPACE) {788return tagName === 'svg';789} // The only way to switch from MathML to SVG is via`790// svg if parent is either <annotation-xml> or MathML791// text integration points.792793794if (parent.namespaceURI === MATHML_NAMESPACE) {795return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);796} // We only allow elements that are defined in SVG797// spec. All others are disallowed in SVG namespace.798799800return Boolean(ALL_SVG_TAGS[tagName]);801}802803if (element.namespaceURI === MATHML_NAMESPACE) {804// The only way to switch from HTML namespace to MathML805// is via <math>. If it happens via any other tag, then806// it should be killed.807if (parent.namespaceURI === HTML_NAMESPACE) {808return tagName === 'math';809} // The only way to switch from SVG to MathML is via810// <math> and HTML integration points811812813if (parent.namespaceURI === SVG_NAMESPACE) {814return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];815} // We only allow elements that are defined in MathML816// spec. All others are disallowed in MathML namespace.817818819return Boolean(ALL_MATHML_TAGS[tagName]);820}821822if (element.namespaceURI === HTML_NAMESPACE) {823// The only way to switch from SVG to HTML is via824// HTML integration points, and from MathML to HTML825// is via MathML text integration points826if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {827return false;828}829830if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {831return false;832} // We disallow tags that are specific for MathML833// or SVG and should never appear in HTML namespace834835836return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);837} // For XHTML and XML documents that support custom namespaces838839840if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {841return true;842} // The code should never reach this place (this means843// that the element somehow got namespace that is not844// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).845// Return false just in case.846847848return false;849};850/**851* _forceRemove852*853* @param {Node} node a DOM node854*/855856857const _forceRemove = function _forceRemove(node) {858arrayPush(DOMPurify.removed, {859element: node860});861862try {863// eslint-disable-next-line unicorn/prefer-dom-node-remove864node.parentNode.removeChild(node);865} catch (_) {866node.remove();867}868};869/**870* _removeAttribute871*872* @param {String} name an Attribute name873* @param {Node} node a DOM node874*/875876877const _removeAttribute = function _removeAttribute(name, node) {878try {879arrayPush(DOMPurify.removed, {880attribute: node.getAttributeNode(name),881from: node882});883} catch (_) {884arrayPush(DOMPurify.removed, {885attribute: null,886from: node887});888}889890node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes891892if (name === 'is' && !ALLOWED_ATTR[name]) {893if (RETURN_DOM || RETURN_DOM_FRAGMENT) {894try {895_forceRemove(node);896} catch (_) {}897} else {898try {899node.setAttribute(name, '');900} catch (_) {}901}902}903};904/**905* _initDocument906*907* @param {String} dirty a string of dirty markup908* @return {Document} a DOM, filled with the dirty markup909*/910911912const _initDocument = function _initDocument(dirty) {913/* Create a HTML document */914let doc = null;915let leadingWhitespace = null;916917if (FORCE_BODY) {918dirty = '<remove></remove>' + dirty;919} else {920/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */921const matches = stringMatch(dirty, /^[\r\n\t ]+/);922leadingWhitespace = matches && matches[0];923}924925if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {926// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)927dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';928}929930const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;931/*932* Use the DOMParser API by default, fallback later if needs be933* DOMParser not work for svg when has multiple root element.934*/935936if (NAMESPACE === HTML_NAMESPACE) {937try {938doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);939} catch (_) {}940}941/* Use createHTMLDocument in case DOMParser is not available */942943944if (!doc || !doc.documentElement) {945doc = implementation.createDocument(NAMESPACE, 'template', null);946947try {948doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;949} catch (_) {// Syntax error if dirtyPayload is invalid xml950}951}952953const body = doc.body || doc.documentElement;954955if (dirty && leadingWhitespace) {956body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);957}958/* Work on whole document or just its body */959960961if (NAMESPACE === HTML_NAMESPACE) {962return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];963}964965return WHOLE_DOCUMENT ? doc.documentElement : body;966};967/**968* Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.969*970* @param {Node} root The root element or node to start traversing on.971* @return {NodeIterator} The created NodeIterator972*/973974975const _createNodeIterator = function _createNodeIterator(root) {976return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise977NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null);978};979/**980* _isClobbered981*982* @param {Node} elm element to check for clobbering attacks983* @return {Boolean} true if clobbered, false if safe984*/985986987const _isClobbered = function _isClobbered(elm) {988return 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');989};990/**991* Checks whether the given object is a DOM node.992*993* @param {Node} object object to check whether it's a DOM node994* @return {Boolean} true is object is a DOM node995*/996997998const _isNode = function _isNode(object) {999return typeof Node === 'function' && object instanceof Node;1000};1001/**1002* _executeHook1003* Execute user configurable hooks1004*1005* @param {String} entryPoint Name of the hook's entry point1006* @param {Node} currentNode node to work on with the hook1007* @param {Object} data additional hook parameters1008*/100910101011const _executeHook = function _executeHook(entryPoint, currentNode, data) {1012if (!hooks[entryPoint]) {1013return;1014}10151016arrayForEach(hooks[entryPoint], hook => {1017hook.call(DOMPurify, currentNode, data, CONFIG);1018});1019};1020/**1021* _sanitizeElements1022*1023* @protect nodeName1024* @protect textContent1025* @protect removeChild1026*1027* @param {Node} currentNode to check for permission to exist1028* @return {Boolean} true if node was killed, false if left alive1029*/103010311032const _sanitizeElements = function _sanitizeElements(currentNode) {1033let content = null;1034/* Execute a hook if present */10351036_executeHook('beforeSanitizeElements', currentNode, null);1037/* Check if element is clobbered or can clobber */103810391040if (_isClobbered(currentNode)) {1041_forceRemove(currentNode);10421043return true;1044}1045/* Now let's check the element's type and name */104610471048const tagName = transformCaseFunc(currentNode.nodeName);1049/* Execute a hook if present */10501051_executeHook('uponSanitizeElement', currentNode, {1052tagName,1053allowedTags: ALLOWED_TAGS1054});1055/* Detect mXSS attempts abusing namespace confusion */105610571058if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {1059_forceRemove(currentNode);10601061return true;1062}1063/* Remove element if anything forbids its presence */106410651066if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {1067/* Check if we have a custom element to handle */1068if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {1069if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {1070return false;1071}10721073if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {1074return false;1075}1076}1077/* Keep content except for bad-listed elements */107810791080if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {1081const parentNode = getParentNode(currentNode) || currentNode.parentNode;1082const childNodes = getChildNodes(currentNode) || currentNode.childNodes;10831084if (childNodes && parentNode) {1085const childCount = childNodes.length;10861087for (let i = childCount - 1; i >= 0; --i) {1088parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));1089}1090}1091}10921093_forceRemove(currentNode);10941095return true;1096}1097/* Check whether element has a valid namespace */109810991100if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {1101_forceRemove(currentNode);11021103return true;1104}1105/* Make sure that older browsers don't get fallback-tag mXSS */110611071108if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {1109_forceRemove(currentNode);11101111return true;1112}1113/* Sanitize element content to be template-safe */111411151116if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {1117/* Get the element's text content */1118content = currentNode.textContent;1119arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1120content = stringReplace(content, expr, ' ');1121});11221123if (currentNode.textContent !== content) {1124arrayPush(DOMPurify.removed, {1125element: currentNode.cloneNode()1126});1127currentNode.textContent = content;1128}1129}1130/* Execute a hook if present */113111321133_executeHook('afterSanitizeElements', currentNode, null);11341135return false;1136};1137/**1138* _isValidAttribute1139*1140* @param {string} lcTag Lowercase tag name of containing element.1141* @param {string} lcName Lowercase attribute name.1142* @param {string} value Attribute value.1143* @return {Boolean} Returns true if `value` is valid, otherwise false.1144*/1145// eslint-disable-next-line complexity114611471148const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {1149/* Make sure attribute cannot clobber */1150if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {1151return false;1152}1153/* Allow valid data-* attributes: At least one character after "-"1154(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)1155XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)1156We don't need to check the value; it's always URI safe. */115711581159if (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]) {1160if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND1161// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck1162// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck1163_isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND1164// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck1165lcName === '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 {1166return false;1167}1168/* Check value is safe. First, is attr inert? If so, is safe */11691170} 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) {1171return false;1172} else ;11731174return true;1175};1176/**1177* _isBasicCustomElement1178* checks if at least one dash is included in tagName, and it's not the first char1179* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name1180*1181* @param {string} tagName name of the tag of the node to sanitize1182* @returns {boolean} Returns true if the tag name meets the basic criteria for a custom element, otherwise false.1183*/118411851186const _isBasicCustomElement = function _isBasicCustomElement(tagName) {1187return tagName.indexOf('-') > 0;1188};1189/**1190* _sanitizeAttributes1191*1192* @protect attributes1193* @protect nodeName1194* @protect removeAttribute1195* @protect setAttribute1196*1197* @param {Node} currentNode to sanitize1198*/119912001201const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {1202/* Execute a hook if present */1203_executeHook('beforeSanitizeAttributes', currentNode, null);12041205const {1206attributes1207} = currentNode;1208/* Check if we have attributes; if not we might have a text node */12091210if (!attributes) {1211return;1212}12131214const hookEvent = {1215attrName: '',1216attrValue: '',1217keepAttr: true,1218allowedAttributes: ALLOWED_ATTR1219};1220let l = attributes.length;1221/* Go backwards over all attributes; safely remove bad ones */12221223while (l--) {1224const attr = attributes[l];1225const {1226name,1227namespaceURI,1228value: attrValue1229} = attr;1230const lcName = transformCaseFunc(name);1231let value = name === 'value' ? attrValue : stringTrim(attrValue);1232/* Execute a hook if present */12331234hookEvent.attrName = lcName;1235hookEvent.attrValue = value;1236hookEvent.keepAttr = true;1237hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set12381239_executeHook('uponSanitizeAttribute', currentNode, hookEvent);12401241value = hookEvent.attrValue;1242/* Did the hooks approve of the attribute? */12431244if (hookEvent.forceKeepAttr) {1245continue;1246}1247/* Remove attribute */124812491250_removeAttribute(name, currentNode);1251/* Did the hooks approve of the attribute? */125212531254if (!hookEvent.keepAttr) {1255continue;1256}1257/* Work around a security issue in jQuery 3.0 */125812591260if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {1261_removeAttribute(name, currentNode);12621263continue;1264}1265/* Sanitize attribute content to be template-safe */126612671268if (SAFE_FOR_TEMPLATES) {1269arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1270value = stringReplace(value, expr, ' ');1271});1272}1273/* Is `value` valid for this attribute? */127412751276const lcTag = transformCaseFunc(currentNode.nodeName);12771278if (!_isValidAttribute(lcTag, lcName, value)) {1279continue;1280}1281/* Full DOM Clobbering protection via namespace isolation,1282* Prefix id and name attributes with `user-content-`1283*/128412851286if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {1287// Remove the attribute with this value1288_removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value128912901291value = SANITIZE_NAMED_PROPS_PREFIX + value;1292}1293/* Handle attributes that require Trusted Types */129412951296if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {1297if (namespaceURI) ; else {1298switch (trustedTypes.getAttributeType(lcTag, lcName)) {1299case 'TrustedHTML':1300{1301value = trustedTypesPolicy.createHTML(value);1302break;1303}13041305case 'TrustedScriptURL':1306{1307value = trustedTypesPolicy.createScriptURL(value);1308break;1309}1310}1311}1312}1313/* Handle invalid data-* attribute set by try-catching it */131413151316try {1317if (namespaceURI) {1318currentNode.setAttributeNS(namespaceURI, name, value);1319} else {1320/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */1321currentNode.setAttribute(name, value);1322}13231324arrayPop(DOMPurify.removed);1325} catch (_) {}1326}1327/* Execute a hook if present */132813291330_executeHook('afterSanitizeAttributes', currentNode, null);1331};1332/**1333* _sanitizeShadowDOM1334*1335* @param {DocumentFragment} fragment to iterate over recursively1336*/133713381339const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {1340let shadowNode = null;13411342const shadowIterator = _createNodeIterator(fragment);1343/* Execute a hook if present */134413451346_executeHook('beforeSanitizeShadowDOM', fragment, null);13471348while (shadowNode = shadowIterator.nextNode()) {1349/* Execute a hook if present */1350_executeHook('uponSanitizeShadowNode', shadowNode, null);1351/* Sanitize tags and elements */135213531354if (_sanitizeElements(shadowNode)) {1355continue;1356}1357/* Deep shadow DOM detected */135813591360if (shadowNode.content instanceof DocumentFragment) {1361_sanitizeShadowDOM(shadowNode.content);1362}1363/* Check attributes, sanitize if necessary */136413651366_sanitizeAttributes(shadowNode);1367}1368/* Execute a hook if present */136913701371_executeHook('afterSanitizeShadowDOM', fragment, null);1372};1373/**1374* Sanitize1375* Public method providing core sanitation functionality1376*1377* @param {String|Node} dirty string or DOM node1378* @param {Object} cfg object1379*/1380// eslint-disable-next-line complexity138113821383DOMPurify.sanitize = function (dirty) {1384let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};1385let body = null;1386let importedNode = null;1387let currentNode = null;1388let returnNode = null;1389/* Make sure we have a string to sanitize.1390DO NOT return early, as this will return the wrong type if1391the user has requested a DOM object rather than a string */13921393IS_EMPTY_INPUT = !dirty;13941395if (IS_EMPTY_INPUT) {1396dirty = '<!-->';1397}1398/* Stringify, in case dirty is an object */139914001401if (typeof dirty !== 'string' && !_isNode(dirty)) {1402if (typeof dirty.toString === 'function') {1403dirty = dirty.toString();14041405if (typeof dirty !== 'string') {1406throw typeErrorCreate('dirty is not a string, aborting');1407}1408} else {1409throw typeErrorCreate('toString is not a function');1410}1411}1412/* Return dirty HTML if DOMPurify cannot run */141314141415if (!DOMPurify.isSupported) {1416return dirty;1417}1418/* Assign config vars */141914201421if (!SET_CONFIG) {1422_parseConfig(cfg);1423}1424/* Clean up removed elements */142514261427DOMPurify.removed = [];1428/* Check if dirty is correctly typed for IN_PLACE */14291430if (typeof dirty === 'string') {1431IN_PLACE = false;1432}14331434if (IN_PLACE) {1435/* Do some early pre-sanitization to avoid unsafe root nodes */1436if (dirty.nodeName) {1437const tagName = transformCaseFunc(dirty.nodeName);14381439if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {1440throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');1441}1442}1443} else if (dirty instanceof Node) {1444/* If dirty is a DOM element, append to an empty document to avoid1445elements being stripped by the parser */1446body = _initDocument('<!---->');1447importedNode = body.ownerDocument.importNode(dirty, true);14481449if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {1450/* Node is already a body, use as is */1451body = importedNode;1452} else if (importedNode.nodeName === 'HTML') {1453body = importedNode;1454} else {1455// eslint-disable-next-line unicorn/prefer-dom-node-append1456body.appendChild(importedNode);1457}1458} else {1459/* Exit directly if we have nothing to do */1460if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes1461dirty.indexOf('<') === -1) {1462return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;1463}1464/* Initialize the document to work on */146514661467body = _initDocument(dirty);1468/* Check we have a DOM node from the data */14691470if (!body) {1471return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';1472}1473}1474/* Remove first element node (ours) if FORCE_BODY is set */147514761477if (body && FORCE_BODY) {1478_forceRemove(body.firstChild);1479}1480/* Get node iterator */148114821483const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);1484/* Now start iterating over the created document */148514861487while (currentNode = nodeIterator.nextNode()) {1488/* Sanitize tags and elements */1489if (_sanitizeElements(currentNode)) {1490continue;1491}1492/* Shadow DOM detected, sanitize it */149314941495if (currentNode.content instanceof DocumentFragment) {1496_sanitizeShadowDOM(currentNode.content);1497}1498/* Check attributes, sanitize if necessary */149915001501_sanitizeAttributes(currentNode);1502}1503/* If we sanitized `dirty` in-place, return it. */150415051506if (IN_PLACE) {1507return dirty;1508}1509/* Return sanitized string or DOM */151015111512if (RETURN_DOM) {1513if (RETURN_DOM_FRAGMENT) {1514returnNode = createDocumentFragment.call(body.ownerDocument);15151516while (body.firstChild) {1517// eslint-disable-next-line unicorn/prefer-dom-node-append1518returnNode.appendChild(body.firstChild);1519}1520} else {1521returnNode = body;1522}15231524if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {1525/*1526AdoptNode() is not used because internal state is not reset1527(e.g. the past names map of a HTMLFormElement), this is safe1528in theory but we would rather not risk another attack vector.1529The state that is cloned by importNode() is explicitly defined1530by the specs.1531*/1532returnNode = importNode.call(originalDocument, returnNode, true);1533}15341535return returnNode;1536}15371538let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;1539/* Serialize doctype if allowed */15401541if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {1542serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;1543}1544/* Sanitize final string template-safe */154515461547if (SAFE_FOR_TEMPLATES) {1548arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1549serializedHTML = stringReplace(serializedHTML, expr, ' ');1550});1551}15521553return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;1554};1555/**1556* Public method to set the configuration once1557* setConfig1558*1559* @param {Object} cfg configuration object1560*/156115621563DOMPurify.setConfig = function () {1564let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};15651566_parseConfig(cfg);15671568SET_CONFIG = true;1569};1570/**1571* Public method to remove the configuration1572* clearConfig1573*1574*/157515761577DOMPurify.clearConfig = function () {1578CONFIG = null;1579SET_CONFIG = false;1580};1581/**1582* Public method to check if an attribute value is valid.1583* Uses last set config, if any. Otherwise, uses config defaults.1584* isValidAttribute1585*1586* @param {String} tag Tag name of containing element.1587* @param {String} attr Attribute name.1588* @param {String} value Attribute value.1589* @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.1590*/159115921593DOMPurify.isValidAttribute = function (tag, attr, value) {1594/* Initialize shared config vars if necessary. */1595if (!CONFIG) {1596_parseConfig({});1597}15981599const lcTag = transformCaseFunc(tag);1600const lcName = transformCaseFunc(attr);1601return _isValidAttribute(lcTag, lcName, value);1602};1603/**1604* AddHook1605* Public method to add DOMPurify hooks1606*1607* @param {String} entryPoint entry point for the hook to add1608* @param {Function} hookFunction function to execute1609*/161016111612DOMPurify.addHook = function (entryPoint, hookFunction) {1613if (typeof hookFunction !== 'function') {1614return;1615}16161617hooks[entryPoint] = hooks[entryPoint] || [];1618arrayPush(hooks[entryPoint], hookFunction);1619};1620/**1621* RemoveHook1622* Public method to remove a DOMPurify hook at a given entryPoint1623* (pops it from the stack of hooks if more are present)1624*1625* @param {String} entryPoint entry point for the hook to remove1626* @return {Function} removed(popped) hook1627*/162816291630DOMPurify.removeHook = function (entryPoint) {1631if (hooks[entryPoint]) {1632return arrayPop(hooks[entryPoint]);1633}1634};1635/**1636* RemoveHooks1637* Public method to remove all DOMPurify hooks at a given entryPoint1638*1639* @param {String} entryPoint entry point for the hooks to remove1640*/164116421643DOMPurify.removeHooks = function (entryPoint) {1644if (hooks[entryPoint]) {1645hooks[entryPoint] = [];1646}1647};1648/**1649* RemoveAllHooks1650* Public method to remove all DOMPurify hooks1651*/165216531654DOMPurify.removeAllHooks = function () {1655hooks = {};1656};16571658return DOMPurify;1659}16601661var purify = createDOMPurify();16621663export { purify as default };1664//# sourceMappingURL=purify.es.js.map166516661667