智慧水务管理系统 - 精河县供水工程综合管理平台

purify.es.mjs 104KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  1. /*! @license DOMPurify 3.4.10 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.10/LICENSE */
  2. function _arrayLikeToArray(r, a) {
  3. (null == a || a > r.length) && (a = r.length);
  4. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  5. return n;
  6. }
  7. function _arrayWithHoles(r) {
  8. if (Array.isArray(r)) return r;
  9. }
  10. function _iterableToArrayLimit(r, l) {
  11. var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  12. if (null != t) {
  13. var e,
  14. n,
  15. i,
  16. u,
  17. a = [],
  18. f = true,
  19. o = false;
  20. try {
  21. if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
  22. } catch (r) {
  23. o = true, n = r;
  24. } finally {
  25. try {
  26. if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
  27. } finally {
  28. if (o) throw n;
  29. }
  30. }
  31. return a;
  32. }
  33. }
  34. function _nonIterableRest() {
  35. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  36. }
  37. function _slicedToArray(r, e) {
  38. return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
  39. }
  40. function _unsupportedIterableToArray(r, a) {
  41. if (r) {
  42. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  43. var t = {}.toString.call(r).slice(8, -1);
  44. return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  45. }
  46. }
  47. const entries = Object.entries,
  48. setPrototypeOf = Object.setPrototypeOf,
  49. isFrozen = Object.isFrozen,
  50. getPrototypeOf = Object.getPrototypeOf,
  51. getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  52. let freeze = Object.freeze,
  53. seal = Object.seal,
  54. create = Object.create; // eslint-disable-line import/no-mutable-exports
  55. let _ref = typeof Reflect !== 'undefined' && Reflect,
  56. apply = _ref.apply,
  57. construct = _ref.construct;
  58. if (!freeze) {
  59. freeze = function freeze(x) {
  60. return x;
  61. };
  62. }
  63. if (!seal) {
  64. seal = function seal(x) {
  65. return x;
  66. };
  67. }
  68. if (!apply) {
  69. apply = function apply(func, thisArg) {
  70. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  71. args[_key - 2] = arguments[_key];
  72. }
  73. return func.apply(thisArg, args);
  74. };
  75. }
  76. if (!construct) {
  77. construct = function construct(Func) {
  78. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  79. args[_key2 - 1] = arguments[_key2];
  80. }
  81. return new Func(...args);
  82. };
  83. }
  84. const arrayForEach = unapply(Array.prototype.forEach);
  85. const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
  86. const arrayPop = unapply(Array.prototype.pop);
  87. const arrayPush = unapply(Array.prototype.push);
  88. const arraySplice = unapply(Array.prototype.splice);
  89. const arrayIsArray = Array.isArray;
  90. const stringToLowerCase = unapply(String.prototype.toLowerCase);
  91. const stringToString = unapply(String.prototype.toString);
  92. const stringMatch = unapply(String.prototype.match);
  93. const stringReplace = unapply(String.prototype.replace);
  94. const stringIndexOf = unapply(String.prototype.indexOf);
  95. const stringTrim = unapply(String.prototype.trim);
  96. const numberToString = unapply(Number.prototype.toString);
  97. const booleanToString = unapply(Boolean.prototype.toString);
  98. const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
  99. const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
  100. const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
  101. const objectToString = unapply(Object.prototype.toString);
  102. const regExpTest = unapply(RegExp.prototype.test);
  103. const typeErrorCreate = unconstruct(TypeError);
  104. /**
  105. * Creates a new function that calls the given function with a specified thisArg and arguments.
  106. *
  107. * @param func - The function to be wrapped and called.
  108. * @returns A new function that calls the given function with a specified thisArg and arguments.
  109. */
  110. function unapply(func) {
  111. return function (thisArg) {
  112. if (thisArg instanceof RegExp) {
  113. thisArg.lastIndex = 0;
  114. }
  115. for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  116. args[_key3 - 1] = arguments[_key3];
  117. }
  118. return apply(func, thisArg, args);
  119. };
  120. }
  121. /**
  122. * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
  123. *
  124. * @param func - The constructor function to be wrapped and called.
  125. * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
  126. */
  127. function unconstruct(Func) {
  128. return function () {
  129. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  130. args[_key4] = arguments[_key4];
  131. }
  132. return construct(Func, args);
  133. };
  134. }
  135. /**
  136. * Add properties to a lookup table
  137. *
  138. * @param set - The set to which elements will be added.
  139. * @param array - The array containing elements to be added to the set.
  140. * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
  141. * @returns The modified set with added elements.
  142. */
  143. function addToSet(set, array) {
  144. let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
  145. if (setPrototypeOf) {
  146. // Make 'in' and truthy checks like Boolean(set.constructor)
  147. // independent of any properties defined on Object.prototype.
  148. // Prevent prototype setters from intercepting set as a this value.
  149. setPrototypeOf(set, null);
  150. }
  151. if (!arrayIsArray(array)) {
  152. return set;
  153. }
  154. let l = array.length;
  155. while (l--) {
  156. let element = array[l];
  157. if (typeof element === 'string') {
  158. const lcElement = transformCaseFunc(element);
  159. if (lcElement !== element) {
  160. // Config presets (e.g. tags.js, attrs.js) are immutable.
  161. if (!isFrozen(array)) {
  162. array[l] = lcElement;
  163. }
  164. element = lcElement;
  165. }
  166. }
  167. set[element] = true;
  168. }
  169. return set;
  170. }
  171. /**
  172. * Clean up an array to harden against CSPP
  173. *
  174. * @param array - The array to be cleaned.
  175. * @returns The cleaned version of the array
  176. */
  177. function cleanArray(array) {
  178. for (let index = 0; index < array.length; index++) {
  179. const isPropertyExist = objectHasOwnProperty(array, index);
  180. if (!isPropertyExist) {
  181. array[index] = null;
  182. }
  183. }
  184. return array;
  185. }
  186. /**
  187. * Shallow clone an object
  188. *
  189. * @param object - The object to be cloned.
  190. * @returns A new object that copies the original.
  191. */
  192. function clone(object) {
  193. const newObject = create(null);
  194. for (const _ref2 of entries(object)) {
  195. var _ref3 = _slicedToArray(_ref2, 2);
  196. const property = _ref3[0];
  197. const value = _ref3[1];
  198. const isPropertyExist = objectHasOwnProperty(object, property);
  199. if (isPropertyExist) {
  200. if (arrayIsArray(value)) {
  201. newObject[property] = cleanArray(value);
  202. } else if (value && typeof value === 'object' && value.constructor === Object) {
  203. newObject[property] = clone(value);
  204. } else {
  205. newObject[property] = value;
  206. }
  207. }
  208. }
  209. return newObject;
  210. }
  211. /**
  212. * Convert non-node values into strings without depending on direct property access.
  213. *
  214. * @param value - The value to stringify.
  215. * @returns A string representation of the provided value.
  216. */
  217. function stringifyValue(value) {
  218. switch (typeof value) {
  219. case 'string':
  220. {
  221. return value;
  222. }
  223. case 'number':
  224. {
  225. return numberToString(value);
  226. }
  227. case 'boolean':
  228. {
  229. return booleanToString(value);
  230. }
  231. case 'bigint':
  232. {
  233. return bigintToString ? bigintToString(value) : '0';
  234. }
  235. case 'symbol':
  236. {
  237. return symbolToString ? symbolToString(value) : 'Symbol()';
  238. }
  239. case 'undefined':
  240. {
  241. return objectToString(value);
  242. }
  243. case 'function':
  244. case 'object':
  245. {
  246. if (value === null) {
  247. return objectToString(value);
  248. }
  249. const valueAsRecord = value;
  250. const valueToString = lookupGetter(valueAsRecord, 'toString');
  251. if (typeof valueToString === 'function') {
  252. const stringified = valueToString(valueAsRecord);
  253. return typeof stringified === 'string' ? stringified : objectToString(stringified);
  254. }
  255. return objectToString(value);
  256. }
  257. default:
  258. {
  259. return objectToString(value);
  260. }
  261. }
  262. }
  263. /**
  264. * This method automatically checks if the prop is function or getter and behaves accordingly.
  265. *
  266. * @param object - The object to look up the getter function in its prototype chain.
  267. * @param prop - The property name for which to find the getter function.
  268. * @returns The getter function found in the prototype chain or a fallback function.
  269. */
  270. function lookupGetter(object, prop) {
  271. while (object !== null) {
  272. const desc = getOwnPropertyDescriptor(object, prop);
  273. if (desc) {
  274. if (desc.get) {
  275. return unapply(desc.get);
  276. }
  277. if (typeof desc.value === 'function') {
  278. return unapply(desc.value);
  279. }
  280. }
  281. object = getPrototypeOf(object);
  282. }
  283. function fallbackValue() {
  284. return null;
  285. }
  286. return fallbackValue;
  287. }
  288. function isRegex(value) {
  289. try {
  290. regExpTest(value, '');
  291. return true;
  292. } catch (_unused) {
  293. return false;
  294. }
  295. }
  296. const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', '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']);
  297. const 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', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
  298. const 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']);
  299. // List of SVG elements that are disallowed by default.
  300. // We still need to know them so that we can do namespace
  301. // checks properly in case one wants to add them to
  302. // allow-list.
  303. const 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']);
  304. const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
  305. // Similarly to SVG, we want to know all MathML elements,
  306. // even those that we disallow by default.
  307. const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
  308. const text = freeze(['#text']);
  309. const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', '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']);
  310. const 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', 'mask-type', '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']);
  311. const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', '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']);
  312. const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
  313. const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
  314. const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
  315. const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
  316. const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
  317. const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
  318. const 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-escape
  319. );
  320. const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  321. const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
  322. );
  323. const DOCTYPE_NAME = seal(/^html$/i);
  324. const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
  325. // Markup-significant character probes used by _sanitizeElements.
  326. // Shared module-level instances are safe despite the sticky /g flags:
  327. // unapply() resets lastIndex for RegExp receivers before every call.
  328. const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
  329. const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
  330. const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
  331. const SELF_CLOSING_TAG = seal(/\/>/i);
  332. /* eslint-disable @typescript-eslint/indent */
  333. // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
  334. const NODE_TYPE = {
  335. element: 1,
  336. attribute: 2,
  337. text: 3,
  338. cdataSection: 4,
  339. entityReference: 5,
  340. // Deprecated
  341. entityNode: 6,
  342. // Deprecated
  343. processingInstruction: 7,
  344. comment: 8,
  345. document: 9,
  346. documentType: 10,
  347. documentFragment: 11,
  348. notation: 12 // Deprecated
  349. };
  350. const getGlobal = function getGlobal() {
  351. return typeof window === 'undefined' ? null : window;
  352. };
  353. /**
  354. * Creates a no-op policy for internal use only.
  355. * Don't export this function outside this module!
  356. * @param trustedTypes The policy factory.
  357. * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
  358. * @return The policy created (or null, if Trusted Types
  359. * are not supported or creating the policy failed).
  360. */
  361. const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
  362. if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  363. return null;
  364. }
  365. // Allow the callers to control the unique policy name
  366. // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
  367. // Policy creation with duplicate names throws in Trusted Types.
  368. let suffix = null;
  369. const ATTR_NAME = 'data-tt-policy-suffix';
  370. if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
  371. suffix = purifyHostElement.getAttribute(ATTR_NAME);
  372. }
  373. const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  374. try {
  375. return trustedTypes.createPolicy(policyName, {
  376. createHTML(html) {
  377. return html;
  378. },
  379. createScriptURL(scriptUrl) {
  380. return scriptUrl;
  381. }
  382. });
  383. } catch (_) {
  384. // Policy creation failed (most likely another DOMPurify script has
  385. // already run). Skip creating the policy, as this will only cause errors
  386. // if TT are enforced.
  387. console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  388. return null;
  389. }
  390. };
  391. const _createHooksMap = function _createHooksMap() {
  392. return {
  393. afterSanitizeAttributes: [],
  394. afterSanitizeElements: [],
  395. afterSanitizeShadowDOM: [],
  396. beforeSanitizeAttributes: [],
  397. beforeSanitizeElements: [],
  398. beforeSanitizeShadowDOM: [],
  399. uponSanitizeAttribute: [],
  400. uponSanitizeElement: [],
  401. uponSanitizeShadowNode: []
  402. };
  403. };
  404. /**
  405. * Resolve a set-valued configuration option: a fresh set built from
  406. * cfg[key] when it is an own array property (seeded with a clone of
  407. * options.base when given, case-normalized via options.transform),
  408. * the fallback set otherwise.
  409. *
  410. * @param cfg the cloned, prototype-free configuration object
  411. * @param key the configuration property to read
  412. * @param fallback the set to use when the option is absent or not an array
  413. * @param options transform and optional base set to merge into
  414. * @returns the resolved set
  415. */
  416. const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
  417. return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
  418. };
  419. function createDOMPurify() {
  420. let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  421. const DOMPurify = root => createDOMPurify(root);
  422. DOMPurify.version = '3.4.10';
  423. DOMPurify.removed = [];
  424. if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
  425. // Not running in a browser, provide a factory function
  426. // so that you can pass your own Window
  427. DOMPurify.isSupported = false;
  428. return DOMPurify;
  429. }
  430. let document = window.document;
  431. const originalDocument = document;
  432. const currentScript = originalDocument.currentScript;
  433. window.DocumentFragment;
  434. const HTMLTemplateElement = window.HTMLTemplateElement,
  435. Node = window.Node,
  436. Element = window.Element,
  437. NodeFilter = window.NodeFilter,
  438. _window$NamedNodeMap = window.NamedNodeMap;
  439. _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
  440. window.HTMLFormElement;
  441. const DOMParser = window.DOMParser,
  442. trustedTypes = window.trustedTypes;
  443. const ElementPrototype = Element.prototype;
  444. const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  445. const remove = lookupGetter(ElementPrototype, 'remove');
  446. const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  447. const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  448. const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  449. const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
  450. const getAttributes = lookupGetter(ElementPrototype, 'attributes');
  451. const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
  452. const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
  453. // As per issue #47, the web-components registry is inherited by a
  454. // new document created via createHTMLDocument. As per the spec
  455. // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
  456. // a new empty registry is used when creating a template contents owner
  457. // document, so we use that as our parent document to ensure nothing
  458. // is inherited.
  459. if (typeof HTMLTemplateElement === 'function') {
  460. const template = document.createElement('template');
  461. if (template.content && template.content.ownerDocument) {
  462. document = template.content.ownerDocument;
  463. }
  464. }
  465. let trustedTypesPolicy;
  466. let emptyHTML = '';
  467. // The instance's own internal Trusted Types policy. Unlike a caller-supplied
  468. // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
  469. // on duplicate policy names — and is the only policy allowed to persist
  470. // across configurations and survive `clearConfig()`.
  471. let defaultTrustedTypesPolicy;
  472. let defaultTrustedTypesPolicyResolved = false;
  473. // Tracks whether we are already inside a call to the configured Trusted Types
  474. // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
  475. // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
  476. // re-enter the policy and recurse until the stack overflows. We detect that
  477. // re-entry and throw a clear, actionable error instead. The guard is shared
  478. // across both callbacks, because either one re-entering `sanitize` triggers
  479. // the same unbounded recursion.
  480. let IN_TRUSTED_TYPES_POLICY = 0;
  481. const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
  482. if (IN_TRUSTED_TYPES_POLICY > 0) {
  483. throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted ' + 'Types" section of the README.');
  484. }
  485. };
  486. const _createTrustedHTML = function _createTrustedHTML(html) {
  487. _assertNotInTrustedTypesPolicy();
  488. IN_TRUSTED_TYPES_POLICY++;
  489. try {
  490. return trustedTypesPolicy.createHTML(html);
  491. } finally {
  492. IN_TRUSTED_TYPES_POLICY--;
  493. }
  494. };
  495. const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
  496. _assertNotInTrustedTypesPolicy();
  497. IN_TRUSTED_TYPES_POLICY++;
  498. try {
  499. return trustedTypesPolicy.createScriptURL(scriptUrl);
  500. } finally {
  501. IN_TRUSTED_TYPES_POLICY--;
  502. }
  503. };
  504. // Lazily resolve (and cache) the instance's internal default policy.
  505. // Resolution is attempted at most once: a successful `createPolicy` cannot be
  506. // repeated (Trusted Types throws on duplicate names), and a failed or
  507. // unsupported attempt must not be retried on every parse.
  508. const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
  509. if (!defaultTrustedTypesPolicyResolved) {
  510. defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
  511. defaultTrustedTypesPolicyResolved = true;
  512. }
  513. return defaultTrustedTypesPolicy;
  514. };
  515. const _document = document,
  516. implementation = _document.implementation,
  517. createNodeIterator = _document.createNodeIterator,
  518. createDocumentFragment = _document.createDocumentFragment,
  519. getElementsByTagName = _document.getElementsByTagName;
  520. const importNode = originalDocument.importNode;
  521. let hooks = _createHooksMap();
  522. /**
  523. * Expose whether this browser supports running the full DOMPurify.
  524. */
  525. DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
  526. const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
  527. ERB_EXPR$1 = ERB_EXPR,
  528. TMPLIT_EXPR$1 = TMPLIT_EXPR,
  529. DATA_ATTR$1 = DATA_ATTR,
  530. ARIA_ATTR$1 = ARIA_ATTR,
  531. IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
  532. ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
  533. CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
  534. let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
  535. /**
  536. * We consider the elements and attributes below to be safe. Ideally
  537. * don't add any new ones but feel free to remove unwanted ones.
  538. */
  539. /* allowed element names */
  540. let ALLOWED_TAGS = null;
  541. const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
  542. /* Allowed attribute names */
  543. let ALLOWED_ATTR = null;
  544. const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
  545. /*
  546. * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
  547. * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
  548. * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
  549. * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
  550. */
  551. let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
  552. tagNameCheck: {
  553. writable: true,
  554. configurable: false,
  555. enumerable: true,
  556. value: null
  557. },
  558. attributeNameCheck: {
  559. writable: true,
  560. configurable: false,
  561. enumerable: true,
  562. value: null
  563. },
  564. allowCustomizedBuiltInElements: {
  565. writable: true,
  566. configurable: false,
  567. enumerable: true,
  568. value: false
  569. }
  570. }));
  571. /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
  572. let FORBID_TAGS = null;
  573. /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
  574. let FORBID_ATTR = null;
  575. /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
  576. const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
  577. tagCheck: {
  578. writable: true,
  579. configurable: false,
  580. enumerable: true,
  581. value: null
  582. },
  583. attributeCheck: {
  584. writable: true,
  585. configurable: false,
  586. enumerable: true,
  587. value: null
  588. }
  589. }));
  590. /* Decide if ARIA attributes are okay */
  591. let ALLOW_ARIA_ATTR = true;
  592. /* Decide if custom data attributes are okay */
  593. let ALLOW_DATA_ATTR = true;
  594. /* Decide if unknown protocols are okay */
  595. let ALLOW_UNKNOWN_PROTOCOLS = false;
  596. /* Decide if self-closing tags in attributes are allowed.
  597. * Usually removed due to a mXSS issue in jQuery 3.0 */
  598. let ALLOW_SELF_CLOSE_IN_ATTR = true;
  599. /* Output should be safe for common template engines.
  600. * This means, DOMPurify removes data attributes, mustaches and ERB
  601. */
  602. let SAFE_FOR_TEMPLATES = false;
  603. /* Output should be safe even for XML used within HTML and alike.
  604. * This means, DOMPurify removes comments when containing risky content.
  605. */
  606. let SAFE_FOR_XML = true;
  607. /* Decide if document with <html>... should be returned */
  608. let WHOLE_DOCUMENT = false;
  609. /* Track whether config is already set on this instance of DOMPurify. */
  610. let SET_CONFIG = false;
  611. /* Decide if all elements (e.g. style, script) must be children of
  612. * document.body. By default, browsers might move them to document.head */
  613. let FORCE_BODY = false;
  614. /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
  615. * string (or a TrustedHTML object if Trusted Types are supported).
  616. * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
  617. */
  618. let RETURN_DOM = false;
  619. /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
  620. * string (or a TrustedHTML object if Trusted Types are supported) */
  621. let RETURN_DOM_FRAGMENT = false;
  622. /* Try to return a Trusted Type object instead of a string, return a string in
  623. * case Trusted Types are not supported */
  624. let RETURN_TRUSTED_TYPE = false;
  625. /* Output should be free from DOM clobbering attacks?
  626. * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
  627. */
  628. let SANITIZE_DOM = true;
  629. /* Achieve full DOM Clobbering protection by isolating the namespace of named
  630. * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
  631. *
  632. * HTML/DOM spec rules that enable DOM Clobbering:
  633. * - Named Access on Window (§7.3.3)
  634. * - DOM Tree Accessors (§3.1.5)
  635. * - Form Element Parent-Child Relations (§4.10.3)
  636. * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
  637. * - HTMLCollection (§4.2.10.2)
  638. *
  639. * Namespace isolation is implemented by prefixing `id` and `name` attributes
  640. * with a constant string, i.e., `user-content-`
  641. */
  642. let SANITIZE_NAMED_PROPS = false;
  643. const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
  644. /* Keep element content when removing element? */
  645. let KEEP_CONTENT = true;
  646. /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
  647. * of importing it into a new Document and returning a sanitized copy */
  648. let IN_PLACE = false;
  649. /* Allow usage of profiles like html, svg and mathMl */
  650. let USE_PROFILES = {};
  651. /* Tags to ignore content of when KEEP_CONTENT is true */
  652. let FORBID_CONTENTS = null;
  653. const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
  654. // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
  655. // the UA (customizable <select>) — including any on* handlers — and the
  656. // engine re-mirrors synchronously whenever a removal changes which
  657. // option/selectedcontent is current, even inside DOMPurify's inert
  658. // DOMParser document. Hoisting its children on removal re-inserts a fresh
  659. // mirror target ahead of the walk, which the engine refills, looping
  660. // forever (DoS) and amplifying output. Dropping its content on removal
  661. // (rather than hoisting) breaks that cascade; the content is a duplicate
  662. // of the option, which is sanitized on its own. See campaign-3 F1/F6.
  663. 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
  664. /* Tags that are safe for data: URIs */
  665. let DATA_URI_TAGS = null;
  666. const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
  667. /* Attributes safe for values like "javascript:" */
  668. let URI_SAFE_ATTRIBUTES = null;
  669. const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
  670. const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  671. const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  672. const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  673. /* Document namespace */
  674. let NAMESPACE = HTML_NAMESPACE;
  675. let IS_EMPTY_INPUT = false;
  676. /* Allowed XHTML+XML namespaces */
  677. let ALLOWED_NAMESPACES = null;
  678. const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
  679. const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
  680. let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
  681. const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
  682. let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
  683. // Certain elements are allowed in both SVG and HTML
  684. // namespace. We need to specify them explicitly
  685. // so that they don't get erroneously deleted from
  686. // HTML namespace.
  687. const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
  688. /* Parsing of strict XHTML documents */
  689. let PARSER_MEDIA_TYPE = null;
  690. const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
  691. const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  692. let transformCaseFunc = null;
  693. /* Keep a reference to config to pass to hooks */
  694. let CONFIG = null;
  695. /* Ideally, do not touch anything below this line */
  696. /* ______________________________________________ */
  697. const formElement = document.createElement('form');
  698. const isRegexOrFunction = function isRegexOrFunction(testValue) {
  699. return testValue instanceof RegExp || testValue instanceof Function;
  700. };
  701. /**
  702. * _parseConfig
  703. *
  704. * @param cfg optional config literal
  705. */
  706. // eslint-disable-next-line complexity
  707. const _parseConfig = function _parseConfig() {
  708. let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  709. if (CONFIG && CONFIG === cfg) {
  710. return;
  711. }
  712. /* Shield configuration object from tampering */
  713. if (!cfg || typeof cfg !== 'object') {
  714. cfg = {};
  715. }
  716. /* Shield configuration object from prototype pollution */
  717. cfg = clone(cfg);
  718. PARSER_MEDIA_TYPE =
  719. // eslint-disable-next-line unicorn/prefer-includes
  720. SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
  721. // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
  722. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
  723. /* Set configuration parameters */
  724. ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
  725. transform: transformCaseFunc
  726. });
  727. ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
  728. transform: transformCaseFunc
  729. });
  730. ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
  731. transform: stringToString
  732. });
  733. URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
  734. transform: transformCaseFunc,
  735. base: DEFAULT_URI_SAFE_ATTRIBUTES
  736. });
  737. DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
  738. transform: transformCaseFunc,
  739. base: DEFAULT_DATA_URI_TAGS
  740. });
  741. FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
  742. transform: transformCaseFunc
  743. });
  744. FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
  745. transform: transformCaseFunc
  746. });
  747. FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
  748. transform: transformCaseFunc
  749. });
  750. USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
  751. ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
  752. ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
  753. ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
  754. ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
  755. SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
  756. SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
  757. WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
  758. RETURN_DOM = cfg.RETURN_DOM || false; // Default false
  759. RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
  760. RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
  761. FORCE_BODY = cfg.FORCE_BODY || false; // Default false
  762. SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
  763. SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
  764. KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
  765. IN_PLACE = cfg.IN_PLACE || false; // Default false
  766. IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
  767. NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
  768. MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map
  769. HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map
  770. const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
  771. CUSTOM_ELEMENT_HANDLING = create(null);
  772. if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
  773. CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
  774. }
  775. if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
  776. CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
  777. }
  778. if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
  779. CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
  780. }
  781. seal(CUSTOM_ELEMENT_HANDLING);
  782. if (SAFE_FOR_TEMPLATES) {
  783. ALLOW_DATA_ATTR = false;
  784. }
  785. if (RETURN_DOM_FRAGMENT) {
  786. RETURN_DOM = true;
  787. }
  788. /* Parse profile info */
  789. if (USE_PROFILES) {
  790. ALLOWED_TAGS = addToSet({}, text);
  791. ALLOWED_ATTR = create(null);
  792. if (USE_PROFILES.html === true) {
  793. addToSet(ALLOWED_TAGS, html$1);
  794. addToSet(ALLOWED_ATTR, html);
  795. }
  796. if (USE_PROFILES.svg === true) {
  797. addToSet(ALLOWED_TAGS, svg$1);
  798. addToSet(ALLOWED_ATTR, svg);
  799. addToSet(ALLOWED_ATTR, xml);
  800. }
  801. if (USE_PROFILES.svgFilters === true) {
  802. addToSet(ALLOWED_TAGS, svgFilters);
  803. addToSet(ALLOWED_ATTR, svg);
  804. addToSet(ALLOWED_ATTR, xml);
  805. }
  806. if (USE_PROFILES.mathMl === true) {
  807. addToSet(ALLOWED_TAGS, mathMl$1);
  808. addToSet(ALLOWED_ATTR, mathMl);
  809. addToSet(ALLOWED_ATTR, xml);
  810. }
  811. }
  812. /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
  813. * leaking across calls when switching from function to array config */
  814. EXTRA_ELEMENT_HANDLING.tagCheck = null;
  815. EXTRA_ELEMENT_HANDLING.attributeCheck = null;
  816. /* Merge configuration parameters */
  817. if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
  818. if (typeof cfg.ADD_TAGS === 'function') {
  819. EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
  820. } else if (arrayIsArray(cfg.ADD_TAGS)) {
  821. if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  822. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  823. }
  824. addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
  825. }
  826. }
  827. if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
  828. if (typeof cfg.ADD_ATTR === 'function') {
  829. EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
  830. } else if (arrayIsArray(cfg.ADD_ATTR)) {
  831. if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  832. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  833. }
  834. addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
  835. }
  836. }
  837. if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
  838. addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
  839. }
  840. if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
  841. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  842. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  843. }
  844. addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
  845. }
  846. if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
  847. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  848. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  849. }
  850. addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
  851. }
  852. /* Add #text in case KEEP_CONTENT is set to true */
  853. if (KEEP_CONTENT) {
  854. ALLOWED_TAGS['#text'] = true;
  855. }
  856. /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
  857. if (WHOLE_DOCUMENT) {
  858. addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
  859. }
  860. /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
  861. if (ALLOWED_TAGS.table) {
  862. addToSet(ALLOWED_TAGS, ['tbody']);
  863. delete FORBID_TAGS.tbody;
  864. }
  865. // Re-derive the active Trusted Types policy from this configuration on
  866. // every parse. The active policy must never be sticky closure state that
  867. // outlives the config that set it: a caller-supplied policy left in place
  868. // after `clearConfig()` — or after a later call that supplied none, or
  869. // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
  870. // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
  871. // See GHSA-vxr8-fq34-vvx9.
  872. if (cfg.TRUSTED_TYPES_POLICY) {
  873. if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
  874. throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
  875. }
  876. if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
  877. throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
  878. }
  879. // A caller-supplied policy applies to this configuration only.
  880. const previousTrustedTypesPolicy = trustedTypesPolicy;
  881. trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
  882. // Sign local variables required by `sanitize`. If the supplied policy's
  883. // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
  884. // throws via the re-entrancy guard. Restore the previous policy first so
  885. // the instance is not left in a poisoned state. See #1422.
  886. try {
  887. emptyHTML = _createTrustedHTML('');
  888. } catch (error) {
  889. trustedTypesPolicy = previousTrustedTypesPolicy;
  890. throw error;
  891. }
  892. } else if (cfg.TRUSTED_TYPES_POLICY === null) {
  893. // Explicit opt-out for this call: perform no Trusted Types signing and
  894. // create nothing (so a strict `trusted-types` CSP that disallows a
  895. // `dompurify` policy can still call `sanitize` from inside its own
  896. // policy — see #1422). Resetting to `undefined` rather than a sticky
  897. // `null` also drops any previously retained caller policy, so it cannot
  898. // resurface on a later call, while still allowing the next config-less
  899. // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
  900. trustedTypesPolicy = undefined;
  901. emptyHTML = '';
  902. } else {
  903. // No policy supplied: keep the currently active policy if one is set — a
  904. // previously supplied policy is intentionally sticky across config-less
  905. // calls — otherwise fall back to the instance's own internal policy,
  906. // created at most once. (A policy supplied for a *single* call still
  907. // lingers by design; what must not linger is a policy whose configuration
  908. // has been torn down via `clearConfig()`, which restores the default.)
  909. if (trustedTypesPolicy === undefined) {
  910. trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
  911. }
  912. // Sign internal variables only when a policy is active. A falsy policy
  913. // (Trusted Types unsupported, creation failed, or an explicit opt-out)
  914. // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
  915. // a non-policy and throw. See #1422.
  916. if (trustedTypesPolicy && typeof emptyHTML === 'string') {
  917. emptyHTML = _createTrustedHTML('');
  918. }
  919. }
  920. /*
  921. * Mirror the clone-before-mutate pattern already applied above for
  922. * cfg.ADD_TAGS / cfg.ADD_ATTR: if any uponSanitize* hook is
  923. * registered AND the set still points at the default constant,
  924. * clone it. The hook then mutates the clone (in-call widening
  925. * still works exactly as documented) and the next default-cfg
  926. * call rebinds to the untouched original via the reassignment at
  927. * the top of this function.
  928. */
  929. if ((hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) && ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  930. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  931. }
  932. if (hooks.uponSanitizeAttribute.length > 0 && ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  933. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  934. }
  935. // Prevent further manipulation of configuration.
  936. // Not available in IE8, Safari 5, etc.
  937. if (freeze) {
  938. freeze(cfg);
  939. }
  940. CONFIG = cfg;
  941. };
  942. /* Keep track of all possible SVG and MathML tags
  943. * so that we can perform the namespace checks
  944. * correctly. */
  945. const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
  946. const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
  947. /**
  948. * Namespace rules for an element in the SVG namespace.
  949. *
  950. * @param tagName the element's lowercase tag name
  951. * @param parent the (possibly simulated) parent node
  952. * @param parentTagName the parent's lowercase tag name
  953. * @returns true if a spec-compliant parser could produce this element
  954. */
  955. const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
  956. // The only way to switch from HTML namespace to SVG
  957. // is via <svg>. If it happens via any other tag, then
  958. // it should be killed.
  959. if (parent.namespaceURI === HTML_NAMESPACE) {
  960. return tagName === 'svg';
  961. }
  962. // The only way to switch from MathML to SVG is via <svg>
  963. // if the parent is either <annotation-xml> or a MathML
  964. // text integration point.
  965. if (parent.namespaceURI === MATHML_NAMESPACE) {
  966. return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  967. }
  968. // We only allow elements that are defined in SVG
  969. // spec. All others are disallowed in SVG namespace.
  970. return Boolean(ALL_SVG_TAGS[tagName]);
  971. };
  972. /**
  973. * Namespace rules for an element in the MathML namespace.
  974. *
  975. * @param tagName the element's lowercase tag name
  976. * @param parent the (possibly simulated) parent node
  977. * @param parentTagName the parent's lowercase tag name
  978. * @returns true if a spec-compliant parser could produce this element
  979. */
  980. const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
  981. // The only way to switch from HTML namespace to MathML
  982. // is via <math>. If it happens via any other tag, then
  983. // it should be killed.
  984. if (parent.namespaceURI === HTML_NAMESPACE) {
  985. return tagName === 'math';
  986. }
  987. // The only way to switch from SVG to MathML is via
  988. // <math> and HTML integration points
  989. if (parent.namespaceURI === SVG_NAMESPACE) {
  990. return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  991. }
  992. // We only allow elements that are defined in MathML
  993. // spec. All others are disallowed in MathML namespace.
  994. return Boolean(ALL_MATHML_TAGS[tagName]);
  995. };
  996. /**
  997. * Namespace rules for an element in the HTML namespace.
  998. *
  999. * @param tagName the element's lowercase tag name
  1000. * @param parent the (possibly simulated) parent node
  1001. * @param parentTagName the parent's lowercase tag name
  1002. * @returns true if a spec-compliant parser could produce this element
  1003. */
  1004. const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
  1005. // The only way to switch from SVG to HTML is via
  1006. // HTML integration points, and from MathML to HTML
  1007. // is via MathML text integration points
  1008. if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  1009. return false;
  1010. }
  1011. if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  1012. return false;
  1013. }
  1014. // We disallow tags that are specific for MathML
  1015. // or SVG and should never appear in HTML namespace
  1016. return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
  1017. };
  1018. /**
  1019. * @param element a DOM element whose namespace is being checked
  1020. * @returns Return false if the element has a
  1021. * namespace that a spec-compliant parser would never
  1022. * return. Return true otherwise.
  1023. */
  1024. const _checkValidNamespace = function _checkValidNamespace(element) {
  1025. let parent = getParentNode(element);
  1026. // In JSDOM, if we're inside shadow DOM, then parentNode
  1027. // can be null. We just simulate parent in this case.
  1028. if (!parent || !parent.tagName) {
  1029. parent = {
  1030. namespaceURI: NAMESPACE,
  1031. tagName: 'template'
  1032. };
  1033. }
  1034. const tagName = stringToLowerCase(element.tagName);
  1035. const parentTagName = stringToLowerCase(parent.tagName);
  1036. if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
  1037. return false;
  1038. }
  1039. if (element.namespaceURI === SVG_NAMESPACE) {
  1040. return _checkSvgNamespace(tagName, parent, parentTagName);
  1041. }
  1042. if (element.namespaceURI === MATHML_NAMESPACE) {
  1043. return _checkMathMlNamespace(tagName, parent, parentTagName);
  1044. }
  1045. if (element.namespaceURI === HTML_NAMESPACE) {
  1046. return _checkHtmlNamespace(tagName, parent, parentTagName);
  1047. }
  1048. // For XHTML and XML documents that support custom namespaces
  1049. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
  1050. return true;
  1051. }
  1052. // The code should never reach this place (this means
  1053. // that the element somehow got namespace that is not
  1054. // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
  1055. // Return false just in case.
  1056. return false;
  1057. };
  1058. /**
  1059. * _forceRemove
  1060. *
  1061. * @param node a DOM node
  1062. */
  1063. const _forceRemove = function _forceRemove(node) {
  1064. arrayPush(DOMPurify.removed, {
  1065. element: node
  1066. });
  1067. try {
  1068. // eslint-disable-next-line unicorn/prefer-dom-node-remove
  1069. getParentNode(node).removeChild(node);
  1070. } catch (_) {
  1071. /* The normal detach failed — this is reached for a parentless node
  1072. (getParentNode() is null, so .removeChild throws). Element.prototype
  1073. .remove() is itself a spec no-op on a parentless node, so a recorded
  1074. "removal" would otherwise hand the caller back an intact,
  1075. payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
  1076. the style-with-element-child rule decided to kill). Fail closed by
  1077. throwing — exactly as a clobbered root does at the IN_PLACE entry —
  1078. rather than trying to "neutralize" the node via its own methods.
  1079. Neutralizing would mean calling getAttributeNames()/removeAttribute()
  1080. on the node, both of which a <form> root can clobber via a named child
  1081. (and _isClobbered does not even probe getAttributeNames), so the
  1082. neutralize step could itself be silently defeated, leaving the payload
  1083. intact. A throw touches only the cached, clobber-safe remove() and
  1084. getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
  1085. to every root-kill reason. REPORT-3.
  1086. This lives inside the catch, so it never fires for a normally-removed
  1087. in-tree node: those have a parent, removeChild() succeeds, and the
  1088. catch is not entered. Only a kept (parentless) root reaches here. */
  1089. remove(node);
  1090. if (!getParentNode(node)) {
  1091. throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
  1092. }
  1093. }
  1094. };
  1095. /**
  1096. * _neutralizeRoot
  1097. *
  1098. * Fail-closed teardown of an in-place root after the sanitize walk aborts
  1099. * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
  1100. * custom element's reaction detaches a node so `_forceRemove`'s deliberate
  1101. * parentless guard throws, or any other re-entrant engine mutation — would
  1102. * otherwise leave the caller's *live* tree half-sanitized, with everything
  1103. * after the abort point still carrying its handlers. There is no safe way
  1104. * to resume the walk (the tree mutated under us), so we strip the root bare:
  1105. * remove every child and every attribute, then let the caller's catch see
  1106. * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
  1107. * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
  1108. *
  1109. * @param root the in-place root to empty
  1110. */
  1111. const _neutralizeRoot = function _neutralizeRoot(root) {
  1112. const childNodes = getChildNodes(root);
  1113. if (childNodes) {
  1114. const snapshot = [];
  1115. arrayForEach(childNodes, child => {
  1116. arrayPush(snapshot, child);
  1117. });
  1118. arrayForEach(snapshot, child => {
  1119. try {
  1120. remove(child);
  1121. } catch (_) {
  1122. /* Best-effort teardown; a still-attached child is handled below */
  1123. }
  1124. });
  1125. }
  1126. const attributes = getAttributes(root);
  1127. if (attributes) {
  1128. for (let i = attributes.length - 1; i >= 0; --i) {
  1129. const attribute = attributes[i];
  1130. const name = attribute && attribute.name;
  1131. if (typeof name === 'string') {
  1132. try {
  1133. root.removeAttribute(name);
  1134. } catch (_) {
  1135. /* Clobbered removeAttribute — ignore (fail-closed best effort) */
  1136. }
  1137. }
  1138. }
  1139. }
  1140. };
  1141. /**
  1142. * _removeAttribute
  1143. *
  1144. * @param name an Attribute name
  1145. * @param element a DOM node
  1146. */
  1147. const _removeAttribute = function _removeAttribute(name, element) {
  1148. try {
  1149. arrayPush(DOMPurify.removed, {
  1150. attribute: element.getAttributeNode(name),
  1151. from: element
  1152. });
  1153. } catch (_) {
  1154. arrayPush(DOMPurify.removed, {
  1155. attribute: null,
  1156. from: element
  1157. });
  1158. }
  1159. element.removeAttribute(name);
  1160. // We void attribute values for unremovable "is" attributes
  1161. if (name === 'is') {
  1162. if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  1163. try {
  1164. _forceRemove(element);
  1165. } catch (_) {}
  1166. } else {
  1167. try {
  1168. element.setAttribute(name, '');
  1169. } catch (_) {}
  1170. }
  1171. }
  1172. };
  1173. /**
  1174. * _stripDisallowedAttributes
  1175. *
  1176. * Removes every attribute the active configuration does not allow from a
  1177. * single element, using the same allowlist as the main attribute pass (so
  1178. * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
  1179. * neutralise nodes that are being discarded from an in-place tree.
  1180. *
  1181. * @param element the element to strip
  1182. */
  1183. const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
  1184. const attributes = getAttributes(element);
  1185. if (!attributes) {
  1186. return;
  1187. }
  1188. for (let i = attributes.length - 1; i >= 0; --i) {
  1189. const attribute = attributes[i];
  1190. const name = attribute && attribute.name;
  1191. if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
  1192. continue;
  1193. }
  1194. try {
  1195. element.removeAttribute(name);
  1196. } catch (_) {
  1197. /* Clobbered removeAttribute on a doomed node — ignore */
  1198. }
  1199. }
  1200. };
  1201. /**
  1202. * _neutralizeSubtree
  1203. *
  1204. * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
  1205. * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
  1206. * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
  1207. * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
  1208. * those dropped nodes are detached from the caller's LIVE tree but a
  1209. * handler-bearing original among them (an `<img onerror>`/`<video>` that was
  1210. * loading) keeps its queued resource event, which fires in page scope after
  1211. * sanitize returns. This walks a removed subtree and strips every attribute
  1212. * the active configuration does not allow — so `on*` handlers are cancelled
  1213. * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
  1214. * blocklist. Run synchronously before sanitize returns, i.e. before any
  1215. * queued event can fire. Hook-free by design: these nodes leave the output,
  1216. * so firing attribute hooks for them would be surprising. Clobber-safe reads;
  1217. * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
  1218. * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
  1219. * the `<img>`, are reached and scrubbed).
  1220. *
  1221. * @param root the root of a removed subtree to neutralise
  1222. */
  1223. const _neutralizeSubtree = function _neutralizeSubtree(root) {
  1224. const stack = [root];
  1225. while (stack.length > 0) {
  1226. const node = stack.pop();
  1227. const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
  1228. if (nodeType === NODE_TYPE.element) {
  1229. _stripDisallowedAttributes(node);
  1230. }
  1231. const childNodes = getChildNodes(node);
  1232. if (childNodes) {
  1233. for (let i = childNodes.length - 1; i >= 0; --i) {
  1234. stack.push(childNodes[i]);
  1235. }
  1236. }
  1237. }
  1238. };
  1239. /**
  1240. * _initDocument
  1241. *
  1242. * @param dirty - a string of dirty markup
  1243. * @return a DOM, filled with the dirty markup
  1244. */
  1245. const _initDocument = function _initDocument(dirty) {
  1246. /* Create a HTML document */
  1247. let doc = null;
  1248. let leadingWhitespace = null;
  1249. if (FORCE_BODY) {
  1250. dirty = '<remove></remove>' + dirty;
  1251. } else {
  1252. /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
  1253. const matches = stringMatch(dirty, /^[\r\n\t ]+/);
  1254. leadingWhitespace = matches && matches[0];
  1255. }
  1256. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
  1257. // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
  1258. dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
  1259. }
  1260. const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
  1261. /*
  1262. * Use the DOMParser API by default, fallback later if needs be
  1263. * DOMParser not work for svg when has multiple root element.
  1264. */
  1265. if (NAMESPACE === HTML_NAMESPACE) {
  1266. try {
  1267. doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
  1268. } catch (_) {}
  1269. }
  1270. /* Use createHTMLDocument in case DOMParser is not available */
  1271. if (!doc || !doc.documentElement) {
  1272. doc = implementation.createDocument(NAMESPACE, 'template', null);
  1273. try {
  1274. doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
  1275. } catch (_) {
  1276. // Syntax error if dirtyPayload is invalid xml
  1277. }
  1278. }
  1279. const body = doc.body || doc.documentElement;
  1280. if (dirty && leadingWhitespace) {
  1281. body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  1282. }
  1283. /* Work on whole document or just its body */
  1284. if (NAMESPACE === HTML_NAMESPACE) {
  1285. return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  1286. }
  1287. return WHOLE_DOCUMENT ? doc.documentElement : body;
  1288. };
  1289. /**
  1290. * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
  1291. *
  1292. * @param root The root element or node to start traversing on.
  1293. * @return The created NodeIterator
  1294. */
  1295. const _createNodeIterator = function _createNodeIterator(root) {
  1296. return createNodeIterator.call(root.ownerDocument || root, root,
  1297. // eslint-disable-next-line no-bitwise
  1298. NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
  1299. };
  1300. /**
  1301. * Replace template expression syntax (mustache, ERB, template
  1302. * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
  1303. * sites. Order matters: mustache, then ERB, then template literal.
  1304. *
  1305. * @param value the string to scrub
  1306. * @returns the scrubbed string
  1307. */
  1308. const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
  1309. value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
  1310. value = stringReplace(value, ERB_EXPR$1, ' ');
  1311. value = stringReplace(value, TMPLIT_EXPR$1, ' ');
  1312. return value;
  1313. };
  1314. /**
  1315. * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
  1316. * character data of an element subtree. Used as the final safety net for
  1317. * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
  1318. * which only form after text-node normalization (e.g. fragments split across
  1319. * stripped elements) cannot survive into a template-evaluating framework.
  1320. *
  1321. * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
  1322. * in place rather than round-tripping through innerHTML. This preserves
  1323. * descendant node references (important for IN_PLACE callers), avoids a
  1324. * serialize/reparse cycle, and reads literal character data — which means
  1325. * `<%...%>` in text content matches the ERB regex against its real bytes
  1326. * instead of the HTML-entity-escaped form innerHTML would produce.
  1327. *
  1328. * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
  1329. * attributes is performed during the per-node `_sanitizeAttributes` pass.
  1330. *
  1331. * @param node The root element whose character data should be scrubbed.
  1332. */
  1333. const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
  1334. var _node$querySelectorAl;
  1335. node.normalize();
  1336. const walker = createNodeIterator.call(node.ownerDocument || node, node,
  1337. // eslint-disable-next-line no-bitwise
  1338. NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
  1339. let currentNode = walker.nextNode();
  1340. while (currentNode) {
  1341. currentNode.data = _stripTemplateExpressions(currentNode.data);
  1342. currentNode = walker.nextNode();
  1343. }
  1344. // NodeIterator does not descend into <template>.content per the DOM spec,
  1345. // so we must explicitly recurse into each template's content fragment,
  1346. // mirroring the approach used by _sanitizeShadowDOM.
  1347. const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
  1348. if (templates) {
  1349. arrayForEach(templates, tmpl => {
  1350. if (_isDocumentFragment(tmpl.content)) {
  1351. _scrubTemplateExpressions2(tmpl.content);
  1352. }
  1353. });
  1354. }
  1355. };
  1356. /**
  1357. * _isClobbered
  1358. *
  1359. * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
  1360. * interface with [LegacyOverrideBuiltIns]; a descendant element with a
  1361. * `name` attribute matching a prototype property shadows that property
  1362. * on direct reads. We use this check at the IN_PLACE entry-point and
  1363. * during attribute sanitization to refuse clobbered forms.
  1364. *
  1365. * @param element element to check for clobbering attacks
  1366. * @return true if clobbered, false if safe
  1367. */
  1368. const _isClobbered = function _isClobbered(element) {
  1369. // Realm-independent tag-name probe. If we can't determine the tag
  1370. // name at all, we can't reason about clobbering — return false
  1371. // (the caller's other defences still apply).
  1372. const realTagName = getNodeName ? getNodeName(element) : null;
  1373. if (typeof realTagName !== 'string') {
  1374. return false;
  1375. }
  1376. if (transformCaseFunc(realTagName) !== 'form') {
  1377. return false;
  1378. }
  1379. return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
  1380. // Realm-safe NamedNodeMap detection: equality against the cached
  1381. // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
  1382. // makes the direct read diverge from the cached read; a clean form
  1383. // (same-realm OR foreign-realm) has both reads pointing at the same
  1384. // canonical NamedNodeMap.
  1385. element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
  1386. // NodeType clobbering probe. Cached Node.prototype.nodeType getter
  1387. // returns the integer 1 for any Element regardless of realm; direct
  1388. // read on a clobbered form (e.g. <input name="nodeType">) returns
  1389. // the named child element. Cheap addition — nodeType is read from
  1390. // an internal slot, no serialization cost — and removes a residual
  1391. // clobbering surface used by several mXSS / PI / comment branches
  1392. // in _sanitizeElements that compare currentNode.nodeType directly.
  1393. element.nodeType !== getNodeType(element) ||
  1394. // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
  1395. // "childNodes" shadows the prototype getter. Direct reads of
  1396. // form.childNodes from a clobbered form return the named child
  1397. // instead of the real NodeList, so any walk that reads it directly
  1398. // skips the form's real children. Compare the direct read to the
  1399. // cached Node.prototype getter — when the form's named-property
  1400. // getter intercepts the read, the two values differ and we flag
  1401. // the form. This catches every clobbering child type (input,
  1402. // select, etc.) regardless of whether the named child happens to
  1403. // carry a numeric .length, which a typeof-based probe would miss
  1404. // (e.g. HTMLSelectElement.length is a defined unsigned-long).
  1405. element.childNodes !== getChildNodes(element);
  1406. };
  1407. /**
  1408. * Checks whether the given value is a DocumentFragment from any realm.
  1409. *
  1410. * The realm-independent replacement reads `nodeType` through the cached
  1411. * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
  1412. * constant (11). nodeType is a numeric value resolved from the node's
  1413. * internal slot, identical across realms for the same kind of node.
  1414. *
  1415. * @param value object to check
  1416. * @return true if value is a DocumentFragment-shaped node from any realm
  1417. */
  1418. const _isDocumentFragment = function _isDocumentFragment(value) {
  1419. if (!getNodeType || typeof value !== 'object' || value === null) {
  1420. return false;
  1421. }
  1422. try {
  1423. return getNodeType(value) === NODE_TYPE.documentFragment;
  1424. } catch (_) {
  1425. return false;
  1426. }
  1427. };
  1428. /**
  1429. * Checks whether the given object is a DOM node, including nodes that
  1430. * originate from a different window/realm (e.g. an iframe's
  1431. * contentDocument). The previous `value instanceof Node` check was
  1432. * realm-bound: nodes from a different window failed it, causing
  1433. * sanitize() to silently stringify them and reset IN_PLACE to false,
  1434. * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
  1435. *
  1436. * @param value object to check whether it's a DOM node
  1437. * @return true if value is a DOM node from any realm
  1438. */
  1439. const _isNode = function _isNode(value) {
  1440. if (!getNodeType || typeof value !== 'object' || value === null) {
  1441. return false;
  1442. }
  1443. try {
  1444. return typeof getNodeType(value) === 'number';
  1445. } catch (_) {
  1446. return false;
  1447. }
  1448. };
  1449. function _executeHooks(hooks, currentNode, data) {
  1450. if (hooks.length === 0) {
  1451. return;
  1452. }
  1453. arrayForEach(hooks, hook => {
  1454. hook.call(DOMPurify, currentNode, data, CONFIG);
  1455. });
  1456. }
  1457. /**
  1458. * Structural-threat checks that condemn a node regardless of the
  1459. * allowlists: mXSS via namespace confusion, risky CSS construction,
  1460. * processing instructions, markup-bearing comments. Pure predicate;
  1461. * the caller removes. Check order is load-bearing.
  1462. *
  1463. * @param currentNode the node to inspect
  1464. * @param tagName the node's transformCaseFunc'd tag name
  1465. * @return true if the node must be removed
  1466. */
  1467. const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
  1468. /* Detect mXSS attempts abusing namespace confusion */
  1469. if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
  1470. return true;
  1471. }
  1472. /* Remove risky CSS construction leading to mXSS */
  1473. if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
  1474. return true;
  1475. }
  1476. /* Remove any occurrence of processing instructions */
  1477. if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
  1478. return true;
  1479. }
  1480. /* Remove any kind of possibly harmful comments */
  1481. if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
  1482. return true;
  1483. }
  1484. return false;
  1485. };
  1486. /**
  1487. * Handle a node whose tag is forbidden or not allowlisted: keep
  1488. * allowed custom elements (false return exits _sanitizeElements
  1489. * early - namespace/fallback checks and the afterSanitizeElements
  1490. * hook are intentionally skipped for kept custom elements), else
  1491. * hoist content per KEEP_CONTENT and remove.
  1492. *
  1493. * @param currentNode the disallowed node
  1494. * @param tagName the node's transformCaseFunc'd tag name
  1495. * @return true if the node was removed, false if kept
  1496. */
  1497. const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
  1498. /* Check if we have a custom element to handle */
  1499. if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
  1500. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
  1501. return false;
  1502. }
  1503. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
  1504. return false;
  1505. }
  1506. }
  1507. /* Keep content except for bad-listed elements.
  1508. Use the cached prototype getters exclusively — the previous code
  1509. had `|| currentNode.parentNode` / `|| currentNode.childNodes`
  1510. fallbacks, but the cached getters always return the canonical
  1511. value (or null for a real parent-less node), so the fallback
  1512. path was dead in safe cases and a clobbering surface in unsafe
  1513. ones. Falsy cached results stay falsy; the `if (childNodes &&
  1514. parentNode)` check already gates correctly. */
  1515. if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  1516. const parentNode = getParentNode(currentNode);
  1517. const childNodes = getChildNodes(currentNode);
  1518. if (childNodes && parentNode) {
  1519. const childCount = childNodes.length;
  1520. /* In-place: hoist the *original* children so the iterator visits
  1521. and sanitises them through the same allowlist pass as every other
  1522. node. The caller built the tree in the live document, so the
  1523. originals carry already-queued resource events (`<img onerror>`,
  1524. `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
  1525. those originals detached but still armed, firing in page scope
  1526. while the returned tree looked clean. Moving is safe in-place: the
  1527. root is pre-validated as an allowed tag and so is never the node
  1528. being removed, which keeps `parentNode` inside the iterator root
  1529. and the relocated child inside the serialised tree.
  1530. Otherwise (string / DOM-copy paths): clone. The iterator is rooted
  1531. at — and the result serialised from — `body`, so a restrictive
  1532. ALLOWED_TAGS that removes `body` itself must leave its content in
  1533. place, which only cloning does; and those paths parse into an
  1534. inert document, so their discarded originals never had a queued
  1535. event to neutralise.
  1536. `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
  1537. valid whether we move (drops the trailing entry) or clone (leaves
  1538. the list intact). */
  1539. for (let i = childCount - 1; i >= 0; --i) {
  1540. const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
  1541. parentNode.insertBefore(hoisted, getNextSibling(currentNode));
  1542. }
  1543. }
  1544. }
  1545. _forceRemove(currentNode);
  1546. return true;
  1547. };
  1548. /**
  1549. * _sanitizeElements
  1550. *
  1551. * @protect nodeName
  1552. * @protect textContent
  1553. * @protect removeChild
  1554. * @param currentNode to check for permission to exist
  1555. * @return true if node was killed, false if left alive
  1556. */
  1557. const _sanitizeElements = function _sanitizeElements(currentNode) {
  1558. /* Execute a hook if present */
  1559. _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
  1560. /* Check if element is clobbered or can clobber */
  1561. if (_isClobbered(currentNode)) {
  1562. _forceRemove(currentNode);
  1563. return true;
  1564. }
  1565. /* Now let's check the element's type and name */
  1566. const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
  1567. /* Execute a hook if present */
  1568. _executeHooks(hooks.uponSanitizeElement, currentNode, {
  1569. tagName,
  1570. allowedTags: ALLOWED_TAGS
  1571. });
  1572. /* Remove mXSS vectors, processing instructions and risky comments */
  1573. if (_isUnsafeNode(currentNode, tagName)) {
  1574. _forceRemove(currentNode);
  1575. return true;
  1576. }
  1577. /* Remove element if anything forbids its presence */
  1578. if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
  1579. return _sanitizeDisallowedNode(currentNode, tagName);
  1580. }
  1581. /* Check whether element has a valid namespace.
  1582. Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
  1583. nodeType getter rather than `instanceof Element`, which is realm-
  1584. bound and short-circuits to false for any node minted in a different
  1585. realm — letting a foreign-realm element with a forbidden namespace
  1586. slip past the namespace check entirely. */
  1587. const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
  1588. if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
  1589. _forceRemove(currentNode);
  1590. return true;
  1591. }
  1592. /* Make sure that older browsers don't get fallback-tag mXSS */
  1593. if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
  1594. _forceRemove(currentNode);
  1595. return true;
  1596. }
  1597. /* Sanitize element content to be template-safe */
  1598. if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
  1599. /* Get the element's text content */
  1600. const content = _stripTemplateExpressions(currentNode.textContent);
  1601. if (currentNode.textContent !== content) {
  1602. arrayPush(DOMPurify.removed, {
  1603. element: currentNode.cloneNode()
  1604. });
  1605. currentNode.textContent = content;
  1606. }
  1607. }
  1608. /* Execute a hook if present */
  1609. _executeHooks(hooks.afterSanitizeElements, currentNode, null);
  1610. return false;
  1611. };
  1612. /**
  1613. * _isValidAttribute
  1614. *
  1615. * @param lcTag Lowercase tag name of containing element.
  1616. * @param lcName Lowercase attribute name.
  1617. * @param value Attribute value.
  1618. * @return Returns true if `value` is valid, otherwise false.
  1619. */
  1620. // eslint-disable-next-line complexity
  1621. const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  1622. /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
  1623. if (FORBID_ATTR[lcName]) {
  1624. return false;
  1625. }
  1626. /* Make sure attribute cannot clobber */
  1627. if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  1628. return false;
  1629. }
  1630. const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
  1631. /* Allow valid data-* attributes: At least one character after "-"
  1632. (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
  1633. XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
  1634. We don't need to check the value; it's always URI safe. */
  1635. if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
  1636. if (
  1637. // First condition does a very basic check if a) it's basically a valid custom element tagname AND
  1638. // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
  1639. // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
  1640. _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)) ||
  1641. // Alternative, second condition checks if it's an `is`-attribute, AND
  1642. // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
  1643. lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
  1644. return false;
  1645. }
  1646. /* Check value is safe. First, is attr inert? If so, is safe */
  1647. } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; 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$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {
  1648. return false;
  1649. } else ;
  1650. return true;
  1651. };
  1652. /* Names the HTML spec reserves from valid-custom-element-name; these must
  1653. * never be treated as basic custom elements even when a permissive
  1654. * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
  1655. const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);
  1656. /**
  1657. * _isBasicCustomElement
  1658. * checks if at least one dash is included in tagName, and it's not the first char
  1659. * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
  1660. *
  1661. * @param tagName name of the tag of the node to sanitize
  1662. * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
  1663. */
  1664. const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
  1665. return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
  1666. };
  1667. /**
  1668. * Wrap an attribute value in the matching Trusted Types object when
  1669. * the active policy requires it. Namespaced attributes pass through
  1670. * unchanged (no TT support yet, see
  1671. * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
  1672. *
  1673. * @param lcTag lowercase tag name of the containing element
  1674. * @param lcName lowercase attribute name
  1675. * @param namespaceURI the attribute's namespace, if any
  1676. * @param value the attribute value to wrap
  1677. * @return the value, wrapped when Trusted Types demand it
  1678. */
  1679. const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
  1680. if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
  1681. switch (trustedTypes.getAttributeType(lcTag, lcName)) {
  1682. case 'TrustedHTML':
  1683. {
  1684. return _createTrustedHTML(value);
  1685. }
  1686. case 'TrustedScriptURL':
  1687. {
  1688. return _createTrustedScriptURL(value);
  1689. }
  1690. }
  1691. }
  1692. return value;
  1693. };
  1694. /**
  1695. * Write a modified attribute value back onto the element. On
  1696. * success, re-probe for clobbering introduced by the new value and
  1697. * remove the element when found; otherwise pop the removal entry
  1698. * recorded by the earlier _removeAttribute (long-standing pairing
  1699. * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
  1700. * failure, remove the attribute instead.
  1701. *
  1702. * @param currentNode the element carrying the attribute
  1703. * @param name the attribute name as present on the element
  1704. * @param namespaceURI the attribute's namespace, if any
  1705. * @param value the new attribute value
  1706. */
  1707. const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
  1708. try {
  1709. if (namespaceURI) {
  1710. currentNode.setAttributeNS(namespaceURI, name, value);
  1711. } else {
  1712. /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
  1713. currentNode.setAttribute(name, value);
  1714. }
  1715. if (_isClobbered(currentNode)) {
  1716. _forceRemove(currentNode);
  1717. } else {
  1718. arrayPop(DOMPurify.removed);
  1719. }
  1720. } catch (_) {
  1721. _removeAttribute(name, currentNode);
  1722. }
  1723. };
  1724. /**
  1725. * _sanitizeAttributes
  1726. *
  1727. * @protect attributes
  1728. * @protect nodeName
  1729. * @protect removeAttribute
  1730. * @protect setAttribute
  1731. *
  1732. * @param currentNode to sanitize
  1733. */
  1734. const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  1735. /* Execute a hook if present */
  1736. _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
  1737. const attributes = currentNode.attributes;
  1738. /* Check if we have attributes; if not we might have a text node */
  1739. if (!attributes || _isClobbered(currentNode)) {
  1740. return;
  1741. }
  1742. const hookEvent = {
  1743. attrName: '',
  1744. attrValue: '',
  1745. keepAttr: true,
  1746. allowedAttributes: ALLOWED_ATTR,
  1747. forceKeepAttr: undefined
  1748. };
  1749. let l = attributes.length;
  1750. const lcTag = transformCaseFunc(currentNode.nodeName);
  1751. /* Go backwards over all attributes; safely remove bad ones */
  1752. while (l--) {
  1753. const attr = attributes[l];
  1754. const name = attr.name,
  1755. namespaceURI = attr.namespaceURI,
  1756. attrValue = attr.value;
  1757. const lcName = transformCaseFunc(name);
  1758. const initValue = attrValue;
  1759. let value = name === 'value' ? initValue : stringTrim(initValue);
  1760. /* Execute a hook if present */
  1761. hookEvent.attrName = lcName;
  1762. hookEvent.attrValue = value;
  1763. hookEvent.keepAttr = true;
  1764. hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
  1765. _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
  1766. value = hookEvent.attrValue;
  1767. /* Full DOM Clobbering protection via namespace isolation,
  1768. * Prefix id and name attributes with `user-content-`
  1769. */
  1770. if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
  1771. // Remove the attribute with this value
  1772. _removeAttribute(name, currentNode);
  1773. // Prefix the value and later re-create the attribute with the sanitized value
  1774. value = SANITIZE_NAMED_PROPS_PREFIX + value;
  1775. }
  1776. // Else: already prefixed, leave the attribute alone — the prefix is
  1777. // itself the clobbering protection, and re-applying it is incorrect.
  1778. /* Work around a security issue with comments inside attributes */
  1779. if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
  1780. _removeAttribute(name, currentNode);
  1781. continue;
  1782. }
  1783. /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
  1784. if (lcName === 'attributename' && stringMatch(value, 'href')) {
  1785. _removeAttribute(name, currentNode);
  1786. continue;
  1787. }
  1788. /* Did the hooks force-keep the attribute? */
  1789. if (hookEvent.forceKeepAttr) {
  1790. continue;
  1791. }
  1792. /* Did the hooks approve of the attribute? */
  1793. if (!hookEvent.keepAttr) {
  1794. _removeAttribute(name, currentNode);
  1795. continue;
  1796. }
  1797. /* Work around a security issue in jQuery 3.0 */
  1798. if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
  1799. _removeAttribute(name, currentNode);
  1800. continue;
  1801. }
  1802. /* Sanitize attribute content to be template-safe */
  1803. if (SAFE_FOR_TEMPLATES) {
  1804. value = _stripTemplateExpressions(value);
  1805. }
  1806. /* Is `value` valid for this attribute? */
  1807. if (!_isValidAttribute(lcTag, lcName, value)) {
  1808. _removeAttribute(name, currentNode);
  1809. continue;
  1810. }
  1811. /* Handle attributes that require Trusted Types */
  1812. value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
  1813. /* Handle invalid data-* attribute set by try-catching it */
  1814. if (value !== initValue) {
  1815. _setAttributeValue(currentNode, name, namespaceURI, value);
  1816. }
  1817. }
  1818. /* Execute a hook if present */
  1819. _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
  1820. };
  1821. /**
  1822. * _sanitizeShadowDOM
  1823. *
  1824. * @param fragment to iterate over recursively
  1825. */
  1826. const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
  1827. let shadowNode = null;
  1828. const shadowIterator = _createNodeIterator(fragment);
  1829. /* Execute a hook if present */
  1830. _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
  1831. while (shadowNode = shadowIterator.nextNode()) {
  1832. /* Execute a hook if present */
  1833. _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
  1834. /* Sanitize tags and elements */
  1835. _sanitizeElements(shadowNode);
  1836. /* Check attributes next */
  1837. _sanitizeAttributes(shadowNode);
  1838. /* Deep shadow DOM detected.
  1839. Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
  1840. DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
  1841. recurse into <template>.content from foreign realms too. */
  1842. if (_isDocumentFragment(shadowNode.content)) {
  1843. _sanitizeShadowDOM2(shadowNode.content);
  1844. }
  1845. /* An element iterated here may itself host an attached
  1846. shadow root. The default NodeIterator does not enter shadow
  1847. trees, so a shadow root nested inside template.content was
  1848. previously reached by no walk at all (the pre-pass at
  1849. _sanitizeAttachedShadowRoots descends via childNodes, which
  1850. doesn't enter template.content; the template-content recursion
  1851. above iterates the content but never inspected shadowRoot).
  1852. Walk it explicitly. The nodeType guard avoids reading
  1853. shadowRoot off text / comment / CDATA / PI nodes that the
  1854. iterator also surfaces. */
  1855. const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
  1856. if (shadowNodeType === NODE_TYPE.element) {
  1857. const innerSr = getShadowRoot(shadowNode);
  1858. if (_isDocumentFragment(innerSr)) {
  1859. _sanitizeAttachedShadowRoots(innerSr);
  1860. _sanitizeShadowDOM2(innerSr);
  1861. }
  1862. }
  1863. }
  1864. /* Execute a hook if present */
  1865. _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
  1866. };
  1867. /**
  1868. * _sanitizeAttachedShadowRoots
  1869. *
  1870. * Walks `root` and feeds every attached shadow root we encounter into
  1871. * the existing _sanitizeShadowDOM pipeline. The default node iterator
  1872. * does not descend into shadow trees, so nodes inside an attached
  1873. * shadow root would otherwise be skipped entirely.
  1874. *
  1875. * Two real input paths put attached shadow roots in front of us:
  1876. * 1. IN_PLACE on a DOM node that already has shadow roots attached.
  1877. * 2. DOM-node input where importNode(dirty, true) deep-clones the
  1878. * shadow root because it was created with `clonable: true`.
  1879. *
  1880. * This pass runs once, up front, so the main iteration loop (and the
  1881. * existing _sanitizeShadowDOM template-content recursion) stay
  1882. * untouched — string-input paths are not affected.
  1883. *
  1884. * @param root the subtree root to walk for attached shadow roots
  1885. */
  1886. const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
  1887. /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
  1888. impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
  1889. built straight into the DOM — the IN_PLACE surface) deeper than the JS
  1890. call-stack budget would otherwise overflow native recursion here and
  1891. throw at the IN_PLACE entry pre-pass, before a single node is
  1892. sanitized, leaving the caller's live tree untouched (fail-open). See
  1893. campaign-3 F4. A heap stack keeps depth off the call stack.
  1894. Each work item is either a node to descend into, or a deferred
  1895. `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
  1896. form preserves the original post-order discipline: a shadow root's
  1897. nested shadow roots are discovered before the outer shadow is
  1898. sanitized (which may remove hosts). Pushes are in reverse of the
  1899. desired processing order (LIFO): template content, then children, then
  1900. the shadow-sanitize, then the shadow walk — so the order matches the
  1901. previous recursion exactly. */
  1902. const stack = [{
  1903. node: root,
  1904. shadow: null
  1905. }];
  1906. while (stack.length > 0) {
  1907. const item = stack.pop();
  1908. /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
  1909. if (item.shadow) {
  1910. _sanitizeShadowDOM2(item.shadow);
  1911. continue;
  1912. }
  1913. const node = item.node;
  1914. const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
  1915. const isElement = nodeType === NODE_TYPE.element;
  1916. /* (pushed last → processed first) Children, snapshotted in reverse so
  1917. the first child is processed first. Snapshotting matters because a
  1918. hook may detach siblings mid-walk. */
  1919. const childNodes = getChildNodes(node);
  1920. if (childNodes) {
  1921. for (let i = childNodes.length - 1; i >= 0; --i) {
  1922. stack.push({
  1923. node: childNodes[i],
  1924. shadow: null
  1925. });
  1926. }
  1927. }
  1928. /* (pushed before children → processed after them, matching the old
  1929. "template content last" order) When the node is a <template>,
  1930. descend into its content. */
  1931. if (isElement) {
  1932. const rootName = getNodeName ? getNodeName(node) : null;
  1933. if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
  1934. const content = node.content;
  1935. if (_isDocumentFragment(content)) {
  1936. stack.push({
  1937. node: content,
  1938. shadow: null
  1939. });
  1940. }
  1941. }
  1942. }
  1943. /* Shadow root (processed first): walk its subtree, then sanitise it.
  1944. Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
  1945. rather than `instanceof DocumentFragment`, which is realm-bound and
  1946. silently skipped foreign-realm shadow roots (e.g.
  1947. iframe.contentDocument attachShadow). */
  1948. if (isElement) {
  1949. const sr = getShadowRoot(node);
  1950. if (_isDocumentFragment(sr)) {
  1951. /* Push the deferred sanitise first so it pops after the shadow
  1952. walk we push next, i.e. nested shadow roots are discovered
  1953. before this one is sanitised. */
  1954. stack.push({
  1955. node: null,
  1956. shadow: sr
  1957. }, {
  1958. node: sr,
  1959. shadow: null
  1960. });
  1961. }
  1962. }
  1963. }
  1964. };
  1965. // eslint-disable-next-line complexity
  1966. DOMPurify.sanitize = function (dirty) {
  1967. let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1968. let body = null;
  1969. let importedNode = null;
  1970. let currentNode = null;
  1971. let returnNode = null;
  1972. /* Make sure we have a string to sanitize.
  1973. DO NOT return early, as this will return the wrong type if
  1974. the user has requested a DOM object rather than a string */
  1975. IS_EMPTY_INPUT = !dirty;
  1976. if (IS_EMPTY_INPUT) {
  1977. dirty = '<!-->';
  1978. }
  1979. /* Stringify, in case dirty is an object */
  1980. if (typeof dirty !== 'string' && !_isNode(dirty)) {
  1981. dirty = stringifyValue(dirty);
  1982. if (typeof dirty !== 'string') {
  1983. throw typeErrorCreate('dirty is not a string, aborting');
  1984. }
  1985. }
  1986. /* Return dirty HTML if DOMPurify cannot run */
  1987. if (!DOMPurify.isSupported) {
  1988. return dirty;
  1989. }
  1990. /* Assign config vars */
  1991. if (!SET_CONFIG) {
  1992. _parseConfig(cfg);
  1993. }
  1994. /* Clean up removed elements */
  1995. DOMPurify.removed = [];
  1996. /* Resolve IN_PLACE for this call without mutating persistent config.
  1997. Writing the IN_PLACE closure variable here leaks under setConfig(),
  1998. where _parseConfig is skipped on later calls: a single string call would
  1999. disable in-place mode for every subsequent node call, returning a
  2000. sanitized copy while leaving the caller's node — which in-place callers
  2001. keep using and whose return value they ignore — unsanitized. REPORT-2. */
  2002. const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
  2003. if (inPlace) {
  2004. /* Do some early pre-sanitization to avoid unsafe root nodes.
  2005. Read nodeName through the cached prototype getter — a clobbering
  2006. child named "nodeName" on the form root would otherwise shadow
  2007. the property and let this check skip the root-allowlist
  2008. validation entirely. */
  2009. const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
  2010. if (typeof nn === 'string') {
  2011. const tagName = transformCaseFunc(nn);
  2012. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  2013. throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
  2014. }
  2015. }
  2016. /* Pre-flight the root through _isClobbered. The iterator-driven
  2017. removal path can not detach a parent-less root: _forceRemove
  2018. falls through to Element.prototype.remove(), which per spec
  2019. is a no-op on a node with no parent. A clobbered root would
  2020. then survive the main loop with its attributes uninspected,
  2021. because _sanitizeAttributes early-returns on _isClobbered. The
  2022. result would be an attacker-controlled form, complete with any
  2023. event-handler attributes the caller passed in, handed back to
  2024. the application unsanitized. Refuse to sanitize such a root
  2025. the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
  2026. if (_isClobbered(dirty)) {
  2027. throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
  2028. }
  2029. /* Sanitize attached shadow roots before the main iterator runs.
  2030. The iterator does not descend into shadow trees. Same fail-closed
  2031. barrier as the main walk (campaign-3 F2): a custom-element reaction
  2032. inside a shadow root could abort this pre-pass before the walk runs,
  2033. which would otherwise leave the entire live tree unsanitized. */
  2034. try {
  2035. _sanitizeAttachedShadowRoots(dirty);
  2036. } catch (error) {
  2037. _neutralizeRoot(dirty);
  2038. throw error;
  2039. }
  2040. } else if (_isNode(dirty)) {
  2041. /* If dirty is a DOM element, append to an empty document to avoid
  2042. elements being stripped by the parser */
  2043. body = _initDocument('<!---->');
  2044. importedNode = body.ownerDocument.importNode(dirty, true);
  2045. if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
  2046. /* Node is already a body, use as is */
  2047. body = importedNode;
  2048. } else if (importedNode.nodeName === 'HTML') {
  2049. body = importedNode;
  2050. } else {
  2051. // eslint-disable-next-line unicorn/prefer-dom-node-append
  2052. body.appendChild(importedNode);
  2053. }
  2054. /* Clonable shadow roots are deep-cloned by importNode(); sanitize
  2055. them before the main iterator runs, since the iterator does not
  2056. descend into shadow trees. The walk routes every read through a
  2057. cached prototype getter so clobbering descendants on a form root
  2058. cannot hide a shadow host from this pass. */
  2059. _sanitizeAttachedShadowRoots(importedNode);
  2060. } else {
  2061. /* Exit directly if we have nothing to do */
  2062. if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
  2063. // eslint-disable-next-line unicorn/prefer-includes
  2064. dirty.indexOf('<') === -1) {
  2065. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
  2066. }
  2067. /* Initialize the document to work on */
  2068. body = _initDocument(dirty);
  2069. /* Check we have a DOM node from the data */
  2070. if (!body) {
  2071. return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
  2072. }
  2073. }
  2074. /* Remove first element node (ours) if FORCE_BODY is set */
  2075. if (body && FORCE_BODY) {
  2076. _forceRemove(body.firstChild);
  2077. }
  2078. /* Get node iterator */
  2079. const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
  2080. /* Now start iterating over the created document.
  2081. The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
  2082. engine/custom-element mutation can detach a node mid-walk so
  2083. `_forceRemove`'s parentless guard throws, aborting the loop. Without the
  2084. barrier the caller's in-place tree would be left half-sanitized with the
  2085. unvisited tail still armed. On any throw we fail closed — strip the
  2086. in-place root bare — then rethrow so the existing throw contract is
  2087. preserved. (String/DOM-copy paths never return the partial body, so the
  2088. propagating throw is already fail-closed there.) */
  2089. try {
  2090. while (currentNode = nodeIterator.nextNode()) {
  2091. /* Sanitize tags and elements */
  2092. _sanitizeElements(currentNode);
  2093. /* Check attributes next */
  2094. _sanitizeAttributes(currentNode);
  2095. /* Shadow DOM detected, sanitize it.
  2096. Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
  2097. instead of instanceof, so foreign-realm <template>.content is
  2098. walked correctly. */
  2099. if (_isDocumentFragment(currentNode.content)) {
  2100. _sanitizeShadowDOM2(currentNode.content);
  2101. }
  2102. }
  2103. } catch (error) {
  2104. if (inPlace) {
  2105. _neutralizeRoot(dirty);
  2106. }
  2107. throw error;
  2108. }
  2109. /* If we sanitized `dirty` in-place, return it. */
  2110. if (inPlace) {
  2111. /* Fail-closed completion of the audit-5 F1 fix: every node removed from
  2112. the caller's live tree is detached but may still hold a queued
  2113. resource-event handler that fires in page scope after we return. The
  2114. move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
  2115. non-allow-listed attributes off every other removed subtree (clobber,
  2116. mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
  2117. cancelled before any event can fire. Runs synchronously, pre-return. */
  2118. arrayForEach(DOMPurify.removed, entry => {
  2119. if (entry.element) {
  2120. _neutralizeSubtree(entry.element);
  2121. }
  2122. });
  2123. if (SAFE_FOR_TEMPLATES) {
  2124. _scrubTemplateExpressions2(dirty);
  2125. }
  2126. return dirty;
  2127. }
  2128. /* Return sanitized string or DOM */
  2129. if (RETURN_DOM) {
  2130. if (SAFE_FOR_TEMPLATES) {
  2131. _scrubTemplateExpressions2(body);
  2132. }
  2133. if (RETURN_DOM_FRAGMENT) {
  2134. returnNode = createDocumentFragment.call(body.ownerDocument);
  2135. while (body.firstChild) {
  2136. // eslint-disable-next-line unicorn/prefer-dom-node-append
  2137. returnNode.appendChild(body.firstChild);
  2138. }
  2139. } else {
  2140. returnNode = body;
  2141. }
  2142. if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
  2143. /*
  2144. AdoptNode() is not used because internal state is not reset
  2145. (e.g. the past names map of a HTMLFormElement), this is safe
  2146. in theory but we would rather not risk another attack vector.
  2147. The state that is cloned by importNode() is explicitly defined
  2148. by the specs.
  2149. */
  2150. returnNode = importNode.call(originalDocument, returnNode, true);
  2151. }
  2152. return returnNode;
  2153. }
  2154. let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  2155. /* Serialize doctype if allowed */
  2156. if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
  2157. serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
  2158. }
  2159. /* Sanitize final string template-safe */
  2160. if (SAFE_FOR_TEMPLATES) {
  2161. serializedHTML = _stripTemplateExpressions(serializedHTML);
  2162. }
  2163. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
  2164. };
  2165. DOMPurify.setConfig = function () {
  2166. let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  2167. _parseConfig(cfg);
  2168. SET_CONFIG = true;
  2169. };
  2170. DOMPurify.clearConfig = function () {
  2171. CONFIG = null;
  2172. SET_CONFIG = false;
  2173. // Drop any caller-supplied Trusted Types policy so it cannot poison later
  2174. // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
  2175. // never recreated — Trusted Types throws on duplicate names) is restored by
  2176. // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
  2177. trustedTypesPolicy = defaultTrustedTypesPolicy;
  2178. emptyHTML = '';
  2179. };
  2180. DOMPurify.isValidAttribute = function (tag, attr, value) {
  2181. /* Initialize shared config vars if necessary. */
  2182. if (!CONFIG) {
  2183. _parseConfig({});
  2184. }
  2185. const lcTag = transformCaseFunc(tag);
  2186. const lcName = transformCaseFunc(attr);
  2187. return _isValidAttribute(lcTag, lcName, value);
  2188. };
  2189. DOMPurify.addHook = function (entryPoint, hookFunction) {
  2190. if (typeof hookFunction !== 'function') {
  2191. return;
  2192. }
  2193. arrayPush(hooks[entryPoint], hookFunction);
  2194. };
  2195. DOMPurify.removeHook = function (entryPoint, hookFunction) {
  2196. if (hookFunction !== undefined) {
  2197. const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
  2198. return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
  2199. }
  2200. return arrayPop(hooks[entryPoint]);
  2201. };
  2202. DOMPurify.removeHooks = function (entryPoint) {
  2203. hooks[entryPoint] = [];
  2204. };
  2205. DOMPurify.removeAllHooks = function () {
  2206. hooks = _createHooksMap();
  2207. };
  2208. return DOMPurify;
  2209. }
  2210. var purify = createDOMPurify();
  2211. export { purify as default };
  2212. //# sourceMappingURL=purify.es.mjs.map