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

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