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

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