Path: blob/main/src/vs/base/browser/dompurify/dompurify.js
3294 views
/*! @license DOMPurify 3.1.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.7/LICENSE */12const {3entries,4setPrototypeOf,5isFrozen,6getPrototypeOf,7getOwnPropertyDescriptor8} = Object;9let {10freeze,11seal,12create13} = Object; // eslint-disable-line import/no-mutable-exports14let {15apply,16construct17} = typeof Reflect !== 'undefined' && Reflect;18if (!freeze) {19freeze = function freeze(x) {20return x;21};22}23if (!seal) {24seal = function seal(x) {25return x;26};27}28if (!apply) {29apply = function apply(fun, thisValue, args) {30return fun.apply(thisValue, args);31};32}33if (!construct) {34construct = function construct(Func, args) {35return new Func(...args);36};37}38const arrayForEach = unapply(Array.prototype.forEach);39const arrayPop = unapply(Array.prototype.pop);40const arrayPush = unapply(Array.prototype.push);41const stringToLowerCase = unapply(String.prototype.toLowerCase);42const stringToString = unapply(String.prototype.toString);43const stringMatch = unapply(String.prototype.match);44const stringReplace = unapply(String.prototype.replace);45const stringIndexOf = unapply(String.prototype.indexOf);46const stringTrim = unapply(String.prototype.trim);47const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);48const regExpTest = unapply(RegExp.prototype.test);49const typeErrorCreate = unconstruct(TypeError);5051/**52* Creates a new function that calls the given function with a specified thisArg and arguments.53*54* @param {Function} func - The function to be wrapped and called.55* @returns {Function} A new function that calls the given function with a specified thisArg and arguments.56*/57function unapply(func) {58return function (thisArg) {59for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {60args[_key - 1] = arguments[_key];61}62return apply(func, thisArg, args);63};64}6566/**67* Creates a new function that constructs an instance of the given constructor function with the provided arguments.68*69* @param {Function} func - The constructor function to be wrapped and called.70* @returns {Function} A new function that constructs an instance of the given constructor function with the provided arguments.71*/72function unconstruct(func) {73return function () {74for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {75args[_key2] = arguments[_key2];76}77return construct(func, args);78};79}8081/**82* Add properties to a lookup table83*84* @param {Object} set - The set to which elements will be added.85* @param {Array} array - The array containing elements to be added to the set.86* @param {Function} transformCaseFunc - An optional function to transform the case of each element before adding to the set.87* @returns {Object} The modified set with added elements.88*/89function addToSet(set, array) {90let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;91if (setPrototypeOf) {92// Make 'in' and truthy checks like Boolean(set.constructor)93// independent of any properties defined on Object.prototype.94// Prevent prototype setters from intercepting set as a this value.95setPrototypeOf(set, null);96}97let l = array.length;98while (l--) {99let element = array[l];100if (typeof element === 'string') {101const lcElement = transformCaseFunc(element);102if (lcElement !== element) {103// Config presets (e.g. tags.js, attrs.js) are immutable.104if (!isFrozen(array)) {105array[l] = lcElement;106}107element = lcElement;108}109}110set[element] = true;111}112return set;113}114115/**116* Clean up an array to harden against CSPP117*118* @param {Array} array - The array to be cleaned.119* @returns {Array} The cleaned version of the array120*/121function cleanArray(array) {122for (let index = 0; index < array.length; index++) {123const isPropertyExist = objectHasOwnProperty(array, index);124if (!isPropertyExist) {125array[index] = null;126}127}128return array;129}130131/**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*/137function clone(object) {138const newObject = create(null);139for (const [property, value] of entries(object)) {140const isPropertyExist = objectHasOwnProperty(object, property);141if (isPropertyExist) {142if (Array.isArray(value)) {143newObject[property] = cleanArray(value);144} else if (value && typeof value === 'object' && value.constructor === Object) {145newObject[property] = clone(value);146} else {147newObject[property] = value;148}149}150}151return newObject;152}153154/**155* This method automatically checks if the prop is function or getter and behaves accordingly.156*157* @param {Object} object - The object to look up the getter function in its prototype chain.158* @param {String} prop - The property name for which to find the getter function.159* @returns {Function} The getter function found in the prototype chain or a fallback function.160*/161function lookupGetter(object, prop) {162while (object !== null) {163const desc = getOwnPropertyDescriptor(object, prop);164if (desc) {165if (desc.get) {166return unapply(desc.get);167}168if (typeof desc.value === 'function') {169return unapply(desc.value);170}171}172object = getPrototypeOf(object);173}174function fallbackValue() {175return null;176}177return fallbackValue;178}179180const 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']);181182// SVG183const 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']);184const 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']);185186// 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.190const 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']);191const 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']);192193// Similarly to SVG, we want to know all MathML elements,194// even those that we disallow by default.195const 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', 'popover', 'popovertarget', 'popovertargetaction', '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', 'wrap', 'xmlns', 'slot']);199const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', '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', 'exponent', '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', 'intercept', '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', 'slope', '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', 'tablevalues', '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']);202203// eslint-disable-next-line unicorn/better-regex204const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode205const 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-escape208const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape209const 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-escape210);211const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);212const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex213);214const DOCTYPE_NAME = seal(/^html$/i);215const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);216217var EXPRESSIONS = /*#__PURE__*/Object.freeze({218__proto__: null,219MUSTACHE_EXPR: MUSTACHE_EXPR,220ERB_EXPR: ERB_EXPR,221TMPLIT_EXPR: TMPLIT_EXPR,222DATA_ATTR: DATA_ATTR,223ARIA_ATTR: ARIA_ATTR,224IS_ALLOWED_URI: IS_ALLOWED_URI,225IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,226ATTR_WHITESPACE: ATTR_WHITESPACE,227DOCTYPE_NAME: DOCTYPE_NAME,228CUSTOM_ELEMENT: CUSTOM_ELEMENT229});230231// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType232const NODE_TYPE = {233element: 1,234attribute: 2,235text: 3,236cdataSection: 4,237entityReference: 5,238// Deprecated239entityNode: 6,240// Deprecated241progressingInstruction: 7,242comment: 8,243document: 9,244documentType: 10,245documentFragment: 11,246notation: 12 // Deprecated247};248const getGlobal = function getGlobal() {249return typeof window === 'undefined' ? null : window;250};251252/**253* Creates a no-op policy for internal use only.254* Don't export this function outside this module!255* @param {TrustedTypePolicyFactory} trustedTypes The policy factory.256* @param {HTMLScriptElement} purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).257* @return {TrustedTypePolicy} The policy created (or null, if Trusted Types258* are not supported or creating the policy failed).259*/260const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {261if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {262return null;263}264265// Allow the callers to control the unique policy name266// by adding a data-tt-policy-suffix to the script element with the DOMPurify.267// Policy creation with duplicate names throws in Trusted Types.268let suffix = null;269const ATTR_NAME = 'data-tt-policy-suffix';270if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {271suffix = purifyHostElement.getAttribute(ATTR_NAME);272}273const policyName = 'dompurify' + (suffix ? '#' + suffix : '');274try {275return trustedTypes.createPolicy(policyName, {276createHTML(html) {277return html;278},279createScriptURL(scriptUrl) {280return scriptUrl;281}282});283} catch (_) {284// Policy creation failed (most likely another DOMPurify script has285// already run). Skip creating the policy, as this will only cause errors286// if TT are enforced.287console.warn('TrustedTypes policy ' + policyName + ' could not be created.');288return null;289}290};291function createDOMPurify() {292let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();293const DOMPurify = root => createDOMPurify(root);294295/**296* Version label, exposed for easier checks297* if DOMPurify is up to date or not298*/299DOMPurify.version = '3.1.7';300301/**302* Array of elements that DOMPurify removed during sanitation.303* Empty if nothing was removed.304*/305DOMPurify.removed = [];306if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document) {307// Not running in a browser, provide a factory function308// so that you can pass your own Window309DOMPurify.isSupported = false;310return DOMPurify;311}312let {313document314} = window;315const originalDocument = document;316const currentScript = originalDocument.currentScript;317const {318DocumentFragment,319HTMLTemplateElement,320Node,321Element,322NodeFilter,323NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,324HTMLFormElement,325DOMParser,326trustedTypes327} = window;328const ElementPrototype = Element.prototype;329const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');330const remove = lookupGetter(ElementPrototype, 'remove');331const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');332const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');333const getParentNode = lookupGetter(ElementPrototype, 'parentNode');334335// As per issue #47, the web-components registry is inherited by a336// new document created via createHTMLDocument. As per the spec337// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)338// a new empty registry is used when creating a template contents owner339// document, so we use that as our parent document to ensure nothing340// is inherited.341if (typeof HTMLTemplateElement === 'function') {342const template = document.createElement('template');343if (template.content && template.content.ownerDocument) {344document = template.content.ownerDocument;345}346}347let trustedTypesPolicy;348let emptyHTML = '';349const {350implementation,351createNodeIterator,352createDocumentFragment,353getElementsByTagName354} = document;355const {356importNode357} = originalDocument;358let hooks = {};359360/**361* Expose whether this browser supports running the full DOMPurify.362*/363DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;364const {365MUSTACHE_EXPR,366ERB_EXPR,367TMPLIT_EXPR,368DATA_ATTR,369ARIA_ATTR,370IS_SCRIPT_OR_DATA,371ATTR_WHITESPACE,372CUSTOM_ELEMENT373} = EXPRESSIONS;374let {375IS_ALLOWED_URI: IS_ALLOWED_URI$1376} = EXPRESSIONS;377378/**379* We consider the elements and attributes below to be safe. Ideally380* don't add any new ones but feel free to remove unwanted ones.381*/382383/* allowed element names */384let ALLOWED_TAGS = null;385const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);386387/* Allowed attribute names */388let ALLOWED_ATTR = null;389const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);390391/*392* Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.393* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)394* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)395* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.396*/397let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {398tagNameCheck: {399writable: true,400configurable: false,401enumerable: true,402value: null403},404attributeNameCheck: {405writable: true,406configurable: false,407enumerable: true,408value: null409},410allowCustomizedBuiltInElements: {411writable: true,412configurable: false,413enumerable: true,414value: false415}416}));417418/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */419let FORBID_TAGS = null;420421/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */422let FORBID_ATTR = null;423424/* Decide if ARIA attributes are okay */425let ALLOW_ARIA_ATTR = true;426427/* Decide if custom data attributes are okay */428let ALLOW_DATA_ATTR = true;429430/* Decide if unknown protocols are okay */431let ALLOW_UNKNOWN_PROTOCOLS = false;432433/* Decide if self-closing tags in attributes are allowed.434* Usually removed due to a mXSS issue in jQuery 3.0 */435let ALLOW_SELF_CLOSE_IN_ATTR = true;436437/* Output should be safe for common template engines.438* This means, DOMPurify removes data attributes, mustaches and ERB439*/440let SAFE_FOR_TEMPLATES = false;441442/* Output should be safe even for XML used within HTML and alike.443* This means, DOMPurify removes comments when containing risky content.444*/445let SAFE_FOR_XML = true;446447/* Decide if document with <html>... should be returned */448let WHOLE_DOCUMENT = false;449450/* Track whether config is already set on this instance of DOMPurify. */451let SET_CONFIG = false;452453/* Decide if all elements (e.g. style, script) must be children of454* document.body. By default, browsers might move them to document.head */455let FORCE_BODY = false;456457/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html458* string (or a TrustedHTML object if Trusted Types are supported).459* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead460*/461let RETURN_DOM = false;462463/* Decide if a DOM `DocumentFragment` should be returned, instead of a html464* string (or a TrustedHTML object if Trusted Types are supported) */465let RETURN_DOM_FRAGMENT = false;466467/* Try to return a Trusted Type object instead of a string, return a string in468* case Trusted Types are not supported */469let RETURN_TRUSTED_TYPE = false;470471/* Output should be free from DOM clobbering attacks?472* This sanitizes markups named with colliding, clobberable built-in DOM APIs.473*/474let SANITIZE_DOM = true;475476/* Achieve full DOM Clobbering protection by isolating the namespace of named477* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.478*479* HTML/DOM spec rules that enable DOM Clobbering:480* - Named Access on Window (§7.3.3)481* - DOM Tree Accessors (§3.1.5)482* - Form Element Parent-Child Relations (§4.10.3)483* - Iframe srcdoc / Nested WindowProxies (§4.8.5)484* - HTMLCollection (§4.2.10.2)485*486* Namespace isolation is implemented by prefixing `id` and `name` attributes487* with a constant string, i.e., `user-content-`488*/489let SANITIZE_NAMED_PROPS = false;490const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';491492/* Keep element content when removing element? */493let KEEP_CONTENT = true;494495/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead496* of importing it into a new Document and returning a sanitized copy */497let IN_PLACE = false;498499/* Allow usage of profiles like html, svg and mathMl */500let USE_PROFILES = {};501502/* Tags to ignore content of when KEEP_CONTENT is true */503let FORBID_CONTENTS = null;504const 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']);505506/* Tags that are safe for data: URIs */507let DATA_URI_TAGS = null;508const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);509510/* Attributes safe for values like "javascript:" */511let URI_SAFE_ATTRIBUTES = null;512const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);513const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';514const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';515const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';516/* Document namespace */517let NAMESPACE = HTML_NAMESPACE;518let IS_EMPTY_INPUT = false;519520/* Allowed XHTML+XML namespaces */521let ALLOWED_NAMESPACES = null;522const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);523524/* Parsing of strict XHTML documents */525let PARSER_MEDIA_TYPE = null;526const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];527const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';528let transformCaseFunc = null;529530/* Keep a reference to config to pass to hooks */531let CONFIG = null;532533/* Ideally, do not touch anything below this line */534/* ______________________________________________ */535536const formElement = document.createElement('form');537const isRegexOrFunction = function isRegexOrFunction(testValue) {538return testValue instanceof RegExp || testValue instanceof Function;539};540541/**542* _parseConfig543*544* @param {Object} cfg optional config literal545*/546// eslint-disable-next-line complexity547const _parseConfig = function _parseConfig() {548let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};549if (CONFIG && CONFIG === cfg) {550return;551}552553/* Shield configuration object from tampering */554if (!cfg || typeof cfg !== 'object') {555cfg = {};556}557558/* Shield configuration object from prototype pollution */559cfg = clone(cfg);560PARSER_MEDIA_TYPE =561// eslint-disable-next-line unicorn/prefer-includes562SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;563564// HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.565transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;566567/* Set configuration parameters */568ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;569ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;570ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;571URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES),572// eslint-disable-line indent573cfg.ADD_URI_SAFE_ATTR,574// eslint-disable-line indent575transformCaseFunc // eslint-disable-line indent576) // eslint-disable-line indent577: DEFAULT_URI_SAFE_ATTRIBUTES;578DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS),579// eslint-disable-line indent580cfg.ADD_DATA_URI_TAGS,581// eslint-disable-line indent582transformCaseFunc // eslint-disable-line indent583) // eslint-disable-line indent584: DEFAULT_DATA_URI_TAGS;585FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;586FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};587FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};588USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;589ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true590ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true591ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false592ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true593SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false594SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true595WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false596RETURN_DOM = cfg.RETURN_DOM || false; // Default false597RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false598RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false599FORCE_BODY = cfg.FORCE_BODY || false; // Default false600SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true601SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false602KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true603IN_PLACE = cfg.IN_PLACE || false; // Default false604IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;605NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;606CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};607if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {608CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;609}610if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {611CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;612}613if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {614CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;615}616if (SAFE_FOR_TEMPLATES) {617ALLOW_DATA_ATTR = false;618}619if (RETURN_DOM_FRAGMENT) {620RETURN_DOM = true;621}622623/* Parse profile info */624if (USE_PROFILES) {625ALLOWED_TAGS = addToSet({}, text);626ALLOWED_ATTR = [];627if (USE_PROFILES.html === true) {628addToSet(ALLOWED_TAGS, html$1);629addToSet(ALLOWED_ATTR, html);630}631if (USE_PROFILES.svg === true) {632addToSet(ALLOWED_TAGS, svg$1);633addToSet(ALLOWED_ATTR, svg);634addToSet(ALLOWED_ATTR, xml);635}636if (USE_PROFILES.svgFilters === true) {637addToSet(ALLOWED_TAGS, svgFilters);638addToSet(ALLOWED_ATTR, svg);639addToSet(ALLOWED_ATTR, xml);640}641if (USE_PROFILES.mathMl === true) {642addToSet(ALLOWED_TAGS, mathMl$1);643addToSet(ALLOWED_ATTR, mathMl);644addToSet(ALLOWED_ATTR, xml);645}646}647648/* Merge configuration parameters */649if (cfg.ADD_TAGS) {650if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {651ALLOWED_TAGS = clone(ALLOWED_TAGS);652}653addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);654}655if (cfg.ADD_ATTR) {656if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {657ALLOWED_ATTR = clone(ALLOWED_ATTR);658}659addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);660}661if (cfg.ADD_URI_SAFE_ATTR) {662addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);663}664if (cfg.FORBID_CONTENTS) {665if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {666FORBID_CONTENTS = clone(FORBID_CONTENTS);667}668addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);669}670671/* Add #text in case KEEP_CONTENT is set to true */672if (KEEP_CONTENT) {673ALLOWED_TAGS['#text'] = true;674}675676/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */677if (WHOLE_DOCUMENT) {678addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);679}680681/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */682if (ALLOWED_TAGS.table) {683addToSet(ALLOWED_TAGS, ['tbody']);684delete FORBID_TAGS.tbody;685}686if (cfg.TRUSTED_TYPES_POLICY) {687if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {688throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');689}690if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {691throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');692}693694// Overwrite existing TrustedTypes policy.695trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;696697// Sign local variables required by `sanitize`.698emptyHTML = trustedTypesPolicy.createHTML('');699} else {700// Uninitialized policy, attempt to initialize the internal dompurify policy.701if (trustedTypesPolicy === undefined) {702trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);703}704705// If creating the internal policy succeeded sign internal variables.706if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {707emptyHTML = trustedTypesPolicy.createHTML('');708}709}710711// Prevent further manipulation of configuration.712// Not available in IE8, Safari 5, etc.713if (freeze) {714freeze(cfg);715}716CONFIG = cfg;717};718const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);719const HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);720721// Certain elements are allowed in both SVG and HTML722// namespace. We need to specify them explicitly723// so that they don't get erroneously deleted from724// HTML namespace.725const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);726727/* Keep track of all possible SVG and MathML tags728* so that we can perform the namespace checks729* correctly. */730const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);731const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);732733/**734* @param {Element} element a DOM element whose namespace is being checked735* @returns {boolean} Return false if the element has a736* namespace that a spec-compliant parser would never737* return. Return true otherwise.738*/739const _checkValidNamespace = function _checkValidNamespace(element) {740let parent = getParentNode(element);741742// In JSDOM, if we're inside shadow DOM, then parentNode743// can be null. We just simulate parent in this case.744if (!parent || !parent.tagName) {745parent = {746namespaceURI: NAMESPACE,747tagName: 'template'748};749}750const tagName = stringToLowerCase(element.tagName);751const parentTagName = stringToLowerCase(parent.tagName);752if (!ALLOWED_NAMESPACES[element.namespaceURI]) {753return false;754}755if (element.namespaceURI === SVG_NAMESPACE) {756// The only way to switch from HTML namespace to SVG757// is via <svg>. If it happens via any other tag, then758// it should be killed.759if (parent.namespaceURI === HTML_NAMESPACE) {760return tagName === 'svg';761}762763// The only way to switch from MathML to SVG is via`764// svg if parent is either <annotation-xml> or MathML765// text integration points.766if (parent.namespaceURI === MATHML_NAMESPACE) {767return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);768}769770// We only allow elements that are defined in SVG771// spec. All others are disallowed in SVG namespace.772return Boolean(ALL_SVG_TAGS[tagName]);773}774if (element.namespaceURI === MATHML_NAMESPACE) {775// The only way to switch from HTML namespace to MathML776// is via <math>. If it happens via any other tag, then777// it should be killed.778if (parent.namespaceURI === HTML_NAMESPACE) {779return tagName === 'math';780}781782// The only way to switch from SVG to MathML is via783// <math> and HTML integration points784if (parent.namespaceURI === SVG_NAMESPACE) {785return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];786}787788// We only allow elements that are defined in MathML789// spec. All others are disallowed in MathML namespace.790return Boolean(ALL_MATHML_TAGS[tagName]);791}792if (element.namespaceURI === HTML_NAMESPACE) {793// The only way to switch from SVG to HTML is via794// HTML integration points, and from MathML to HTML795// is via MathML text integration points796if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {797return false;798}799if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {800return false;801}802803// We disallow tags that are specific for MathML804// or SVG and should never appear in HTML namespace805return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);806}807808// For XHTML and XML documents that support custom namespaces809if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {810return true;811}812813// The code should never reach this place (this means814// that the element somehow got namespace that is not815// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).816// Return false just in case.817return false;818};819820/**821* _forceRemove822*823* @param {Node} node a DOM node824*/825const _forceRemove = function _forceRemove(node) {826arrayPush(DOMPurify.removed, {827element: node828});829try {830// eslint-disable-next-line unicorn/prefer-dom-node-remove831getParentNode(node).removeChild(node);832} catch (_) {833remove(node);834}835};836837/**838* _removeAttribute839*840* @param {String} name an Attribute name841* @param {Node} node a DOM node842*/843const _removeAttribute = function _removeAttribute(name, node) {844try {845arrayPush(DOMPurify.removed, {846attribute: node.getAttributeNode(name),847from: node848});849} catch (_) {850arrayPush(DOMPurify.removed, {851attribute: null,852from: node853});854}855node.removeAttribute(name);856857// We void attribute values for unremovable "is"" attributes858if (name === 'is' && !ALLOWED_ATTR[name]) {859if (RETURN_DOM || RETURN_DOM_FRAGMENT) {860try {861_forceRemove(node);862} catch (_) {}863} else {864try {865node.setAttribute(name, '');866} catch (_) {}867}868}869};870871/**872* _initDocument873*874* @param {String} dirty a string of dirty markup875* @return {Document} a DOM, filled with the dirty markup876*/877const _initDocument = function _initDocument(dirty) {878/* Create a HTML document */879let doc = null;880let leadingWhitespace = null;881if (FORCE_BODY) {882dirty = '<remove></remove>' + dirty;883} else {884/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */885const matches = stringMatch(dirty, /^[\r\n\t ]+/);886leadingWhitespace = matches && matches[0];887}888if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {889// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)890dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';891}892const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;893/*894* Use the DOMParser API by default, fallback later if needs be895* DOMParser not work for svg when has multiple root element.896*/897if (NAMESPACE === HTML_NAMESPACE) {898try {899doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);900} catch (_) {}901}902903/* Use createHTMLDocument in case DOMParser is not available */904if (!doc || !doc.documentElement) {905doc = implementation.createDocument(NAMESPACE, 'template', null);906try {907doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;908} catch (_) {909// Syntax error if dirtyPayload is invalid xml910}911}912const body = doc.body || doc.documentElement;913if (dirty && leadingWhitespace) {914body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);915}916917/* Work on whole document or just its body */918if (NAMESPACE === HTML_NAMESPACE) {919return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];920}921return WHOLE_DOCUMENT ? doc.documentElement : body;922};923924/**925* Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.926*927* @param {Node} root The root element or node to start traversing on.928* @return {NodeIterator} The created NodeIterator929*/930const _createNodeIterator = function _createNodeIterator(root) {931return createNodeIterator.call(root.ownerDocument || root, root,932// eslint-disable-next-line no-bitwise933NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);934};935936/**937* _isClobbered938*939* @param {Node} elm element to check for clobbering attacks940* @return {Boolean} true if clobbered, false if safe941*/942const _isClobbered = function _isClobbered(elm) {943return 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');944};945946/**947* Checks whether the given object is a DOM node.948*949* @param {Node} object object to check whether it's a DOM node950* @return {Boolean} true is object is a DOM node951*/952const _isNode = function _isNode(object) {953return typeof Node === 'function' && object instanceof Node;954};955956/**957* _executeHook958* Execute user configurable hooks959*960* @param {String} entryPoint Name of the hook's entry point961* @param {Node} currentNode node to work on with the hook962* @param {Object} data additional hook parameters963*/964const _executeHook = function _executeHook(entryPoint, currentNode, data) {965if (!hooks[entryPoint]) {966return;967}968arrayForEach(hooks[entryPoint], hook => {969hook.call(DOMPurify, currentNode, data, CONFIG);970});971};972973/**974* _sanitizeElements975*976* @protect nodeName977* @protect textContent978* @protect removeChild979*980* @param {Node} currentNode to check for permission to exist981* @return {Boolean} true if node was killed, false if left alive982*/983const _sanitizeElements = function _sanitizeElements(currentNode) {984let content = null;985986/* Execute a hook if present */987_executeHook('beforeSanitizeElements', currentNode, null);988989/* Check if element is clobbered or can clobber */990if (_isClobbered(currentNode)) {991_forceRemove(currentNode);992return true;993}994995/* Now let's check the element's type and name */996const tagName = transformCaseFunc(currentNode.nodeName);997998/* Execute a hook if present */999_executeHook('uponSanitizeElement', currentNode, {1000tagName,1001allowedTags: ALLOWED_TAGS1002});10031004/* Detect mXSS attempts abusing namespace confusion */1005if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {1006_forceRemove(currentNode);1007return true;1008}10091010/* Remove any occurrence of processing instructions */1011if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {1012_forceRemove(currentNode);1013return true;1014}10151016/* Remove any kind of possibly harmful comments */1017if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {1018_forceRemove(currentNode);1019return true;1020}10211022/* Remove element if anything forbids its presence */1023if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {1024/* Check if we have a custom element to handle */1025if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {1026if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {1027return false;1028}1029if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {1030return false;1031}1032}10331034/* Keep content except for bad-listed elements */1035if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {1036const parentNode = getParentNode(currentNode) || currentNode.parentNode;1037const childNodes = getChildNodes(currentNode) || currentNode.childNodes;1038if (childNodes && parentNode) {1039const childCount = childNodes.length;1040for (let i = childCount - 1; i >= 0; --i) {1041const childClone = cloneNode(childNodes[i], true);1042childClone.__removalCount = (currentNode.__removalCount || 0) + 1;1043parentNode.insertBefore(childClone, getNextSibling(currentNode));1044}1045}1046}1047_forceRemove(currentNode);1048return true;1049}10501051/* Check whether element has a valid namespace */1052if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {1053_forceRemove(currentNode);1054return true;1055}10561057/* Make sure that older browsers don't get fallback-tag mXSS */1058if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {1059_forceRemove(currentNode);1060return true;1061}10621063/* Sanitize element content to be template-safe */1064if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {1065/* Get the element's text content */1066content = currentNode.textContent;1067arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1068content = stringReplace(content, expr, ' ');1069});1070if (currentNode.textContent !== content) {1071arrayPush(DOMPurify.removed, {1072element: currentNode.cloneNode()1073});1074currentNode.textContent = content;1075}1076}10771078/* Execute a hook if present */1079_executeHook('afterSanitizeElements', currentNode, null);1080return false;1081};10821083/**1084* _isValidAttribute1085*1086* @param {string} lcTag Lowercase tag name of containing element.1087* @param {string} lcName Lowercase attribute name.1088* @param {string} value Attribute value.1089* @return {Boolean} Returns true if `value` is valid, otherwise false.1090*/1091// eslint-disable-next-line complexity1092const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {1093/* Make sure attribute cannot clobber */1094if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {1095return false;1096}10971098/* Allow valid data-* attributes: At least one character after "-"1099(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)1100XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)1101We don't need to check the value; it's always URI safe. */1102if (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]) {1103if (1104// First condition does a very basic check if a) it's basically a valid custom element tagname AND1105// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck1106// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck1107_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)) ||1108// Alternative, second condition checks if it's an `is`-attribute, AND1109// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck1110lcName === '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 {1111return false;1112}1113/* Check value is safe. First, is attr inert? If so, is safe */1114} 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) {1115return false;1116} else ;1117return true;1118};11191120/**1121* _isBasicCustomElement1122* checks if at least one dash is included in tagName, and it's not the first char1123* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name1124*1125* @param {string} tagName name of the tag of the node to sanitize1126* @returns {boolean} Returns true if the tag name meets the basic criteria for a custom element, otherwise false.1127*/1128const _isBasicCustomElement = function _isBasicCustomElement(tagName) {1129return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);1130};11311132/**1133* _sanitizeAttributes1134*1135* @protect attributes1136* @protect nodeName1137* @protect removeAttribute1138* @protect setAttribute1139*1140* @param {Node} currentNode to sanitize1141*/1142const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {1143/* Execute a hook if present */1144_executeHook('beforeSanitizeAttributes', currentNode, null);1145const {1146attributes1147} = currentNode;11481149/* Check if we have attributes; if not we might have a text node */1150if (!attributes) {1151return;1152}1153const hookEvent = {1154attrName: '',1155attrValue: '',1156keepAttr: true,1157allowedAttributes: ALLOWED_ATTR1158};1159let l = attributes.length;11601161/* Go backwards over all attributes; safely remove bad ones */1162while (l--) {1163const attr = attributes[l];1164const {1165name,1166namespaceURI,1167value: attrValue1168} = attr;1169const lcName = transformCaseFunc(name);1170let value = name === 'value' ? attrValue : stringTrim(attrValue);11711172/* Execute a hook if present */1173hookEvent.attrName = lcName;1174hookEvent.attrValue = value;1175hookEvent.keepAttr = true;1176hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set1177_executeHook('uponSanitizeAttribute', currentNode, hookEvent);1178value = hookEvent.attrValue;11791180/* Did the hooks approve of the attribute? */1181if (hookEvent.forceKeepAttr) {1182continue;1183}11841185/* Remove attribute */1186_removeAttribute(name, currentNode);11871188/* Did the hooks approve of the attribute? */1189if (!hookEvent.keepAttr) {1190continue;1191}11921193/* Work around a security issue in jQuery 3.0 */1194if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {1195_removeAttribute(name, currentNode);1196continue;1197}11981199/* Sanitize attribute content to be template-safe */1200if (SAFE_FOR_TEMPLATES) {1201arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1202value = stringReplace(value, expr, ' ');1203});1204}12051206/* Is `value` valid for this attribute? */1207const lcTag = transformCaseFunc(currentNode.nodeName);1208if (!_isValidAttribute(lcTag, lcName, value)) {1209continue;1210}12111212/* Full DOM Clobbering protection via namespace isolation,1213* Prefix id and name attributes with `user-content-`1214*/1215if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {1216// Remove the attribute with this value1217_removeAttribute(name, currentNode);12181219// Prefix the value and later re-create the attribute with the sanitized value1220value = SANITIZE_NAMED_PROPS_PREFIX + value;1221}12221223/* Work around a security issue with comments inside attributes */1224if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) {1225_removeAttribute(name, currentNode);1226continue;1227}12281229/* Handle attributes that require Trusted Types */1230if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {1231if (namespaceURI) ; else {1232switch (trustedTypes.getAttributeType(lcTag, lcName)) {1233case 'TrustedHTML':1234{1235value = trustedTypesPolicy.createHTML(value);1236break;1237}1238case 'TrustedScriptURL':1239{1240value = trustedTypesPolicy.createScriptURL(value);1241break;1242}1243}1244}1245}12461247/* Handle invalid data-* attribute set by try-catching it */1248try {1249if (namespaceURI) {1250currentNode.setAttributeNS(namespaceURI, name, value);1251} else {1252/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */1253currentNode.setAttribute(name, value);1254}1255if (_isClobbered(currentNode)) {1256_forceRemove(currentNode);1257} else {1258arrayPop(DOMPurify.removed);1259}1260} catch (_) {}1261}12621263/* Execute a hook if present */1264_executeHook('afterSanitizeAttributes', currentNode, null);1265};12661267/**1268* _sanitizeShadowDOM1269*1270* @param {DocumentFragment} fragment to iterate over recursively1271*/1272const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {1273let shadowNode = null;1274const shadowIterator = _createNodeIterator(fragment);12751276/* Execute a hook if present */1277_executeHook('beforeSanitizeShadowDOM', fragment, null);1278while (shadowNode = shadowIterator.nextNode()) {1279/* Execute a hook if present */1280_executeHook('uponSanitizeShadowNode', shadowNode, null);12811282/* Sanitize tags and elements */1283if (_sanitizeElements(shadowNode)) {1284continue;1285}12861287/* Deep shadow DOM detected */1288if (shadowNode.content instanceof DocumentFragment) {1289_sanitizeShadowDOM(shadowNode.content);1290}12911292/* Check attributes, sanitize if necessary */1293_sanitizeAttributes(shadowNode);1294}12951296/* Execute a hook if present */1297_executeHook('afterSanitizeShadowDOM', fragment, null);1298};12991300/**1301* Sanitize1302* Public method providing core sanitation functionality1303*1304* @param {String|Node} dirty string or DOM node1305* @param {Object} cfg object1306*/1307// eslint-disable-next-line complexity1308DOMPurify.sanitize = function (dirty) {1309let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};1310let body = null;1311let importedNode = null;1312let currentNode = null;1313let returnNode = null;1314/* Make sure we have a string to sanitize.1315DO NOT return early, as this will return the wrong type if1316the user has requested a DOM object rather than a string */1317IS_EMPTY_INPUT = !dirty;1318if (IS_EMPTY_INPUT) {1319dirty = '<!-->';1320}13211322/* Stringify, in case dirty is an object */1323if (typeof dirty !== 'string' && !_isNode(dirty)) {1324if (typeof dirty.toString === 'function') {1325dirty = dirty.toString();1326if (typeof dirty !== 'string') {1327throw typeErrorCreate('dirty is not a string, aborting');1328}1329} else {1330throw typeErrorCreate('toString is not a function');1331}1332}13331334/* Return dirty HTML if DOMPurify cannot run */1335if (!DOMPurify.isSupported) {1336return dirty;1337}13381339/* Assign config vars */1340if (!SET_CONFIG) {1341_parseConfig(cfg);1342}13431344/* Clean up removed elements */1345DOMPurify.removed = [];13461347/* Check if dirty is correctly typed for IN_PLACE */1348if (typeof dirty === 'string') {1349IN_PLACE = false;1350}1351if (IN_PLACE) {1352/* Do some early pre-sanitization to avoid unsafe root nodes */1353if (dirty.nodeName) {1354const tagName = transformCaseFunc(dirty.nodeName);1355if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {1356throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');1357}1358}1359} else if (dirty instanceof Node) {1360/* If dirty is a DOM element, append to an empty document to avoid1361elements being stripped by the parser */1362body = _initDocument('<!---->');1363importedNode = body.ownerDocument.importNode(dirty, true);1364if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {1365/* Node is already a body, use as is */1366body = importedNode;1367} else if (importedNode.nodeName === 'HTML') {1368body = importedNode;1369} else {1370// eslint-disable-next-line unicorn/prefer-dom-node-append1371body.appendChild(importedNode);1372}1373} else {1374/* Exit directly if we have nothing to do */1375if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&1376// eslint-disable-next-line unicorn/prefer-includes1377dirty.indexOf('<') === -1) {1378return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;1379}13801381/* Initialize the document to work on */1382body = _initDocument(dirty);13831384/* Check we have a DOM node from the data */1385if (!body) {1386return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';1387}1388}13891390/* Remove first element node (ours) if FORCE_BODY is set */1391if (body && FORCE_BODY) {1392_forceRemove(body.firstChild);1393}13941395/* Get node iterator */1396const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);13971398/* Now start iterating over the created document */1399while (currentNode = nodeIterator.nextNode()) {1400/* Sanitize tags and elements */1401if (_sanitizeElements(currentNode)) {1402continue;1403}14041405/* Shadow DOM detected, sanitize it */1406if (currentNode.content instanceof DocumentFragment) {1407_sanitizeShadowDOM(currentNode.content);1408}14091410/* Check attributes, sanitize if necessary */1411_sanitizeAttributes(currentNode);1412}14131414/* If we sanitized `dirty` in-place, return it. */1415if (IN_PLACE) {1416return dirty;1417}14181419/* Return sanitized string or DOM */1420if (RETURN_DOM) {1421if (RETURN_DOM_FRAGMENT) {1422returnNode = createDocumentFragment.call(body.ownerDocument);1423while (body.firstChild) {1424// eslint-disable-next-line unicorn/prefer-dom-node-append1425returnNode.appendChild(body.firstChild);1426}1427} else {1428returnNode = body;1429}1430if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {1431/*1432AdoptNode() is not used because internal state is not reset1433(e.g. the past names map of a HTMLFormElement), this is safe1434in theory but we would rather not risk another attack vector.1435The state that is cloned by importNode() is explicitly defined1436by the specs.1437*/1438returnNode = importNode.call(originalDocument, returnNode, true);1439}1440return returnNode;1441}1442let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;14431444/* Serialize doctype if allowed */1445if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {1446serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;1447}14481449/* Sanitize final string template-safe */1450if (SAFE_FOR_TEMPLATES) {1451arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1452serializedHTML = stringReplace(serializedHTML, expr, ' ');1453});1454}1455return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;1456};14571458/**1459* Public method to set the configuration once1460* setConfig1461*1462* @param {Object} cfg configuration object1463*/1464DOMPurify.setConfig = function () {1465let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};1466_parseConfig(cfg);1467SET_CONFIG = true;1468};14691470/**1471* Public method to remove the configuration1472* clearConfig1473*1474*/1475DOMPurify.clearConfig = function () {1476CONFIG = null;1477SET_CONFIG = false;1478};14791480/**1481* Public method to check if an attribute value is valid.1482* Uses last set config, if any. Otherwise, uses config defaults.1483* isValidAttribute1484*1485* @param {String} tag Tag name of containing element.1486* @param {String} attr Attribute name.1487* @param {String} value Attribute value.1488* @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.1489*/1490DOMPurify.isValidAttribute = function (tag, attr, value) {1491/* Initialize shared config vars if necessary. */1492if (!CONFIG) {1493_parseConfig({});1494}1495const lcTag = transformCaseFunc(tag);1496const lcName = transformCaseFunc(attr);1497return _isValidAttribute(lcTag, lcName, value);1498};14991500/**1501* AddHook1502* Public method to add DOMPurify hooks1503*1504* @param {String} entryPoint entry point for the hook to add1505* @param {Function} hookFunction function to execute1506*/1507DOMPurify.addHook = function (entryPoint, hookFunction) {1508if (typeof hookFunction !== 'function') {1509return;1510}1511hooks[entryPoint] = hooks[entryPoint] || [];1512arrayPush(hooks[entryPoint], hookFunction);1513};15141515/**1516* RemoveHook1517* Public method to remove a DOMPurify hook at a given entryPoint1518* (pops it from the stack of hooks if more are present)1519*1520* @param {String} entryPoint entry point for the hook to remove1521* @return {Function} removed(popped) hook1522*/1523DOMPurify.removeHook = function (entryPoint) {1524if (hooks[entryPoint]) {1525return arrayPop(hooks[entryPoint]);1526}1527};15281529/**1530* RemoveHooks1531* Public method to remove all DOMPurify hooks at a given entryPoint1532*1533* @param {String} entryPoint entry point for the hooks to remove1534*/1535DOMPurify.removeHooks = function (entryPoint) {1536if (hooks[entryPoint]) {1537hooks[entryPoint] = [];1538}1539};15401541/**1542* RemoveAllHooks1543* Public method to remove all DOMPurify hooks1544*/1545DOMPurify.removeAllHooks = function () {1546hooks = {};1547};1548return DOMPurify;1549}1550var purify = createDOMPurify();15511552export { purify as default };1553//# sourceMappingURL=purify.es.mjs.map15541555