purify.js 17 KB

1
  1. !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).DOMPurify=t()}(this,function(){"use strict";var r,o=Object.hasOwnProperty,i=Object.setPrototypeOf,a=Object.isFrozen,l=Object.getPrototypeOf,c=Object.getOwnPropertyDescriptor,Re=Object.freeze,e=Object.seal,s=Object.create,t="undefined"!=typeof Reflect&&Reflect,u=(u=t.apply)||function(e,t,n){return e.apply(t,n)},Re=Re||function(e){return e},e=e||function(e){return e},m=(m=t.construct)||function(e,t){return new(Function.prototype.bind.apply(e,[null].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(t))))},_e=f(Array.prototype.forEach),Ne=f(Array.prototype.pop),Oe=f(Array.prototype.push),Me=f(String.prototype.toLowerCase),Le=f(String.prototype.match),Fe=f(String.prototype.replace),Ie=f(String.prototype.indexOf),Ce=f(String.prototype.trim),ze=f(RegExp.prototype.test),Ue=(r=TypeError,function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return m(r,t)});function f(o){return function(e){for(var t=arguments.length,n=Array(1<t?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return u(o,e,n)}}function He(e,t){i&&i(e,null);for(var n=t.length;n--;){var r,o=t[n];"string"!=typeof o||(r=Me(o))!==o&&(a(t)||(t[n]=r),o=r),e[o]=!0}return e}function je(e){var t=s(null),n=void 0;for(n in e)u(o,e,[n])&&(t[n]=e[n]);return t}function Pe(e,t){for(;null!==e;){var n=c(e,t);if(n){if(n.get)return f(n.get);if("function"==typeof n.value)return f(n.value)}e=l(e)}return function(e){return console.warn("fallback value for",e),null}}var Be=Re(["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"]),We=Re(["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"]),Ge=Re(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),qe=Re(["animate","color-profile","cursor","discard","fedropshadow","feimage","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"]),Ke=Re(["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"]),Ve=Re(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ye=Re(["#text"]),Xe=Re(["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","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),$e=Re(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","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"]),Ze=Re(["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"]),Je=Re(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Qe=e(/\{\{[\s\S]*|[\s\S]*\}\}/gm),et=e(/<%[\s\S]*|[\s\S]*%>/gm),tt=e(/^data-[\-\w.\u00B7-\uFFFF]/),nt=e(/^aria-[\-\w]+$/),rt=e(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ot=e(/^(?:\w+script|data):/i),it=e(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),at="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function lt(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}return function t(e){var l=0<arguments.length&&void 0!==e?e:"undefined"==typeof window?null:window,u=function(e){return t(e)};if(u.version="2.2.9",u.removed=[],!l||!l.document||9!==l.document.nodeType)return u.isSupported=!1,u;var c=l.document,o=l.document,s=l.DocumentFragment,n=l.HTMLTemplateElement,m=l.Node,a=l.Element,r=l.NodeFilter,i=l.NamedNodeMap,f=void 0===i?l.NamedNodeMap||l.MozNamedAttrMap:i,p=l.Text,d=l.Comment,g=l.DOMParser,e=l.trustedTypes,i=a.prototype,h=Pe(i,"cloneNode"),y=Pe(i,"nextSibling"),v=Pe(i,"childNodes"),b=Pe(i,"parentNode");"function"!=typeof n||(n=o.createElement("template")).content&&n.content.ownerDocument&&(o=n.content.ownerDocument);var A=function(e,t){if("object"!==(void 0===e?"undefined":at(e))||"function"!=typeof e.createPolicy)return null;var n=null,r="data-tt-policy-suffix",n="dompurify"+((n=t.currentScript&&t.currentScript.hasAttribute(r)?t.currentScript.getAttribute(r):n)?"#"+n:"");try{return e.createPolicy(n,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+n+" could not be created."),null}}(e,c),T=A&&J?A.createHTML(""):"",e=o,w=e.implementation,x=e.createNodeIterator,S=e.createDocumentFragment,k=c.importNode,e={};try{e=je(o).documentMode?o.documentMode:{}}catch(e){}var D={};u.isSupported="function"==typeof b&&w&&void 0!==w.createHTMLDocument&&9!==e;function E(e){fe&&fe===e||(e=je(e=e&&"object"===(void 0===e?"undefined":at(e))?e:{}),C="ALLOWED_TAGS"in e?He({},e.ALLOWED_TAGS):z,U="ALLOWED_ATTR"in e?He({},e.ALLOWED_ATTR):H,ae="ADD_URI_SAFE_ATTR"in e?He(je(le),e.ADD_URI_SAFE_ATTR):le,oe="ADD_DATA_URI_TAGS"in e?He(je(ie),e.ADD_DATA_URI_TAGS):ie,j="FORBID_TAGS"in e?He({},e.FORBID_TAGS):{},P="FORBID_ATTR"in e?He({},e.FORBID_ATTR):{},ne="USE_PROFILES"in e&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,W=!1!==e.ALLOW_DATA_ATTR,G=e.ALLOW_UNKNOWN_PROTOCOLS||!1,q=e.SAFE_FOR_TEMPLATES||!1,K=e.WHOLE_DOCUMENT||!1,X=e.RETURN_DOM||!1,$=e.RETURN_DOM_FRAGMENT||!1,Z=!1!==e.RETURN_DOM_IMPORT,J=e.RETURN_TRUSTED_TYPE||!1,Y=e.FORCE_BODY||!1,Q=!1!==e.SANITIZE_DOM,ee=!1!==e.KEEP_CONTENT,te=e.IN_PLACE||!1,I=e.ALLOWED_URI_REGEXP||I,me=e.NAMESPACE||ue,q&&(W=!1),$&&(X=!0),ne&&(C=He({},[].concat(lt(Ye))),U=[],!0===ne.html&&(He(C,Be),He(U,Xe)),!0===ne.svg&&(He(C,We),He(U,$e),He(U,Je)),!0===ne.svgFilters&&(He(C,Ge),He(U,$e),He(U,Je)),!0===ne.mathMl&&(He(C,Ke),He(U,Ze),He(U,Je))),e.ADD_TAGS&&He(C=C===z?je(C):C,e.ADD_TAGS),e.ADD_ATTR&&He(U=U===H?je(U):U,e.ADD_ATTR),e.ADD_URI_SAFE_ATTR&&He(ae,e.ADD_URI_SAFE_ATTR),ee&&(C["#text"]=!0),K&&He(C,["html","head","body"]),C.table&&(He(C,["tbody"]),delete j.tbody),Re&&Re(e),fe=e)}var R,_=Qe,N=et,O=tt,M=nt,L=ot,F=it,I=rt,C=null,z=He({},[].concat(lt(Be),lt(We),lt(Ge),lt(Ke),lt(Ye))),U=null,H=He({},[].concat(lt(Xe),lt($e),lt(Ze),lt(Je))),j=null,P=null,B=!0,W=!0,G=!1,q=!1,K=!1,V=!1,Y=!1,X=!1,$=!1,Z=!0,J=!1,Q=!0,ee=!0,te=!1,ne={},re=He({},["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"]),oe=null,ie=He({},["audio","video","img","source","image","track"]),ae=null,le=He({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),ce="http://www.w3.org/1998/Math/MathML",se="http://www.w3.org/2000/svg",ue="http://www.w3.org/1999/xhtml",me=ue,fe=null,pe=o.createElement("form"),de=He({},["mi","mo","mn","ms","mtext"]),ge=He({},["foreignobject","desc","title","annotation-xml"]),he=He({},We);He(he,Ge),He(he,qe);var ye=He({},Ke);He(ye,Ve);function ve(t){Oe(u.removed,{element:t});try{t.parentNode.removeChild(t)}catch(e){try{t.outerHTML=T}catch(e){t.remove()}}}function be(e){var t=void 0,n=void 0;Y?e="<remove></remove>"+e:n=(r=Le(e,/^[\r\n\t ]+/))&&r[0];var r=A?A.createHTML(e):e;if(me===ue)try{t=(new g).parseFromString(r,"text/html")}catch(e){}if(!t||!t.documentElement){t=w.createDocument(me,"template",null);try{t.documentElement.innerHTML=R?"":r}catch(e){}}return r=t.body||t.documentElement,e&&n&&r.insertBefore(o.createTextNode(n),r.childNodes[0]||null),K?t.documentElement:r}function Ae(e){return x.call(e.ownerDocument||e,e,r.SHOW_ELEMENT|r.SHOW_COMMENT|r.SHOW_TEXT,null,!1)}function Te(e){return"object"===(void 0===m?"undefined":at(m))?e instanceof m:e&&"object"===(void 0===e?"undefined":at(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName}function we(e){var t;if(De("beforeSanitizeElements",e,null),!((n=e)instanceof p||n instanceof d||"string"==typeof n.nodeName&&"string"==typeof n.textContent&&"function"==typeof n.removeChild&&n.attributes instanceof f&&"function"==typeof n.removeAttribute&&"function"==typeof n.setAttribute&&"string"==typeof n.namespaceURI&&"function"==typeof n.insertBefore))return ve(e),1;if(Le(e.nodeName,/[\u0080-\uFFFF]/))return ve(e),1;var n=Me(e.nodeName);if(De("uponSanitizeElement",e,{tagName:n,allowedTags:C}),!Te(e.firstElementChild)&&(!Te(e.content)||!Te(e.content.firstElementChild))&&ze(/<[/\w]/g,e.innerHTML)&&ze(/<[/\w]/g,e.textContent))return ve(e),1;if(C[n]&&!j[n])return e instanceof a&&!function(e){var t=b(e);t&&t.tagName||(t={namespaceURI:ue,tagName:"template"});var n=Me(e.tagName),r=Me(t.tagName);return e.namespaceURI===se?t.namespaceURI===ue?"svg"===n:t.namespaceURI===ce?"svg"===n&&("annotation-xml"===r||de[r]):Boolean(he[n]):e.namespaceURI===ce?t.namespaceURI===ue?"math"===n:t.namespaceURI===se?"math"===n&&ge[r]:Boolean(ye[n]):e.namespaceURI===ue&&((t.namespaceURI!==se||ge[r])&&((t.namespaceURI!==ce||de[r])&&(r=He({},["title","style","font","a","script"]),!ye[n]&&(r[n]||!he[n]))))}(e)||("noscript"===n||"noembed"===n)&&ze(/<\/no(script|embed)/i,e.innerHTML)?(ve(e),1):(q&&3===e.nodeType&&(t=e.textContent,t=Fe(t,_," "),t=Fe(t,N," "),e.textContent!==t&&(Oe(u.removed,{element:e.cloneNode()}),e.textContent=t)),De("afterSanitizeElements",e,null),0);if(ee&&!re[n]){var r=b(e)||e.parentNode,o=v(e)||e.childNodes;if(o&&r)for(var i=o.length-1;0<=i;--i)r.insertBefore(h(o[i],!0),y(e))}return ve(e),1}function xe(e){var t=void 0,n=void 0,r=void 0;De("beforeSanitizeAttributes",e,null);var o=e.attributes;if(o){for(var i={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U},r=o.length;r--;){var a=(t=o[r]).name,l=t.namespaceURI,n=Ce(t.value),c=Me(a);if(i.attrName=c,i.attrValue=n,i.keepAttr=!0,i.forceKeepAttr=void 0,De("uponSanitizeAttribute",e,i),n=i.attrValue,!i.forceKeepAttr&&(ke(a,e),i.keepAttr))if(ze(/\/>/i,n))ke(a,e);else{q&&(n=Fe(n,_," "),n=Fe(n,N," "));var s=e.nodeName.toLowerCase();if(Ee(s,c,n))try{l?e.setAttributeNS(l,a,n):e.setAttribute(a,n),Ne(u.removed)}catch(e){}}}De("afterSanitizeAttributes",e,null)}}function Se(e){var t,n=Ae(e);for(De("beforeSanitizeShadowDOM",e,null);t=n.nextNode();)De("uponSanitizeShadowNode",t,null),we(t)||(t.content instanceof s&&Se(t.content),xe(t));De("afterSanitizeShadowDOM",e,null)}var ke=function(e,t){try{Oe(u.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Oe(u.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e&&!U[e])if(X||$)try{ve(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},De=function(e,t,n){D[e]&&_e(D[e],function(e){e.call(u,t,n,fe)})},Ee=function(e,t,n){if(Q&&("id"===t||"name"===t)&&(n in o||n in pe))return!1;if(!(W&&ze(O,t)||B&&ze(M,t))){if(!U[t]||P[t])return!1;if(!ae[t]&&!ze(I,Fe(n,F,""))&&("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Ie(n,"data:")||!oe[e])&&(!G||ze(L,Fe(n,F,"")))&&n)return!1}return!0};return u.sanitize=function(e,t){var n,r=void 0,o=void 0,i=void 0;if("string"!=typeof(e=(R=!e)?"\x3c!--\x3e":e)&&!Te(e)){if("function"!=typeof e.toString)throw Ue("toString is not a function");if("string"!=typeof(e=e.toString()))throw Ue("dirty is not a string, aborting")}if(!u.isSupported){if("object"===at(l.toStaticHTML)||"function"==typeof l.toStaticHTML){if("string"==typeof e)return l.toStaticHTML(e);if(Te(e))return l.toStaticHTML(e.outerHTML)}return e}if(V||E(t),u.removed=[],!(te="string"!=typeof e&&te))if(e instanceof m)1===(t=(r=be("\x3c!----\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===t.nodeName||"HTML"===t.nodeName?r=t:r.appendChild(t);else{if(!X&&!q&&!K&&-1===e.indexOf("<"))return A&&J?A.createHTML(e):e;if(!(r=be(e)))return X?null:T}r&&Y&&ve(r.firstChild);for(var a=Ae(te?e:r);n=a.nextNode();)3===n.nodeType&&n===o||we(n)||(n.content instanceof s&&Se(n.content),xe(n),o=n);if(o=null,te)return e;if(X){if($)for(i=S.call(r.ownerDocument);r.firstChild;)i.appendChild(r.firstChild);else i=r;return i=Z?k.call(c,i,!0):i}return e=K?r.outerHTML:r.innerHTML,q&&(e=Fe(e,_," "),e=Fe(e,N," ")),A&&J?A.createHTML(e):e},u.setConfig=function(e){E(e),V=!0},u.clearConfig=function(){fe=null,V=!1},u.isValidAttribute=function(e,t,n){return fe||E({}),e=Me(e),t=Me(t),Ee(e,t,n)},u.addHook=function(e,t){"function"==typeof t&&(D[e]=D[e]||[],Oe(D[e],t))},u.removeHook=function(e){D[e]&&Ne(D[e])},u.removeHooks=function(e){D[e]&&(D[e]=[])},u.removeAllHooks=function(){D={}},u}()});