Path: blob/main/src/vs/base/browser/dompurify/dompurify.js
5222 views
/*! @license DOMPurify 3.2.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.2.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(func, thisArg) {30for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {31args[_key - 2] = arguments[_key];32}33return func.apply(thisArg, args);34};35}36if (!construct) {37construct = function construct(Func) {38for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {39args[_key2 - 1] = arguments[_key2];40}41return new Func(...args);42};43}44const arrayForEach = unapply(Array.prototype.forEach);45const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);46const arrayPop = unapply(Array.prototype.pop);47const arrayPush = unapply(Array.prototype.push);48const arraySplice = unapply(Array.prototype.splice);49const stringToLowerCase = unapply(String.prototype.toLowerCase);50const stringToString = unapply(String.prototype.toString);51const stringMatch = unapply(String.prototype.match);52const stringReplace = unapply(String.prototype.replace);53const stringIndexOf = unapply(String.prototype.indexOf);54const stringTrim = unapply(String.prototype.trim);55const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);56const regExpTest = unapply(RegExp.prototype.test);57const typeErrorCreate = unconstruct(TypeError);58/**59* Creates a new function that calls the given function with a specified thisArg and arguments.60*61* @param func - The function to be wrapped and called.62* @returns A new function that calls the given function with a specified thisArg and arguments.63*/64function unapply(func) {65return function (thisArg) {66if (thisArg instanceof RegExp) {67thisArg.lastIndex = 0;68}69for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {70args[_key3 - 1] = arguments[_key3];71}72return apply(func, thisArg, args);73};74}75/**76* Creates a new function that constructs an instance of the given constructor function with the provided arguments.77*78* @param func - The constructor function to be wrapped and called.79* @returns A new function that constructs an instance of the given constructor function with the provided arguments.80*/81function unconstruct(Func) {82return function () {83for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {84args[_key4] = arguments[_key4];85}86return construct(Func, args);87};88}89/**90* Add properties to a lookup table91*92* @param set - The set to which elements will be added.93* @param array - The array containing elements to be added to the set.94* @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.95* @returns The modified set with added elements.96*/97function addToSet(set, array) {98let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;99if (setPrototypeOf) {100// Make 'in' and truthy checks like Boolean(set.constructor)101// independent of any properties defined on Object.prototype.102// Prevent prototype setters from intercepting set as a this value.103setPrototypeOf(set, null);104}105let l = array.length;106while (l--) {107let element = array[l];108if (typeof element === 'string') {109const lcElement = transformCaseFunc(element);110if (lcElement !== element) {111// Config presets (e.g. tags.js, attrs.js) are immutable.112if (!isFrozen(array)) {113array[l] = lcElement;114}115element = lcElement;116}117}118set[element] = true;119}120return set;121}122/**123* Clean up an array to harden against CSPP124*125* @param array - The array to be cleaned.126* @returns The cleaned version of the array127*/128function cleanArray(array) {129for (let index = 0; index < array.length; index++) {130const isPropertyExist = objectHasOwnProperty(array, index);131if (!isPropertyExist) {132array[index] = null;133}134}135return array;136}137/**138* Shallow clone an object139*140* @param object - The object to be cloned.141* @returns A new object that copies the original.142*/143function clone(object) {144const newObject = create(null);145for (const [property, value] of entries(object)) {146const isPropertyExist = objectHasOwnProperty(object, property);147if (isPropertyExist) {148if (Array.isArray(value)) {149newObject[property] = cleanArray(value);150} else if (value && typeof value === 'object' && value.constructor === Object) {151newObject[property] = clone(value);152} else {153newObject[property] = value;154}155}156}157return newObject;158}159/**160* This method automatically checks if the prop is function or getter and behaves accordingly.161*162* @param object - The object to look up the getter function in its prototype chain.163* @param prop - The property name for which to find the getter function.164* @returns The getter function found in the prototype chain or a fallback function.165*/166function lookupGetter(object, prop) {167while (object !== null) {168const desc = getOwnPropertyDescriptor(object, prop);169if (desc) {170if (desc.get) {171return unapply(desc.get);172}173if (typeof desc.value === 'function') {174return unapply(desc.value);175}176}177object = getPrototypeOf(object);178}179function fallbackValue() {180return null;181}182return fallbackValue;183}184185const 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', 'search', 'section', 'select', 'shadow', 'slot', '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']);186const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'slot', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);187const 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']);188// List of SVG elements that are disallowed by default.189// We still need to know them so that we can do namespace190// checks properly in case one wants to add them to191// allow-list.192const 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']);193const 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']);194// Similarly to SVG, we want to know all MathML elements,195// even those that we disallow by default.196const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);197const text = freeze(['#text']);198199const 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', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', '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', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);200const 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']);201const 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']);202const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);203204// eslint-disable-next-line unicorn/better-regex205const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode206const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);207const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex208const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape209const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape210const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape211);212const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);213const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex214);215const DOCTYPE_NAME = seal(/^html$/i);216const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);217218var EXPRESSIONS = /*#__PURE__*/Object.freeze({219__proto__: null,220ARIA_ATTR: ARIA_ATTR,221ATTR_WHITESPACE: ATTR_WHITESPACE,222CUSTOM_ELEMENT: CUSTOM_ELEMENT,223DATA_ATTR: DATA_ATTR,224DOCTYPE_NAME: DOCTYPE_NAME,225ERB_EXPR: ERB_EXPR,226IS_ALLOWED_URI: IS_ALLOWED_URI,227IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,228MUSTACHE_EXPR: MUSTACHE_EXPR,229TMPLIT_EXPR: TMPLIT_EXPR230});231232/* eslint-disable @typescript-eslint/indent */233// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType234const NODE_TYPE = {235element: 1,236attribute: 2,237text: 3,238cdataSection: 4,239entityReference: 5,240// Deprecated241entityNode: 6,242// Deprecated243progressingInstruction: 7,244comment: 8,245document: 9,246documentType: 10,247documentFragment: 11,248notation: 12 // Deprecated249};250const getGlobal = function getGlobal() {251return typeof window === 'undefined' ? null : window;252};253/**254* Creates a no-op policy for internal use only.255* Don't export this function outside this module!256* @param trustedTypes The policy factory.257* @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).258* @return The policy created (or null, if Trusted Types259* are not supported or creating the policy failed).260*/261const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {262if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {263return null;264}265// 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};291const _createHooksMap = function _createHooksMap() {292return {293afterSanitizeAttributes: [],294afterSanitizeElements: [],295afterSanitizeShadowDOM: [],296beforeSanitizeAttributes: [],297beforeSanitizeElements: [],298beforeSanitizeShadowDOM: [],299uponSanitizeAttribute: [],300uponSanitizeElement: [],301uponSanitizeShadowNode: []302};303};304function createDOMPurify() {305let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();306const DOMPurify = root => createDOMPurify(root);307DOMPurify.version = '3.2.7';308DOMPurify.removed = [];309if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {310// Not running in a browser, provide a factory function311// so that you can pass your own Window312DOMPurify.isSupported = false;313return DOMPurify;314}315let {316document317} = window;318const originalDocument = document;319const currentScript = originalDocument.currentScript;320const {321DocumentFragment,322HTMLTemplateElement,323Node,324Element,325NodeFilter,326NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,327HTMLFormElement,328DOMParser,329trustedTypes330} = window;331const ElementPrototype = Element.prototype;332const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');333const remove = lookupGetter(ElementPrototype, 'remove');334const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');335const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');336const getParentNode = lookupGetter(ElementPrototype, 'parentNode');337// As per issue #47, the web-components registry is inherited by a338// new document created via createHTMLDocument. As per the spec339// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)340// a new empty registry is used when creating a template contents owner341// document, so we use that as our parent document to ensure nothing342// is inherited.343if (typeof HTMLTemplateElement === 'function') {344const template = document.createElement('template');345if (template.content && template.content.ownerDocument) {346document = template.content.ownerDocument;347}348}349let trustedTypesPolicy;350let emptyHTML = '';351const {352implementation,353createNodeIterator,354createDocumentFragment,355getElementsByTagName356} = document;357const {358importNode359} = originalDocument;360let hooks = _createHooksMap();361/**362* Expose whether this browser supports running the full DOMPurify.363*/364DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;365const {366MUSTACHE_EXPR,367ERB_EXPR,368TMPLIT_EXPR,369DATA_ATTR,370ARIA_ATTR,371IS_SCRIPT_OR_DATA,372ATTR_WHITESPACE,373CUSTOM_ELEMENT374} = EXPRESSIONS;375let {376IS_ALLOWED_URI: IS_ALLOWED_URI$1377} = EXPRESSIONS;378/**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*/382/* allowed element names */383let ALLOWED_TAGS = null;384const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);385/* Allowed attribute names */386let ALLOWED_ATTR = null;387const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);388/*389* Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.390* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)391* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)392* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.393*/394let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {395tagNameCheck: {396writable: true,397configurable: false,398enumerable: true,399value: null400},401attributeNameCheck: {402writable: true,403configurable: false,404enumerable: true,405value: null406},407allowCustomizedBuiltInElements: {408writable: true,409configurable: false,410enumerable: true,411value: false412}413}));414/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */415let FORBID_TAGS = null;416/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */417let FORBID_ATTR = null;418/* Decide if ARIA attributes are okay */419let ALLOW_ARIA_ATTR = true;420/* Decide if custom data attributes are okay */421let ALLOW_DATA_ATTR = true;422/* Decide if unknown protocols are okay */423let ALLOW_UNKNOWN_PROTOCOLS = false;424/* Decide if self-closing tags in attributes are allowed.425* Usually removed due to a mXSS issue in jQuery 3.0 */426let ALLOW_SELF_CLOSE_IN_ATTR = true;427/* Output should be safe for common template engines.428* This means, DOMPurify removes data attributes, mustaches and ERB429*/430let SAFE_FOR_TEMPLATES = false;431/* Output should be safe even for XML used within HTML and alike.432* This means, DOMPurify removes comments when containing risky content.433*/434let SAFE_FOR_XML = true;435/* Decide if document with <html>... should be returned */436let WHOLE_DOCUMENT = false;437/* Track whether config is already set on this instance of DOMPurify. */438let SET_CONFIG = false;439/* Decide if all elements (e.g. style, script) must be children of440* document.body. By default, browsers might move them to document.head */441let FORCE_BODY = false;442/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html443* string (or a TrustedHTML object if Trusted Types are supported).444* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead445*/446let RETURN_DOM = false;447/* Decide if a DOM `DocumentFragment` should be returned, instead of a html448* string (or a TrustedHTML object if Trusted Types are supported) */449let RETURN_DOM_FRAGMENT = false;450/* Try to return a Trusted Type object instead of a string, return a string in451* case Trusted Types are not supported */452let RETURN_TRUSTED_TYPE = false;453/* Output should be free from DOM clobbering attacks?454* This sanitizes markups named with colliding, clobberable built-in DOM APIs.455*/456let SANITIZE_DOM = true;457/* Achieve full DOM Clobbering protection by isolating the namespace of named458* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.459*460* HTML/DOM spec rules that enable DOM Clobbering:461* - Named Access on Window (§7.3.3)462* - DOM Tree Accessors (§3.1.5)463* - Form Element Parent-Child Relations (§4.10.3)464* - Iframe srcdoc / Nested WindowProxies (§4.8.5)465* - HTMLCollection (§4.2.10.2)466*467* Namespace isolation is implemented by prefixing `id` and `name` attributes468* with a constant string, i.e., `user-content-`469*/470let SANITIZE_NAMED_PROPS = false;471const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';472/* Keep element content when removing element? */473let KEEP_CONTENT = true;474/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead475* of importing it into a new Document and returning a sanitized copy */476let IN_PLACE = false;477/* Allow usage of profiles like html, svg and mathMl */478let USE_PROFILES = {};479/* Tags to ignore content of when KEEP_CONTENT is true */480let FORBID_CONTENTS = null;481const 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']);482/* Tags that are safe for data: URIs */483let DATA_URI_TAGS = null;484const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);485/* Attributes safe for values like "javascript:" */486let URI_SAFE_ATTRIBUTES = null;487const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);488const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';489const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';490const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';491/* Document namespace */492let NAMESPACE = HTML_NAMESPACE;493let IS_EMPTY_INPUT = false;494/* Allowed XHTML+XML namespaces */495let ALLOWED_NAMESPACES = null;496const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);497let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);498let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);499// Certain elements are allowed in both SVG and HTML500// namespace. We need to specify them explicitly501// so that they don't get erroneously deleted from502// HTML namespace.503const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);504/* Parsing of strict XHTML documents */505let PARSER_MEDIA_TYPE = null;506const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];507const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';508let transformCaseFunc = null;509/* Keep a reference to config to pass to hooks */510let CONFIG = null;511/* Ideally, do not touch anything below this line */512/* ______________________________________________ */513const formElement = document.createElement('form');514const isRegexOrFunction = function isRegexOrFunction(testValue) {515return testValue instanceof RegExp || testValue instanceof Function;516};517/**518* _parseConfig519*520* @param cfg optional config literal521*/522// eslint-disable-next-line complexity523const _parseConfig = function _parseConfig() {524let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};525if (CONFIG && CONFIG === cfg) {526return;527}528/* Shield configuration object from tampering */529if (!cfg || typeof cfg !== 'object') {530cfg = {};531}532/* Shield configuration object from prototype pollution */533cfg = clone(cfg);534PARSER_MEDIA_TYPE =535// eslint-disable-next-line unicorn/prefer-includes536SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;537// HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.538transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;539/* Set configuration parameters */540ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;541ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;542ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;543URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;544DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;545FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;546FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});547FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});548USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;549ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true550ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true551ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false552ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true553SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false554SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true555WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false556RETURN_DOM = cfg.RETURN_DOM || false; // Default false557RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false558RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false559FORCE_BODY = cfg.FORCE_BODY || false; // Default false560SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true561SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false562KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true563IN_PLACE = cfg.IN_PLACE || false; // Default false564IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;565NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;566MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;567HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;568CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};569if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {570CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;571}572if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {573CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;574}575if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {576CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;577}578if (SAFE_FOR_TEMPLATES) {579ALLOW_DATA_ATTR = false;580}581if (RETURN_DOM_FRAGMENT) {582RETURN_DOM = true;583}584/* Parse profile info */585if (USE_PROFILES) {586ALLOWED_TAGS = addToSet({}, text);587ALLOWED_ATTR = [];588if (USE_PROFILES.html === true) {589addToSet(ALLOWED_TAGS, html$1);590addToSet(ALLOWED_ATTR, html);591}592if (USE_PROFILES.svg === true) {593addToSet(ALLOWED_TAGS, svg$1);594addToSet(ALLOWED_ATTR, svg);595addToSet(ALLOWED_ATTR, xml);596}597if (USE_PROFILES.svgFilters === true) {598addToSet(ALLOWED_TAGS, svgFilters);599addToSet(ALLOWED_ATTR, svg);600addToSet(ALLOWED_ATTR, xml);601}602if (USE_PROFILES.mathMl === true) {603addToSet(ALLOWED_TAGS, mathMl$1);604addToSet(ALLOWED_ATTR, mathMl);605addToSet(ALLOWED_ATTR, xml);606}607}608/* Merge configuration parameters */609if (cfg.ADD_TAGS) {610if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {611ALLOWED_TAGS = clone(ALLOWED_TAGS);612}613addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);614}615if (cfg.ADD_ATTR) {616if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {617ALLOWED_ATTR = clone(ALLOWED_ATTR);618}619addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);620}621if (cfg.ADD_URI_SAFE_ATTR) {622addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);623}624if (cfg.FORBID_CONTENTS) {625if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {626FORBID_CONTENTS = clone(FORBID_CONTENTS);627}628addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);629}630/* Add #text in case KEEP_CONTENT is set to true */631if (KEEP_CONTENT) {632ALLOWED_TAGS['#text'] = true;633}634/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */635if (WHOLE_DOCUMENT) {636addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);637}638/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */639if (ALLOWED_TAGS.table) {640addToSet(ALLOWED_TAGS, ['tbody']);641delete FORBID_TAGS.tbody;642}643if (cfg.TRUSTED_TYPES_POLICY) {644if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {645throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');646}647if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {648throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');649}650// Overwrite existing TrustedTypes policy.651trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;652// Sign local variables required by `sanitize`.653emptyHTML = trustedTypesPolicy.createHTML('');654} else {655// Uninitialized policy, attempt to initialize the internal dompurify policy.656if (trustedTypesPolicy === undefined) {657trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);658}659// If creating the internal policy succeeded sign internal variables.660if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {661emptyHTML = trustedTypesPolicy.createHTML('');662}663}664// Prevent further manipulation of configuration.665// Not available in IE8, Safari 5, etc.666if (freeze) {667freeze(cfg);668}669CONFIG = cfg;670};671/* Keep track of all possible SVG and MathML tags672* so that we can perform the namespace checks673* correctly. */674const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);675const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);676/**677* @param element a DOM element whose namespace is being checked678* @returns Return false if the element has a679* namespace that a spec-compliant parser would never680* return. Return true otherwise.681*/682const _checkValidNamespace = function _checkValidNamespace(element) {683let parent = getParentNode(element);684// In JSDOM, if we're inside shadow DOM, then parentNode685// can be null. We just simulate parent in this case.686if (!parent || !parent.tagName) {687parent = {688namespaceURI: NAMESPACE,689tagName: 'template'690};691}692const tagName = stringToLowerCase(element.tagName);693const parentTagName = stringToLowerCase(parent.tagName);694if (!ALLOWED_NAMESPACES[element.namespaceURI]) {695return false;696}697if (element.namespaceURI === SVG_NAMESPACE) {698// The only way to switch from HTML namespace to SVG699// is via <svg>. If it happens via any other tag, then700// it should be killed.701if (parent.namespaceURI === HTML_NAMESPACE) {702return tagName === 'svg';703}704// The only way to switch from MathML to SVG is via`705// svg if parent is either <annotation-xml> or MathML706// text integration points.707if (parent.namespaceURI === MATHML_NAMESPACE) {708return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);709}710// We only allow elements that are defined in SVG711// spec. All others are disallowed in SVG namespace.712return Boolean(ALL_SVG_TAGS[tagName]);713}714if (element.namespaceURI === MATHML_NAMESPACE) {715// The only way to switch from HTML namespace to MathML716// is via <math>. If it happens via any other tag, then717// it should be killed.718if (parent.namespaceURI === HTML_NAMESPACE) {719return tagName === 'math';720}721// The only way to switch from SVG to MathML is via722// <math> and HTML integration points723if (parent.namespaceURI === SVG_NAMESPACE) {724return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];725}726// We only allow elements that are defined in MathML727// spec. All others are disallowed in MathML namespace.728return Boolean(ALL_MATHML_TAGS[tagName]);729}730if (element.namespaceURI === HTML_NAMESPACE) {731// The only way to switch from SVG to HTML is via732// HTML integration points, and from MathML to HTML733// is via MathML text integration points734if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {735return false;736}737if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {738return false;739}740// We disallow tags that are specific for MathML741// or SVG and should never appear in HTML namespace742return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);743}744// For XHTML and XML documents that support custom namespaces745if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {746return true;747}748// The code should never reach this place (this means749// that the element somehow got namespace that is not750// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).751// Return false just in case.752return false;753};754/**755* _forceRemove756*757* @param node a DOM node758*/759const _forceRemove = function _forceRemove(node) {760arrayPush(DOMPurify.removed, {761element: node762});763try {764// eslint-disable-next-line unicorn/prefer-dom-node-remove765getParentNode(node).removeChild(node);766} catch (_) {767remove(node);768}769};770/**771* _removeAttribute772*773* @param name an Attribute name774* @param element a DOM node775*/776const _removeAttribute = function _removeAttribute(name, element) {777try {778arrayPush(DOMPurify.removed, {779attribute: element.getAttributeNode(name),780from: element781});782} catch (_) {783arrayPush(DOMPurify.removed, {784attribute: null,785from: element786});787}788element.removeAttribute(name);789// We void attribute values for unremovable "is" attributes790if (name === 'is') {791if (RETURN_DOM || RETURN_DOM_FRAGMENT) {792try {793_forceRemove(element);794} catch (_) {}795} else {796try {797element.setAttribute(name, '');798} catch (_) {}799}800}801};802/**803* _initDocument804*805* @param dirty - a string of dirty markup806* @return a DOM, filled with the dirty markup807*/808const _initDocument = function _initDocument(dirty) {809/* Create a HTML document */810let doc = null;811let leadingWhitespace = null;812if (FORCE_BODY) {813dirty = '<remove></remove>' + dirty;814} else {815/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */816const matches = stringMatch(dirty, /^[\r\n\t ]+/);817leadingWhitespace = matches && matches[0];818}819if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {820// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)821dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';822}823const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;824/*825* Use the DOMParser API by default, fallback later if needs be826* DOMParser not work for svg when has multiple root element.827*/828if (NAMESPACE === HTML_NAMESPACE) {829try {830doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);831} catch (_) {}832}833/* Use createHTMLDocument in case DOMParser is not available */834if (!doc || !doc.documentElement) {835doc = implementation.createDocument(NAMESPACE, 'template', null);836try {837doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;838} catch (_) {839// Syntax error if dirtyPayload is invalid xml840}841}842const body = doc.body || doc.documentElement;843if (dirty && leadingWhitespace) {844body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);845}846/* Work on whole document or just its body */847if (NAMESPACE === HTML_NAMESPACE) {848return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];849}850return WHOLE_DOCUMENT ? doc.documentElement : body;851};852/**853* Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.854*855* @param root The root element or node to start traversing on.856* @return The created NodeIterator857*/858const _createNodeIterator = function _createNodeIterator(root) {859return createNodeIterator.call(root.ownerDocument || root, root,860// eslint-disable-next-line no-bitwise861NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);862};863/**864* _isClobbered865*866* @param element element to check for clobbering attacks867* @return true if clobbered, false if safe868*/869const _isClobbered = function _isClobbered(element) {870return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');871};872/**873* Checks whether the given object is a DOM node.874*875* @param value object to check whether it's a DOM node876* @return true is object is a DOM node877*/878const _isNode = function _isNode(value) {879return typeof Node === 'function' && value instanceof Node;880};881function _executeHooks(hooks, currentNode, data) {882arrayForEach(hooks, hook => {883hook.call(DOMPurify, currentNode, data, CONFIG);884});885}886/**887* _sanitizeElements888*889* @protect nodeName890* @protect textContent891* @protect removeChild892* @param currentNode to check for permission to exist893* @return true if node was killed, false if left alive894*/895const _sanitizeElements = function _sanitizeElements(currentNode) {896let content = null;897/* Execute a hook if present */898_executeHooks(hooks.beforeSanitizeElements, currentNode, null);899/* Check if element is clobbered or can clobber */900if (_isClobbered(currentNode)) {901_forceRemove(currentNode);902return true;903}904/* Now let's check the element's type and name */905const tagName = transformCaseFunc(currentNode.nodeName);906/* Execute a hook if present */907_executeHooks(hooks.uponSanitizeElement, currentNode, {908tagName,909allowedTags: ALLOWED_TAGS910});911/* Detect mXSS attempts abusing namespace confusion */912if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {913_forceRemove(currentNode);914return true;915}916/* Remove any occurrence of processing instructions */917if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {918_forceRemove(currentNode);919return true;920}921/* Remove any kind of possibly harmful comments */922if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {923_forceRemove(currentNode);924return true;925}926/* Remove element if anything forbids its presence */927if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {928/* Check if we have a custom element to handle */929if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {930if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {931return false;932}933if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {934return false;935}936}937/* Keep content except for bad-listed elements */938if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {939const parentNode = getParentNode(currentNode) || currentNode.parentNode;940const childNodes = getChildNodes(currentNode) || currentNode.childNodes;941if (childNodes && parentNode) {942const childCount = childNodes.length;943for (let i = childCount - 1; i >= 0; --i) {944const childClone = cloneNode(childNodes[i], true);945childClone.__removalCount = (currentNode.__removalCount || 0) + 1;946parentNode.insertBefore(childClone, getNextSibling(currentNode));947}948}949}950_forceRemove(currentNode);951return true;952}953/* Check whether element has a valid namespace */954if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {955_forceRemove(currentNode);956return true;957}958/* Make sure that older browsers don't get fallback-tag mXSS */959if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {960_forceRemove(currentNode);961return true;962}963/* Sanitize element content to be template-safe */964if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {965/* Get the element's text content */966content = currentNode.textContent;967arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {968content = stringReplace(content, expr, ' ');969});970if (currentNode.textContent !== content) {971arrayPush(DOMPurify.removed, {972element: currentNode.cloneNode()973});974currentNode.textContent = content;975}976}977/* Execute a hook if present */978_executeHooks(hooks.afterSanitizeElements, currentNode, null);979return false;980};981/**982* _isValidAttribute983*984* @param lcTag Lowercase tag name of containing element.985* @param lcName Lowercase attribute name.986* @param value Attribute value.987* @return Returns true if `value` is valid, otherwise false.988*/989// eslint-disable-next-line complexity990const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {991/* Make sure attribute cannot clobber */992if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {993return false;994}995/* Allow valid data-* attributes: At least one character after "-"996(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)997XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)998We don't need to check the value; it's always URI safe. */999if (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]) {1000if (1001// First condition does a very basic check if a) it's basically a valid custom element tagname AND1002// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck1003// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck1004_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, lcTag)) ||1005// Alternative, second condition checks if it's an `is`-attribute, AND1006// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck1007lcName === '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 {1008return false;1009}1010/* Check value is safe. First, is attr inert? If so, is safe */1011} 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) {1012return false;1013} else ;1014return true;1015};1016/**1017* _isBasicCustomElement1018* checks if at least one dash is included in tagName, and it's not the first char1019* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name1020*1021* @param tagName name of the tag of the node to sanitize1022* @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.1023*/1024const _isBasicCustomElement = function _isBasicCustomElement(tagName) {1025return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);1026};1027/**1028* _sanitizeAttributes1029*1030* @protect attributes1031* @protect nodeName1032* @protect removeAttribute1033* @protect setAttribute1034*1035* @param currentNode to sanitize1036*/1037const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {1038/* Execute a hook if present */1039_executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);1040const {1041attributes1042} = currentNode;1043/* Check if we have attributes; if not we might have a text node */1044if (!attributes || _isClobbered(currentNode)) {1045return;1046}1047const hookEvent = {1048attrName: '',1049attrValue: '',1050keepAttr: true,1051allowedAttributes: ALLOWED_ATTR,1052forceKeepAttr: undefined1053};1054let l = attributes.length;1055/* Go backwards over all attributes; safely remove bad ones */1056while (l--) {1057const attr = attributes[l];1058const {1059name,1060namespaceURI,1061value: attrValue1062} = attr;1063const lcName = transformCaseFunc(name);1064const initValue = attrValue;1065let value = name === 'value' ? initValue : stringTrim(initValue);1066/* Execute a hook if present */1067hookEvent.attrName = lcName;1068hookEvent.attrValue = value;1069hookEvent.keepAttr = true;1070hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set1071_executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);1072value = hookEvent.attrValue;1073/* Full DOM Clobbering protection via namespace isolation,1074* Prefix id and name attributes with `user-content-`1075*/1076if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {1077// Remove the attribute with this value1078_removeAttribute(name, currentNode);1079// Prefix the value and later re-create the attribute with the sanitized value1080value = SANITIZE_NAMED_PROPS_PREFIX + value;1081}1082/* Work around a security issue with comments inside attributes */1083if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) {1084_removeAttribute(name, currentNode);1085continue;1086}1087/* Make sure we cannot easily use animated hrefs, even if animations are allowed */1088if (lcName === 'attributename' && stringMatch(value, 'href')) {1089_removeAttribute(name, currentNode);1090continue;1091}1092/* Did the hooks approve of the attribute? */1093if (hookEvent.forceKeepAttr) {1094continue;1095}1096/* Did the hooks approve of the attribute? */1097if (!hookEvent.keepAttr) {1098_removeAttribute(name, currentNode);1099continue;1100}1101/* Work around a security issue in jQuery 3.0 */1102if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {1103_removeAttribute(name, currentNode);1104continue;1105}1106/* Sanitize attribute content to be template-safe */1107if (SAFE_FOR_TEMPLATES) {1108arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1109value = stringReplace(value, expr, ' ');1110});1111}1112/* Is `value` valid for this attribute? */1113const lcTag = transformCaseFunc(currentNode.nodeName);1114if (!_isValidAttribute(lcTag, lcName, value)) {1115_removeAttribute(name, currentNode);1116continue;1117}1118/* Handle attributes that require Trusted Types */1119if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {1120if (namespaceURI) ; else {1121switch (trustedTypes.getAttributeType(lcTag, lcName)) {1122case 'TrustedHTML':1123{1124value = trustedTypesPolicy.createHTML(value);1125break;1126}1127case 'TrustedScriptURL':1128{1129value = trustedTypesPolicy.createScriptURL(value);1130break;1131}1132}1133}1134}1135/* Handle invalid data-* attribute set by try-catching it */1136if (value !== initValue) {1137try {1138if (namespaceURI) {1139currentNode.setAttributeNS(namespaceURI, name, value);1140} else {1141/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */1142currentNode.setAttribute(name, value);1143}1144if (_isClobbered(currentNode)) {1145_forceRemove(currentNode);1146} else {1147arrayPop(DOMPurify.removed);1148}1149} catch (_) {1150_removeAttribute(name, currentNode);1151}1152}1153}1154/* Execute a hook if present */1155_executeHooks(hooks.afterSanitizeAttributes, currentNode, null);1156};1157/**1158* _sanitizeShadowDOM1159*1160* @param fragment to iterate over recursively1161*/1162const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {1163let shadowNode = null;1164const shadowIterator = _createNodeIterator(fragment);1165/* Execute a hook if present */1166_executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);1167while (shadowNode = shadowIterator.nextNode()) {1168/* Execute a hook if present */1169_executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);1170/* Sanitize tags and elements */1171_sanitizeElements(shadowNode);1172/* Check attributes next */1173_sanitizeAttributes(shadowNode);1174/* Deep shadow DOM detected */1175if (shadowNode.content instanceof DocumentFragment) {1176_sanitizeShadowDOM(shadowNode.content);1177}1178}1179/* Execute a hook if present */1180_executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);1181};1182// eslint-disable-next-line complexity1183DOMPurify.sanitize = function (dirty) {1184let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};1185let body = null;1186let importedNode = null;1187let currentNode = null;1188let returnNode = null;1189/* Make sure we have a string to sanitize.1190DO NOT return early, as this will return the wrong type if1191the user has requested a DOM object rather than a string */1192IS_EMPTY_INPUT = !dirty;1193if (IS_EMPTY_INPUT) {1194dirty = '<!-->';1195}1196/* Stringify, in case dirty is an object */1197if (typeof dirty !== 'string' && !_isNode(dirty)) {1198if (typeof dirty.toString === 'function') {1199dirty = dirty.toString();1200if (typeof dirty !== 'string') {1201throw typeErrorCreate('dirty is not a string, aborting');1202}1203} else {1204throw typeErrorCreate('toString is not a function');1205}1206}1207/* Return dirty HTML if DOMPurify cannot run */1208if (!DOMPurify.isSupported) {1209return dirty;1210}1211/* Assign config vars */1212if (!SET_CONFIG) {1213_parseConfig(cfg);1214}1215/* Clean up removed elements */1216DOMPurify.removed = [];1217/* Check if dirty is correctly typed for IN_PLACE */1218if (typeof dirty === 'string') {1219IN_PLACE = false;1220}1221if (IN_PLACE) {1222/* Do some early pre-sanitization to avoid unsafe root nodes */1223if (dirty.nodeName) {1224const tagName = transformCaseFunc(dirty.nodeName);1225if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {1226throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');1227}1228}1229} else if (dirty instanceof Node) {1230/* If dirty is a DOM element, append to an empty document to avoid1231elements being stripped by the parser */1232body = _initDocument('<!---->');1233importedNode = body.ownerDocument.importNode(dirty, true);1234if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {1235/* Node is already a body, use as is */1236body = importedNode;1237} else if (importedNode.nodeName === 'HTML') {1238body = importedNode;1239} else {1240// eslint-disable-next-line unicorn/prefer-dom-node-append1241body.appendChild(importedNode);1242}1243} else {1244/* Exit directly if we have nothing to do */1245if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&1246// eslint-disable-next-line unicorn/prefer-includes1247dirty.indexOf('<') === -1) {1248return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;1249}1250/* Initialize the document to work on */1251body = _initDocument(dirty);1252/* Check we have a DOM node from the data */1253if (!body) {1254return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';1255}1256}1257/* Remove first element node (ours) if FORCE_BODY is set */1258if (body && FORCE_BODY) {1259_forceRemove(body.firstChild);1260}1261/* Get node iterator */1262const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);1263/* Now start iterating over the created document */1264while (currentNode = nodeIterator.nextNode()) {1265/* Sanitize tags and elements */1266_sanitizeElements(currentNode);1267/* Check attributes next */1268_sanitizeAttributes(currentNode);1269/* Shadow DOM detected, sanitize it */1270if (currentNode.content instanceof DocumentFragment) {1271_sanitizeShadowDOM(currentNode.content);1272}1273}1274/* If we sanitized `dirty` in-place, return it. */1275if (IN_PLACE) {1276return dirty;1277}1278/* Return sanitized string or DOM */1279if (RETURN_DOM) {1280if (RETURN_DOM_FRAGMENT) {1281returnNode = createDocumentFragment.call(body.ownerDocument);1282while (body.firstChild) {1283// eslint-disable-next-line unicorn/prefer-dom-node-append1284returnNode.appendChild(body.firstChild);1285}1286} else {1287returnNode = body;1288}1289if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {1290/*1291AdoptNode() is not used because internal state is not reset1292(e.g. the past names map of a HTMLFormElement), this is safe1293in theory but we would rather not risk another attack vector.1294The state that is cloned by importNode() is explicitly defined1295by the specs.1296*/1297returnNode = importNode.call(originalDocument, returnNode, true);1298}1299return returnNode;1300}1301let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;1302/* Serialize doctype if allowed */1303if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {1304serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;1305}1306/* Sanitize final string template-safe */1307if (SAFE_FOR_TEMPLATES) {1308arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {1309serializedHTML = stringReplace(serializedHTML, expr, ' ');1310});1311}1312return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;1313};1314DOMPurify.setConfig = function () {1315let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};1316_parseConfig(cfg);1317SET_CONFIG = true;1318};1319DOMPurify.clearConfig = function () {1320CONFIG = null;1321SET_CONFIG = false;1322};1323DOMPurify.isValidAttribute = function (tag, attr, value) {1324/* Initialize shared config vars if necessary. */1325if (!CONFIG) {1326_parseConfig({});1327}1328const lcTag = transformCaseFunc(tag);1329const lcName = transformCaseFunc(attr);1330return _isValidAttribute(lcTag, lcName, value);1331};1332DOMPurify.addHook = function (entryPoint, hookFunction) {1333if (typeof hookFunction !== 'function') {1334return;1335}1336arrayPush(hooks[entryPoint], hookFunction);1337};1338DOMPurify.removeHook = function (entryPoint, hookFunction) {1339if (hookFunction !== undefined) {1340const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);1341return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];1342}1343return arrayPop(hooks[entryPoint]);1344};1345DOMPurify.removeHooks = function (entryPoint) {1346hooks[entryPoint] = [];1347};1348DOMPurify.removeAllHooks = function () {1349hooks = _createHooksMap();1350};1351return DOMPurify;1352}1353var purify = createDOMPurify();13541355export { purify as default };135613571358