@wiris/mathtype-ckeditor5 8.15.1 → 8.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,24 +5,65 @@
5
5
  })(this, (function (exports, ckeditor5) { 'use strict';
6
6
 
7
7
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
8
- /*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */
8
+ /*! @license DOMPurify 3.4.15 | (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.15/LICENSE */
9
9
 
10
- const {
11
- entries,
12
- setPrototypeOf,
13
- isFrozen,
14
- getPrototypeOf,
15
- getOwnPropertyDescriptor
16
- } = Object;
17
- let {
18
- freeze,
19
- seal,
20
- create
21
- } = Object; // eslint-disable-line import/no-mutable-exports
22
- let {
23
- apply,
24
- construct
25
- } = typeof Reflect !== 'undefined' && Reflect;
10
+ function _arrayLikeToArray(r, a) {
11
+ (null == a || a > r.length) && (a = r.length);
12
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
13
+ return n;
14
+ }
15
+ function _arrayWithHoles(r) {
16
+ if (Array.isArray(r)) return r;
17
+ }
18
+ function _iterableToArrayLimit(r, l) {
19
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
20
+ if (null != t) {
21
+ var e,
22
+ n,
23
+ i,
24
+ u,
25
+ a = [],
26
+ f = true,
27
+ o = false;
28
+ try {
29
+ 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);
30
+ } catch (r) {
31
+ o = true, n = r;
32
+ } finally {
33
+ try {
34
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
35
+ } finally {
36
+ if (o) throw n;
37
+ }
38
+ }
39
+ return a;
40
+ }
41
+ }
42
+ function _nonIterableRest() {
43
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
44
+ }
45
+ function _slicedToArray(r, e) {
46
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
47
+ }
48
+ function _unsupportedIterableToArray(r, a) {
49
+ if (r) {
50
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
51
+ var t = {}.toString.call(r).slice(8, -1);
52
+ 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;
53
+ }
54
+ }
55
+
56
+ const entries = Object.entries,
57
+ setPrototypeOf = Object.setPrototypeOf,
58
+ isFrozen = Object.isFrozen,
59
+ getPrototypeOf = Object.getPrototypeOf,
60
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
61
+ let freeze = Object.freeze,
62
+ seal = Object.seal,
63
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
64
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
65
+ apply = _ref.apply,
66
+ construct = _ref.construct;
26
67
  if (!freeze) {
27
68
  freeze = function freeze(x) {
28
69
  return x;
@@ -54,13 +95,19 @@
54
95
  const arrayPop = unapply(Array.prototype.pop);
55
96
  const arrayPush = unapply(Array.prototype.push);
56
97
  const arraySplice = unapply(Array.prototype.splice);
98
+ const arrayIsArray = Array.isArray;
57
99
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
58
100
  const stringToString = unapply(String.prototype.toString);
59
101
  const stringMatch = unapply(String.prototype.match);
60
102
  const stringReplace = unapply(String.prototype.replace);
61
103
  const stringIndexOf = unapply(String.prototype.indexOf);
62
104
  const stringTrim = unapply(String.prototype.trim);
105
+ const numberToString = unapply(Number.prototype.toString);
106
+ const booleanToString = unapply(Boolean.prototype.toString);
107
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
108
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
63
109
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
110
+ const objectToString = unapply(Object.prototype.toString);
64
111
  const regExpTest = unapply(RegExp.prototype.test);
65
112
  const typeErrorCreate = unconstruct(TypeError);
66
113
  /**
@@ -110,6 +157,9 @@
110
157
  // Prevent prototype setters from intercepting set as a this value.
111
158
  setPrototypeOf(set, null);
112
159
  }
160
+ if (!arrayIsArray(array)) {
161
+ return set;
162
+ }
113
163
  let l = array.length;
114
164
  while (l--) {
115
165
  let element = array[l];
@@ -150,10 +200,13 @@
150
200
  */
151
201
  function clone(object) {
152
202
  const newObject = create(null);
153
- for (const [property, value] of entries(object)) {
203
+ for (const _ref2 of entries(object)) {
204
+ var _ref3 = _slicedToArray(_ref2, 2);
205
+ const property = _ref3[0];
206
+ const value = _ref3[1];
154
207
  const isPropertyExist = objectHasOwnProperty(object, property);
155
208
  if (isPropertyExist) {
156
- if (Array.isArray(value)) {
209
+ if (arrayIsArray(value)) {
157
210
  newObject[property] = cleanArray(value);
158
211
  } else if (value && typeof value === 'object' && value.constructor === Object) {
159
212
  newObject[property] = clone(value);
@@ -164,6 +217,58 @@
164
217
  }
165
218
  return newObject;
166
219
  }
220
+ /**
221
+ * Convert non-node values into strings without depending on direct property access.
222
+ *
223
+ * @param value - The value to stringify.
224
+ * @returns A string representation of the provided value.
225
+ */
226
+ function stringifyValue(value) {
227
+ switch (typeof value) {
228
+ case 'string':
229
+ {
230
+ return value;
231
+ }
232
+ case 'number':
233
+ {
234
+ return numberToString(value);
235
+ }
236
+ case 'boolean':
237
+ {
238
+ return booleanToString(value);
239
+ }
240
+ case 'bigint':
241
+ {
242
+ return bigintToString ? bigintToString(value) : '0';
243
+ }
244
+ case 'symbol':
245
+ {
246
+ return symbolToString ? symbolToString(value) : 'Symbol()';
247
+ }
248
+ case 'undefined':
249
+ {
250
+ return objectToString(value);
251
+ }
252
+ case 'function':
253
+ case 'object':
254
+ {
255
+ if (value === null) {
256
+ return objectToString(value);
257
+ }
258
+ const valueAsRecord = value;
259
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
260
+ if (typeof valueToString === 'function') {
261
+ const stringified = valueToString(valueAsRecord);
262
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
263
+ }
264
+ return objectToString(value);
265
+ }
266
+ default:
267
+ {
268
+ return objectToString(value);
269
+ }
270
+ }
271
+ }
167
272
  /**
168
273
  * This method automatically checks if the prop is function or getter and behaves accordingly.
169
274
  *
@@ -189,6 +294,14 @@
189
294
  }
190
295
  return fallbackValue;
191
296
  }
297
+ function isRegex(value) {
298
+ try {
299
+ regExpTest(value, '');
300
+ return true;
301
+ } catch (_unused) {
302
+ return false;
303
+ }
304
+ }
192
305
 
193
306
  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']);
194
307
  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']);
@@ -204,15 +317,14 @@
204
317
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
205
318
  const text = freeze(['#text']);
206
319
 
207
- const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
208
- 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']);
209
- const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
320
+ 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']);
321
+ 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', 'dominant-baseline', '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', 'pointer-events', '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-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'vector-effect', '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']);
322
+ 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']);
210
323
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
211
324
 
212
- // eslint-disable-next-line unicorn/better-regex
213
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
214
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
215
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
325
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
326
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
327
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
216
328
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
217
329
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
218
330
  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
@@ -222,30 +334,62 @@
222
334
  );
223
335
  const DOCTYPE_NAME = seal(/^html$/i);
224
336
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
337
+ // Markup-significant character probes used by _sanitizeElements.
338
+ // Shared module-level instances are safe despite the sticky /g flags:
339
+ // unapply() resets lastIndex for RegExp receivers before every call.
340
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
341
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
342
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
343
+ const SELF_CLOSING_TAG = seal(/\/>/i);
225
344
 
226
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
227
- __proto__: null,
228
- ARIA_ATTR: ARIA_ATTR,
229
- ATTR_WHITESPACE: ATTR_WHITESPACE,
230
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
231
- DATA_ATTR: DATA_ATTR,
232
- DOCTYPE_NAME: DOCTYPE_NAME,
233
- ERB_EXPR: ERB_EXPR,
234
- IS_ALLOWED_URI: IS_ALLOWED_URI,
235
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
236
- MUSTACHE_EXPR: MUSTACHE_EXPR,
237
- TMPLIT_EXPR: TMPLIT_EXPR
238
- });
239
-
240
- /* eslint-disable @typescript-eslint/indent */
241
345
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
242
346
  const NODE_TYPE = {
243
347
  element: 1,
348
+ attribute: 2,
244
349
  text: 3,
350
+ cdataSection: 4,
351
+ entityReference: 5,
352
+ // Deprecated
353
+ entityNode: 6,
245
354
  // Deprecated
246
- progressingInstruction: 7,
355
+ processingInstruction: 7,
247
356
  comment: 8,
248
- document: 9};
357
+ document: 9,
358
+ documentType: 10,
359
+ documentFragment: 11,
360
+ notation: 12 // Deprecated
361
+ };
362
+ /* HTML-namespace elements whose child text nodes are serialized *literally*
363
+ (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS
364
+ shapes ride on that literal serialization:
365
+ (a) an element child - a tree the HTML parser can never build, but the DOM
366
+ API and an XML/XHTML parse can - after which a `</tag>`-bearing text
367
+ sibling breaks the element open on reparse; and
368
+ (b) text-only content that already carries the element's OWN end tag, e.g.
369
+ `<style>...</style><img onerror=x>` built as a node, which the literal
370
+ serializer emits verbatim for the HTML parser to re-open.
371
+ Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape
372
+ (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized
373
+ form for these elements) rather than innerHTML, because an XML/XHTML working
374
+ document serializes innerHTML with `<` escaped, which silently blinds the
375
+ innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.
376
+ `script` is never allow-listed, but is kept here so the guard matches the
377
+ serializer's own literal-text list exactly. */
378
+ const LITERAL_TEXT_ELEMENT_NAMES = ['style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript'];
379
+ const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));
380
+ /* Per-element end-tag matcher. On an HTML reparse the ONLY token that
381
+ terminates a literal-text element's raw content is its own end tag; a foreign
382
+ literal-text close (e.g. `</xmp>` sitting inside `<style>`) does not break
383
+ out, so matching is per-element, not a shared alternation. The lookahead
384
+ requires an HTML tag-name terminator (whitespace, `/` or `>`) so a longer
385
+ name such as `</styles` is not mistaken for `</style`. */
386
+ const LITERAL_TEXT_CLOSE = function () {
387
+ const map = {};
388
+ arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, name => {
389
+ map[name] = seal(new RegExp('</' + name + '(?=[\\t\\n\\f\\r />])', 'i'));
390
+ });
391
+ return freeze(map);
392
+ }();
249
393
  const getGlobal = function getGlobal() {
250
394
  return typeof window === 'undefined' ? null : window;
251
395
  };
@@ -300,10 +444,40 @@
300
444
  uponSanitizeShadowNode: []
301
445
  };
302
446
  };
447
+ /**
448
+ * Resolve a set-valued configuration option: a fresh set built from
449
+ * cfg[key] when it is an own array property (seeded with a clone of
450
+ * options.base when given, case-normalized via options.transform),
451
+ * the fallback set otherwise.
452
+ *
453
+ * @param cfg the cloned, prototype-free configuration object
454
+ * @param key the configuration property to read
455
+ * @param fallback the set to use when the option is absent or not an array
456
+ * @param options transform and optional base set to merge into
457
+ * @returns the resolved set
458
+ */
459
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
460
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
461
+ };
462
+ /**
463
+ * Resolve an object-valued configuration option: a prototype-free clone
464
+ * of cfg[key] when it is an own, truthy object property, else a fresh
465
+ * fallback built by makeFallback (fresh on every parse, so a previous
466
+ * parse can never leak state into the next one).
467
+ *
468
+ * @param cfg the cloned, prototype-free configuration object
469
+ * @param key the configuration property to read
470
+ * @param makeFallback builds the fallback value when the option is absent
471
+ * @returns the resolved object
472
+ */
473
+ const _resolveObjectOption = function _resolveObjectOption(cfg, key, makeFallback) {
474
+ const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;
475
+ return value && typeof value === 'object' ? clone(value) : makeFallback();
476
+ };
303
477
  function createDOMPurify() {
304
478
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
305
479
  const DOMPurify = root => createDOMPurify(root);
306
- DOMPurify.version = '3.3.1';
480
+ DOMPurify.version = '3.4.15';
307
481
  DOMPurify.removed = [];
308
482
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
309
483
  // Not running in a browser, provide a factory function
@@ -311,28 +485,46 @@
311
485
  DOMPurify.isSupported = false;
312
486
  return DOMPurify;
313
487
  }
314
- let {
315
- document
316
- } = window;
488
+ let document = window.document;
317
489
  const originalDocument = document;
318
490
  const currentScript = originalDocument.currentScript;
319
- const {
320
- DocumentFragment,
321
- HTMLTemplateElement,
322
- Node,
323
- Element,
324
- NodeFilter,
325
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
326
- HTMLFormElement,
327
- DOMParser,
328
- trustedTypes
329
- } = window;
491
+ window.DocumentFragment;
492
+ const HTMLTemplateElement = window.HTMLTemplateElement,
493
+ Node = window.Node,
494
+ Element = window.Element,
495
+ NodeFilter = window.NodeFilter,
496
+ _window$NamedNodeMap = window.NamedNodeMap;
497
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
498
+ window.HTMLFormElement;
499
+ const DOMParser = window.DOMParser,
500
+ trustedTypes = window.trustedTypes;
330
501
  const ElementPrototype = Element.prototype;
331
502
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
332
503
  const remove = lookupGetter(ElementPrototype, 'remove');
504
+ // Clobber-safe Attr-node removal. On an HTMLFormElement a descendant named
505
+ // "removeAttributeNode" shadows the prototype method via
506
+ // [LegacyOverrideBuiltIns], so element.removeAttributeNode(attr) throws.
507
+ // Calling the cached Element.prototype method with the element as the
508
+ // receiver removes the exact live Attr node regardless of the shadowing.
509
+ const removeAttributeNode = lookupGetter(ElementPrototype, 'removeAttributeNode');
333
510
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
334
511
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
335
512
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
513
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
514
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
515
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
516
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
517
+ const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;
518
+ /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype
519
+ getters, with a direct-property fallback for environments that lack
520
+ Node.prototype. Sites that need a different fallback (e.g. _isClobbered
521
+ returns early on a null name) intentionally keep their own reads. */
522
+ const _readNodeType = function _readNodeType(node) {
523
+ return getNodeType ? getNodeType(node) : node.nodeType;
524
+ };
525
+ const _readNodeName = function _readNodeName(node) {
526
+ return getNodeName ? getNodeName(node) : node.nodeName;
527
+ };
336
528
  // As per issue #47, the web-components registry is inherited by a
337
529
  // new document created via createHTMLDocument. As per the spec
338
530
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -347,33 +539,74 @@
347
539
  }
348
540
  let trustedTypesPolicy;
349
541
  let emptyHTML = '';
350
- const {
351
- implementation,
352
- createNodeIterator,
353
- createDocumentFragment,
354
- getElementsByTagName
355
- } = document;
356
- const {
357
- importNode
358
- } = originalDocument;
542
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
543
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
544
+ // on duplicate policy names — and is the only policy allowed to persist
545
+ // across configurations and survive `clearConfig()`.
546
+ let defaultTrustedTypesPolicy;
547
+ let defaultTrustedTypesPolicyResolved = false;
548
+ // Tracks whether we are already inside a call to the configured Trusted Types
549
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
550
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
551
+ // re-enter the policy and recurse until the stack overflows. We detect that
552
+ // re-entry and throw a clear, actionable error instead. The guard is shared
553
+ // across both callbacks, because either one re-entering `sanitize` triggers
554
+ // the same unbounded recursion.
555
+ let IN_TRUSTED_TYPES_POLICY = 0;
556
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
557
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
558
+ 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.');
559
+ }
560
+ };
561
+ const _createTrustedHTML = function _createTrustedHTML(html) {
562
+ _assertNotInTrustedTypesPolicy();
563
+ IN_TRUSTED_TYPES_POLICY++;
564
+ try {
565
+ return trustedTypesPolicy.createHTML(html);
566
+ } finally {
567
+ IN_TRUSTED_TYPES_POLICY--;
568
+ }
569
+ };
570
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
571
+ _assertNotInTrustedTypesPolicy();
572
+ IN_TRUSTED_TYPES_POLICY++;
573
+ try {
574
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
575
+ } finally {
576
+ IN_TRUSTED_TYPES_POLICY--;
577
+ }
578
+ };
579
+ // Lazily resolve (and cache) the instance's internal default policy.
580
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
581
+ // repeated (Trusted Types throws on duplicate names), and a failed or
582
+ // unsupported attempt must not be retried on every parse.
583
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
584
+ if (!defaultTrustedTypesPolicyResolved) {
585
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
586
+ defaultTrustedTypesPolicyResolved = true;
587
+ }
588
+ return defaultTrustedTypesPolicy;
589
+ };
590
+ const _document = document,
591
+ implementation = _document.implementation,
592
+ createNodeIterator = _document.createNodeIterator,
593
+ createDocumentFragment = _document.createDocumentFragment,
594
+ getElementsByTagName = _document.getElementsByTagName;
595
+ const importNode = originalDocument.importNode;
359
596
  let hooks = _createHooksMap();
360
597
  /**
361
598
  * Expose whether this browser supports running the full DOMPurify.
362
599
  */
363
600
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
364
- const {
365
- MUSTACHE_EXPR,
366
- ERB_EXPR,
367
- TMPLIT_EXPR,
368
- DATA_ATTR,
369
- ARIA_ATTR,
370
- IS_SCRIPT_OR_DATA,
371
- ATTR_WHITESPACE,
372
- CUSTOM_ELEMENT
373
- } = EXPRESSIONS;
374
- let {
375
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
376
- } = EXPRESSIONS;
601
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
602
+ ERB_EXPR$1 = ERB_EXPR,
603
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
604
+ DATA_ATTR$1 = DATA_ATTR,
605
+ ARIA_ATTR$1 = ARIA_ATTR,
606
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
607
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
608
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
609
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
377
610
  /**
378
611
  * We consider the elements and attributes below to be safe. Ideally
379
612
  * don't add any new ones but feel free to remove unwanted ones.
@@ -450,6 +683,13 @@
450
683
  let WHOLE_DOCUMENT = false;
451
684
  /* Track whether config is already set on this instance of DOMPurify. */
452
685
  let SET_CONFIG = false;
686
+ /* Pristine allowlist bindings captured at setConfig() time. On the
687
+ * persistent-config path sanitize() restores the sets from these before
688
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
689
+ * carry across calls. Null until setConfig() is called; reset by
690
+ * clearConfig(). */
691
+ let SET_CONFIG_ALLOWED_TAGS = null;
692
+ let SET_CONFIG_ALLOWED_ATTR = null;
453
693
  /* Decide if all elements (e.g. style, script) must be children of
454
694
  * document.body. By default, browsers might move them to document.head */
455
695
  let FORCE_BODY = false;
@@ -492,7 +732,17 @@
492
732
  let USE_PROFILES = {};
493
733
  /* Tags to ignore content of when KEEP_CONTENT is true */
494
734
  let FORBID_CONTENTS = null;
495
- const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
735
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
736
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
737
+ // the UA (customizable <select>) — including any on* handlers — and the
738
+ // engine re-mirrors synchronously whenever a removal changes which
739
+ // option/selectedcontent is current, even inside DOMPurify's inert
740
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
741
+ // mirror target ahead of the walk, which the engine refills, looping
742
+ // forever (DoS) and amplifying output. Dropping its content on removal
743
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
744
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
745
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
496
746
  /* Tags that are safe for data: URIs */
497
747
  let DATA_URI_TAGS = null;
498
748
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -508,8 +758,10 @@
508
758
  /* Allowed XHTML+XML namespaces */
509
759
  let ALLOWED_NAMESPACES = null;
510
760
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
511
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
512
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
761
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
762
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
763
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
764
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
513
765
  // Certain elements are allowed in both SVG and HTML
514
766
  // namespace. We need to specify them explicitly
515
767
  // so that they don't get erroneously deleted from
@@ -551,15 +803,33 @@
551
803
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
552
804
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
553
805
  /* Set configuration parameters */
554
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
555
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
556
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
557
- URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
558
- DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
559
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
560
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
561
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
562
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
806
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
807
+ transform: transformCaseFunc
808
+ });
809
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
810
+ transform: transformCaseFunc
811
+ });
812
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
813
+ transform: stringToString
814
+ });
815
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
816
+ transform: transformCaseFunc,
817
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
818
+ });
819
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
820
+ transform: transformCaseFunc,
821
+ base: DEFAULT_DATA_URI_TAGS
822
+ });
823
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
824
+ transform: transformCaseFunc
825
+ });
826
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
827
+ transform: transformCaseFunc
828
+ });
829
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
830
+ transform: transformCaseFunc
831
+ });
832
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
563
833
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
564
834
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
565
835
  ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
@@ -575,20 +845,24 @@
575
845
  SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
576
846
  KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
577
847
  IN_PLACE = cfg.IN_PLACE || false; // Default false
578
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
579
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
580
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
581
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
582
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
583
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
584
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
585
- }
586
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
587
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
588
- }
589
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
590
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
591
- }
848
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
849
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
850
+ MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'MATHML_TEXT_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS) // Default built-in map
851
+ );
852
+ HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'HTML_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS) // Default built-in map
853
+ );
854
+ const customElementHandling = _resolveObjectOption(cfg, 'CUSTOM_ELEMENT_HANDLING', () => create(null));
855
+ CUSTOM_ELEMENT_HANDLING = create(null);
856
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
857
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
858
+ }
859
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
860
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
861
+ }
862
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
863
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
864
+ }
865
+ seal(CUSTOM_ELEMENT_HANDLING);
592
866
  if (SAFE_FOR_TEMPLATES) {
593
867
  ALLOW_DATA_ATTR = false;
594
868
  }
@@ -598,7 +872,7 @@
598
872
  /* Parse profile info */
599
873
  if (USE_PROFILES) {
600
874
  ALLOWED_TAGS = addToSet({}, text);
601
- ALLOWED_ATTR = [];
875
+ ALLOWED_ATTR = create(null);
602
876
  if (USE_PROFILES.html === true) {
603
877
  addToSet(ALLOWED_TAGS, html$1);
604
878
  addToSet(ALLOWED_ATTR, html);
@@ -619,37 +893,32 @@
619
893
  addToSet(ALLOWED_ATTR, xml);
620
894
  }
621
895
  }
896
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
897
+ * leaking across calls when switching from function to array config */
898
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
899
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
622
900
  /* Merge configuration parameters */
623
- if (cfg.ADD_TAGS) {
901
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
624
902
  if (typeof cfg.ADD_TAGS === 'function') {
625
903
  EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
626
- } else {
904
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
627
905
  if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
628
906
  ALLOWED_TAGS = clone(ALLOWED_TAGS);
629
907
  }
630
908
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
631
909
  }
632
910
  }
633
- if (cfg.ADD_ATTR) {
911
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
634
912
  if (typeof cfg.ADD_ATTR === 'function') {
635
913
  EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
636
- } else {
914
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
637
915
  if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
638
916
  ALLOWED_ATTR = clone(ALLOWED_ATTR);
639
917
  }
640
918
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
641
919
  }
642
920
  }
643
- if (cfg.ADD_URI_SAFE_ATTR) {
644
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
645
- }
646
- if (cfg.FORBID_CONTENTS) {
647
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
648
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
649
- }
650
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
651
- }
652
- if (cfg.ADD_FORBID_CONTENTS) {
921
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
653
922
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
654
923
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
655
924
  }
@@ -668,6 +937,13 @@
668
937
  addToSet(ALLOWED_TAGS, ['tbody']);
669
938
  delete FORBID_TAGS.tbody;
670
939
  }
940
+ // Re-derive the active Trusted Types policy from this configuration on
941
+ // every parse. The active policy must never be sticky closure state that
942
+ // outlives the config that set it: a caller-supplied policy left in place
943
+ // after `clearConfig()` — or after a later call that supplied none, or
944
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
945
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
946
+ // See GHSA-vxr8-fq34-vvx9.
671
947
  if (cfg.TRUSTED_TYPES_POLICY) {
672
948
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
673
949
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -675,18 +951,45 @@
675
951
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
676
952
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
677
953
  }
678
- // Overwrite existing TrustedTypes policy.
954
+ // A caller-supplied policy applies to this configuration only.
955
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
679
956
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
680
- // Sign local variables required by `sanitize`.
681
- emptyHTML = trustedTypesPolicy.createHTML('');
957
+ // Sign local variables required by `sanitize`. If the supplied policy's
958
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
959
+ // throws via the re-entrancy guard. Restore the previous policy first so
960
+ // the instance is not left in a poisoned state. See #1422.
961
+ try {
962
+ emptyHTML = _createTrustedHTML('');
963
+ } catch (error) {
964
+ trustedTypesPolicy = previousTrustedTypesPolicy;
965
+ throw error;
966
+ }
967
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
968
+ // Explicit opt-out for this call: perform no Trusted Types signing and
969
+ // create nothing (so a strict `trusted-types` CSP that disallows a
970
+ // `dompurify` policy can still call `sanitize` from inside its own
971
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
972
+ // `null` also drops any previously retained caller policy, so it cannot
973
+ // resurface on a later call, while still allowing the next config-less
974
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
975
+ trustedTypesPolicy = undefined;
976
+ emptyHTML = '';
682
977
  } else {
683
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
978
+ // No policy supplied: keep the currently active policy if one is set — a
979
+ // previously supplied policy is intentionally sticky across config-less
980
+ // calls — otherwise fall back to the instance's own internal policy,
981
+ // created at most once. (A policy supplied for a *single* call still
982
+ // lingers by design; what must not linger is a policy whose configuration
983
+ // has been torn down via `clearConfig()`, which restores the default.)
684
984
  if (trustedTypesPolicy === undefined) {
685
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
985
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
686
986
  }
687
- // If creating the internal policy succeeded sign internal variables.
688
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
689
- emptyHTML = trustedTypesPolicy.createHTML('');
987
+ // Sign internal variables only when a policy is active. A falsy policy
988
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
989
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
990
+ // a non-policy and throw. See #1422.
991
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
992
+ emptyHTML = _createTrustedHTML('');
690
993
  }
691
994
  }
692
995
  // Prevent further manipulation of configuration.
@@ -701,6 +1004,77 @@
701
1004
  * correctly. */
702
1005
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
703
1006
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
1007
+ /**
1008
+ * Namespace rules for an element in the SVG namespace.
1009
+ *
1010
+ * @param tagName the element's lowercase tag name
1011
+ * @param parent the (possibly simulated) parent node
1012
+ * @param parentTagName the parent's lowercase tag name
1013
+ * @returns true if a spec-compliant parser could produce this element
1014
+ */
1015
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
1016
+ // The only way to switch from HTML namespace to SVG
1017
+ // is via <svg>. If it happens via any other tag, then
1018
+ // it should be killed.
1019
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1020
+ return tagName === 'svg';
1021
+ }
1022
+ // The only way to switch from MathML to SVG is via <svg>
1023
+ // if the parent is either <annotation-xml> or a MathML
1024
+ // text integration point.
1025
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
1026
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1027
+ }
1028
+ // We only allow elements that are defined in SVG
1029
+ // spec. All others are disallowed in SVG namespace.
1030
+ return Boolean(ALL_SVG_TAGS[tagName]);
1031
+ };
1032
+ /**
1033
+ * Namespace rules for an element in the MathML namespace.
1034
+ *
1035
+ * @param tagName the element's lowercase tag name
1036
+ * @param parent the (possibly simulated) parent node
1037
+ * @param parentTagName the parent's lowercase tag name
1038
+ * @returns true if a spec-compliant parser could produce this element
1039
+ */
1040
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
1041
+ // The only way to switch from HTML namespace to MathML
1042
+ // is via <math>. If it happens via any other tag, then
1043
+ // it should be killed.
1044
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1045
+ return tagName === 'math';
1046
+ }
1047
+ // The only way to switch from SVG to MathML is via
1048
+ // <math> and HTML integration points
1049
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1050
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1051
+ }
1052
+ // We only allow elements that are defined in MathML
1053
+ // spec. All others are disallowed in MathML namespace.
1054
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1055
+ };
1056
+ /**
1057
+ * Namespace rules for an element in the HTML namespace.
1058
+ *
1059
+ * @param tagName the element's lowercase tag name
1060
+ * @param parent the (possibly simulated) parent node
1061
+ * @param parentTagName the parent's lowercase tag name
1062
+ * @returns true if a spec-compliant parser could produce this element
1063
+ */
1064
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1065
+ // The only way to switch from SVG to HTML is via
1066
+ // HTML integration points, and from MathML to HTML
1067
+ // is via MathML text integration points
1068
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1069
+ return false;
1070
+ }
1071
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1072
+ return false;
1073
+ }
1074
+ // We disallow tags that are specific for MathML
1075
+ // or SVG and should never appear in HTML namespace
1076
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1077
+ };
704
1078
  /**
705
1079
  * @param element a DOM element whose namespace is being checked
706
1080
  * @returns Return false if the element has a
@@ -723,51 +1097,13 @@
723
1097
  return false;
724
1098
  }
725
1099
  if (element.namespaceURI === SVG_NAMESPACE) {
726
- // The only way to switch from HTML namespace to SVG
727
- // is via <svg>. If it happens via any other tag, then
728
- // it should be killed.
729
- if (parent.namespaceURI === HTML_NAMESPACE) {
730
- return tagName === 'svg';
731
- }
732
- // The only way to switch from MathML to SVG is via`
733
- // svg if parent is either <annotation-xml> or MathML
734
- // text integration points.
735
- if (parent.namespaceURI === MATHML_NAMESPACE) {
736
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
737
- }
738
- // We only allow elements that are defined in SVG
739
- // spec. All others are disallowed in SVG namespace.
740
- return Boolean(ALL_SVG_TAGS[tagName]);
1100
+ return _checkSvgNamespace(tagName, parent, parentTagName);
741
1101
  }
742
1102
  if (element.namespaceURI === MATHML_NAMESPACE) {
743
- // The only way to switch from HTML namespace to MathML
744
- // is via <math>. If it happens via any other tag, then
745
- // it should be killed.
746
- if (parent.namespaceURI === HTML_NAMESPACE) {
747
- return tagName === 'math';
748
- }
749
- // The only way to switch from SVG to MathML is via
750
- // <math> and HTML integration points
751
- if (parent.namespaceURI === SVG_NAMESPACE) {
752
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
753
- }
754
- // We only allow elements that are defined in MathML
755
- // spec. All others are disallowed in MathML namespace.
756
- return Boolean(ALL_MATHML_TAGS[tagName]);
1103
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
757
1104
  }
758
1105
  if (element.namespaceURI === HTML_NAMESPACE) {
759
- // The only way to switch from SVG to HTML is via
760
- // HTML integration points, and from MathML to HTML
761
- // is via MathML text integration points
762
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
763
- return false;
764
- }
765
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
766
- return false;
767
- }
768
- // We disallow tags that are specific for MathML
769
- // or SVG and should never appear in HTML namespace
770
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1106
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
771
1107
  }
772
1108
  // For XHTML and XML documents that support custom namespaces
773
1109
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -792,28 +1128,153 @@
792
1128
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
793
1129
  getParentNode(node).removeChild(node);
794
1130
  } catch (_) {
1131
+ /* The normal detach failed — this is reached for a parentless node
1132
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1133
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1134
+ "removal" would otherwise hand the caller back an intact,
1135
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1136
+ the style-with-element-child rule decided to kill). Fail closed by
1137
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1138
+ rather than trying to "neutralize" the node via its own methods.
1139
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1140
+ on the node, both of which a <form> root can clobber via a named child
1141
+ (and _isClobbered does not even probe getAttributeNames), so the
1142
+ neutralize step could itself be silently defeated, leaving the payload
1143
+ intact. A throw touches only the cached, clobber-safe remove() and
1144
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1145
+ to every root-kill reason. REPORT-3.
1146
+ This lives inside the catch, so it never fires for a normally-removed
1147
+ in-tree node: those have a parent, removeChild() succeeds, and the
1148
+ catch is not entered. Only a kept (parentless) root reaches here. */
795
1149
  remove(node);
1150
+ if (!getParentNode(node)) {
1151
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1152
+ }
1153
+ }
1154
+ };
1155
+ /**
1156
+ * _stripAttributeNode
1157
+ *
1158
+ * Remove a single Attr node case/namespace-exactly on an attribute-teardown
1159
+ * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an
1160
+ * HTML element in an HTML document and so silently misses a case-preserved
1161
+ * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect
1162
+ * _removeAttribute() was fixed for, which a name-based call would reintroduce
1163
+ * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not
1164
+ * record into DOMPurify.removed: the neutralize passes intentionally do not
1165
+ * book-keep. A clobbered/detached node falls back to best-effort name-based
1166
+ * removal.
1167
+ *
1168
+ * @param element the element to strip the attribute from
1169
+ * @param attribute the Attr node to remove
1170
+ * @param name the attribute's name, for the fallback path
1171
+ */
1172
+ const _stripAttributeNode = function _stripAttributeNode(element, attribute, name) {
1173
+ try {
1174
+ removeAttributeNode(element, attribute);
1175
+ } catch (_) {
1176
+ try {
1177
+ element.removeAttribute(name);
1178
+ } catch (_) {}
1179
+ }
1180
+ };
1181
+ /**
1182
+ * _neutralizeRoot
1183
+ *
1184
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1185
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1186
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1187
+ * parentless guard throws, or any other re-entrant engine mutation — would
1188
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1189
+ * after the abort point still carrying its handlers. There is no safe way
1190
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1191
+ * remove every child and every attribute, then let the caller's catch see
1192
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1193
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1194
+ *
1195
+ * @param root the in-place root to empty
1196
+ */
1197
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1198
+ /* Strip every disallowed attribute (on* handlers included) off the whole
1199
+ subtree BEFORE detaching anything. Detaching first would hand back
1200
+ handler-bearing originals (e.g. an already-loading `<img onerror>`)
1201
+ whose queued resource event still fires in page scope after we throw.
1202
+ Clobber-safe reads; a doomed clobbered node's own attributes are
1203
+ irrelevant while its non-clobbered descendants are reached and scrubbed. */
1204
+ _neutralizeSubtree(root);
1205
+ const childNodes = getChildNodes(root);
1206
+ if (childNodes) {
1207
+ const snapshot = [];
1208
+ arrayForEach(childNodes, child => {
1209
+ arrayPush(snapshot, child);
1210
+ });
1211
+ arrayForEach(snapshot, child => {
1212
+ try {
1213
+ remove(child);
1214
+ } catch (_) {
1215
+ /* Best-effort teardown; a still-attached child is handled below */
1216
+ }
1217
+ });
1218
+ }
1219
+ const attributes = getAttributes(root);
1220
+ if (attributes) {
1221
+ for (let i = attributes.length - 1; i >= 0; --i) {
1222
+ const attribute = attributes[i];
1223
+ const name = attribute && attribute.name;
1224
+ if (typeof name === 'string') {
1225
+ _stripAttributeNode(root, attribute, name);
1226
+ }
1227
+ }
796
1228
  }
797
1229
  };
798
1230
  /**
799
1231
  * _removeAttribute
800
1232
  *
1233
+ * Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their
1234
+ * lookup key for HTML elements in an HTML document, so they silently miss an
1235
+ * attribute whose stored qualified name still contains uppercase ASCII
1236
+ * letters. That happens when the node came from a case-preserving source
1237
+ * (an XML/XHTML document imported via importNode(), or createAttributeNS()),
1238
+ * where e.g. `ONERROR` survives the walk: the policy check lowercases to
1239
+ * `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up
1240
+ * `onerror` and finds nothing. Remove the exact Attr node instead, which is
1241
+ * case- and namespace-exact, and fall back to name-based removal only when
1242
+ * the caller could not supply the node.
1243
+ *
801
1244
  * @param name an Attribute name
802
1245
  * @param element a DOM node
1246
+ * @param attr the exact Attr node to remove, when the caller has it
803
1247
  */
804
- const _removeAttribute = function _removeAttribute(name, element) {
1248
+ const _removeAttribute = function _removeAttribute(name, element, attr) {
1249
+ if (!attr) {
1250
+ try {
1251
+ attr = element.getAttributeNode(name);
1252
+ } catch (_) {
1253
+ attr = null;
1254
+ }
1255
+ }
1256
+ arrayPush(DOMPurify.removed, {
1257
+ attribute: attr || null,
1258
+ from: element
1259
+ });
805
1260
  try {
806
- arrayPush(DOMPurify.removed, {
807
- attribute: element.getAttributeNode(name),
808
- from: element
809
- });
1261
+ if (attr) {
1262
+ removeAttributeNode(element, attr);
1263
+ } else {
1264
+ element.removeAttribute(name);
1265
+ }
810
1266
  } catch (_) {
811
- arrayPush(DOMPurify.removed, {
812
- attribute: null,
813
- from: element
814
- });
1267
+ /* Clobbered or already-detached node - best-effort fall back to a
1268
+ name-based removal so the "is" handling below still runs. Note this
1269
+ fallback ASCII-lowercases its lookup key in an HTML document and so
1270
+ cannot reach a case-preserved attribute name; the cached
1271
+ removeAttributeNode() above is what removes those, and a clobbered
1272
+ form is already removed wholesale by _isClobbered() before reaching
1273
+ here. */
1274
+ try {
1275
+ element.removeAttribute(name);
1276
+ } catch (_) {}
815
1277
  }
816
- element.removeAttribute(name);
817
1278
  // We void attribute values for unremovable "is" attributes
818
1279
  if (name === 'is') {
819
1280
  if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
@@ -827,6 +1288,164 @@
827
1288
  }
828
1289
  }
829
1290
  };
1291
+ /**
1292
+ * _stripDisallowedAttributes
1293
+ *
1294
+ * Removes every attribute the active configuration does not allow from a
1295
+ * single element, using the same allowlist as the main attribute pass (so
1296
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1297
+ * neutralise nodes that are being discarded from an in-place tree.
1298
+ *
1299
+ * @param element the element to strip
1300
+ */
1301
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1302
+ const attributes = getAttributes(element);
1303
+ if (!attributes) {
1304
+ return;
1305
+ }
1306
+ for (let i = attributes.length - 1; i >= 0; --i) {
1307
+ const attribute = attributes[i];
1308
+ const name = attribute && attribute.name;
1309
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1310
+ continue;
1311
+ }
1312
+ _stripAttributeNode(element, attribute, name);
1313
+ }
1314
+ };
1315
+ /**
1316
+ * _neutralizeSubtree
1317
+ *
1318
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1319
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1320
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1321
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1322
+ * those dropped nodes are detached from the caller's LIVE tree but a
1323
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1324
+ * loading) keeps its queued resource event, which fires in page scope after
1325
+ * sanitize returns. This walks a removed subtree and strips every attribute
1326
+ * the active configuration does not allow — so `on*` handlers are cancelled
1327
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1328
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1329
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1330
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1331
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1332
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1333
+ * the `<img>`, are reached and scrubbed).
1334
+ *
1335
+ * @param root the root of a removed subtree to neutralise
1336
+ */
1337
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1338
+ const stack = [root];
1339
+ while (stack.length > 0) {
1340
+ const node = stack.pop();
1341
+ const nodeType = _readNodeType(node);
1342
+ if (nodeType === NODE_TYPE.element) {
1343
+ _stripDisallowedAttributes(node);
1344
+ }
1345
+ const childNodes = getChildNodes(node);
1346
+ if (childNodes) {
1347
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1348
+ stack.push(childNodes[i]);
1349
+ }
1350
+ }
1351
+ }
1352
+ };
1353
+ /**
1354
+ * _neutralizePatchLinkage
1355
+ *
1356
+ * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
1357
+ * hardening, https://github.com/WICG/declarative-partial-updates).
1358
+ *
1359
+ * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
1360
+ * markers (PIs / markup comments) node-by-node, in document order, AS it
1361
+ * reaches each node. On a live in-place root that leaves a window: from the
1362
+ * moment the root is connected until the walk arrives at a given node, that
1363
+ * node's linkage is live. A patch applied on connection/stream can fire as
1364
+ * a microtask during the walk and inject or teleport an unsanitized DOM
1365
+ * range into a region the iterator has already passed and will not revisit,
1366
+ * so the post-return "tree is sanitized" contract is violated. Sweep the
1367
+ * whole tree once up front and sever every linkage before the walk begins,
1368
+ * closing that window.
1369
+ *
1370
+ * This CANNOT undo a patch that already fired before sanitize ran — that is
1371
+ * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
1372
+ * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
1373
+ * to group with the rest of the declarative-partial-updates handling and
1374
+ * stay overridable, consistent with the codebase.
1375
+ *
1376
+ * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
1377
+ * clobbered root cannot defeat the sweep of its non-clobbered descendants.
1378
+ *
1379
+ * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
1380
+ * .html Q1): this mirrors the existing policy of keeping `for` on
1381
+ * <label>/<output>. If the shipping feature can drive a patch through a
1382
+ * surviving `for`-on-label/output + `id` pair, this pre-pass and the
1383
+ * attribute check at _isBasicCustomElement's caller must additionally drop
1384
+ * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
1385
+ *
1386
+ * @param root the in-place root to sweep
1387
+ */
1388
+ /**
1389
+ * Central policy for declarative-partial-updates patch-linkage attributes,
1390
+ * shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so
1391
+ * the two sites cannot drift: `patchsrc` always links, `for` links
1392
+ * everywhere except on <label>/<output>, and the whole policy is gated on
1393
+ * SAFE_FOR_XML (see the rationale block in _isValidAttribute).
1394
+ *
1395
+ * @param lcName the transformCaseFunc'd attribute name
1396
+ * @param lcTag the transformCaseFunc'd tag name of the carrying element
1397
+ * @return true if the attribute is patch linkage and must be dropped
1398
+ */
1399
+ const _isPatchLinkageAttribute = function _isPatchLinkageAttribute(lcName, lcTag) {
1400
+ if (!SAFE_FOR_XML) {
1401
+ return false;
1402
+ }
1403
+ if (lcName === 'patchsrc') {
1404
+ return true;
1405
+ }
1406
+ return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';
1407
+ };
1408
+ const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
1409
+ if (!SAFE_FOR_XML) {
1410
+ return;
1411
+ }
1412
+ const stack = [root];
1413
+ while (stack.length > 0) {
1414
+ const node = stack.pop();
1415
+ const nodeType = _readNodeType(node);
1416
+ /* Remove range markers (the target side of a patch linkage): every
1417
+ processing instruction, and any markup-bearing comment. */
1418
+ if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
1419
+ try {
1420
+ remove(node);
1421
+ } catch (_) {
1422
+ /* Best-effort */
1423
+ }
1424
+ continue;
1425
+ }
1426
+ /* Strip patch-source attributes (the source side) off elements. */
1427
+ if (nodeType === NODE_TYPE.element) {
1428
+ const element = node;
1429
+ const lcTag = transformCaseFunc(_readNodeName(node));
1430
+ try {
1431
+ if (element.hasAttribute && element.hasAttribute('patchsrc')) {
1432
+ element.removeAttribute('patchsrc');
1433
+ }
1434
+ if (element.hasAttribute && element.hasAttribute('for') && _isPatchLinkageAttribute('for', lcTag)) {
1435
+ element.removeAttribute('for');
1436
+ }
1437
+ } catch (_) {
1438
+ /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
1439
+ }
1440
+ }
1441
+ const childNodes = getChildNodes(node);
1442
+ if (childNodes) {
1443
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1444
+ stack.push(childNodes[i]);
1445
+ }
1446
+ }
1447
+ }
1448
+ };
830
1449
  /**
831
1450
  * _initDocument
832
1451
  *
@@ -848,7 +1467,7 @@
848
1467
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
849
1468
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
850
1469
  }
851
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
1470
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
852
1471
  /*
853
1472
  * Use the DOMParser API by default, fallback later if needs be
854
1473
  * DOMParser not work for svg when has multiple root element.
@@ -884,33 +1503,374 @@
884
1503
  * @return The created NodeIterator
885
1504
  */
886
1505
  const _createNodeIterator = function _createNodeIterator(root) {
887
- return createNodeIterator.call(root.ownerDocument || root, root,
1506
+ /* Read ownerDocument through the cached Node.prototype getter, never the
1507
+ direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a
1508
+ clobbering child (<input name="ownerDocument"> or a form-associated
1509
+ external input) shadows the prototype getter and makes a direct read
1510
+ return that <input>. createNodeIterator.call(<input>, ...) then throws
1511
+ "Illegal invocation", and on the IN_PLACE path that throw lands before
1512
+ the walk's fail-closed barrier - leaving the caller's live tree, with
1513
+ any already-armed handler in it, un-neutralized. The cached getter
1514
+ returns the real Document regardless of the clobber. */
1515
+ const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;
1516
+ return createNodeIterator.call(doc || root, root,
888
1517
  // eslint-disable-next-line no-bitwise
889
1518
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
890
1519
  };
1520
+ /**
1521
+ * Replace template expression syntax (mustache, ERB, template
1522
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1523
+ * sites. Order matters: mustache, then ERB, then template literal.
1524
+ *
1525
+ * @param value the string to scrub
1526
+ * @returns the scrubbed string
1527
+ */
1528
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1529
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1530
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1531
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1532
+ return value;
1533
+ };
1534
+ /**
1535
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1536
+ * character data of an element subtree. Used as the final safety net for
1537
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1538
+ * which only form after text-node normalization (e.g. fragments split across
1539
+ * stripped elements) cannot survive into a template-evaluating framework.
1540
+ *
1541
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1542
+ * in place rather than round-tripping through innerHTML. This preserves
1543
+ * descendant node references (important for IN_PLACE callers), avoids a
1544
+ * serialize/reparse cycle, and reads literal character data — which means
1545
+ * `<%...%>` in text content matches the ERB regex against its real bytes
1546
+ * instead of the HTML-entity-escaped form innerHTML would produce.
1547
+ *
1548
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1549
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1550
+ *
1551
+ * @param node The root element whose character data should be scrubbed.
1552
+ */
1553
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1554
+ var _node$querySelectorAl;
1555
+ node.normalize();
1556
+ /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:
1557
+ under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may
1558
+ carry a form-named-getter override of ownerDocument. */
1559
+ const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;
1560
+ const walker = createNodeIterator.call(doc || node, node,
1561
+ // eslint-disable-next-line no-bitwise
1562
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1563
+ let currentNode = walker.nextNode();
1564
+ while (currentNode) {
1565
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1566
+ currentNode = walker.nextNode();
1567
+ }
1568
+ // NodeIterator does not descend into <template>.content per the DOM spec,
1569
+ // so we must explicitly recurse into each template's content fragment,
1570
+ // mirroring the approach used by _sanitizeShadowDOM.
1571
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1572
+ if (templates) {
1573
+ arrayForEach(templates, tmpl => {
1574
+ if (_isDocumentFragment(tmpl.content)) {
1575
+ _scrubTemplateExpressions2(tmpl.content);
1576
+ }
1577
+ });
1578
+ }
1579
+ };
891
1580
  /**
892
1581
  * _isClobbered
893
1582
  *
1583
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1584
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1585
+ * `name` attribute matching a prototype property shadows that property
1586
+ * on direct reads. We use this check at the IN_PLACE entry-point and
1587
+ * during attribute sanitization to refuse clobbered forms.
1588
+ *
894
1589
  * @param element element to check for clobbering attacks
895
1590
  * @return true if clobbered, false if safe
896
1591
  */
897
1592
  const _isClobbered = function _isClobbered(element) {
898
- return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
1593
+ // Realm-independent tag-name probe. If we can't determine the tag
1594
+ // name at all, we can't reason about clobbering — return false
1595
+ // (the caller's other defences still apply).
1596
+ const realTagName = getNodeName ? getNodeName(element) : null;
1597
+ if (typeof realTagName !== 'string') {
1598
+ return false;
1599
+ }
1600
+ if (transformCaseFunc(realTagName) !== 'form') {
1601
+ return false;
1602
+ }
1603
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
1604
+ // Realm-safe NamedNodeMap detection: equality against the cached
1605
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
1606
+ // makes the direct read diverge from the cached read; a clean form
1607
+ // (same-realm OR foreign-realm) has both reads pointing at the same
1608
+ // canonical NamedNodeMap.
1609
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' ||
1610
+ // A form descendant named "removeAttributeNode" or "getAttributeNode"
1611
+ // shadows these Attr-node methods via [LegacyOverrideBuiltIns].
1612
+ // _removeAttribute() / _stripAttributeNode() reach for
1613
+ // element.removeAttributeNode(attr) first; when it is shadowed the call
1614
+ // throws and the name-based fallback element.removeAttribute(name)
1615
+ // ASCII-lowercases its lookup key in an HTML document, silently missing
1616
+ // a case-preserved event-handler attribute (e.g. an ONANIMATIONSTART
1617
+ // that reached the sanitizer through an XML/XHTML parse). Flag the form
1618
+ // so it is removed wholesale, exactly as for the other shadowed methods.
1619
+ typeof element.removeAttributeNode !== 'function' || typeof element.getAttributeNode !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
1620
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
1621
+ // returns the integer 1 for any Element regardless of realm; direct
1622
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
1623
+ // the named child element. Cheap addition — nodeType is read from
1624
+ // an internal slot, no serialization cost — and removes a residual
1625
+ // clobbering surface used by several mXSS / PI / comment branches
1626
+ // in _sanitizeElements that compare currentNode.nodeType directly.
1627
+ element.nodeType !== getNodeType(element) ||
1628
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
1629
+ // "childNodes" shadows the prototype getter. Direct reads of
1630
+ // form.childNodes from a clobbered form return the named child
1631
+ // instead of the real NodeList, so any walk that reads it directly
1632
+ // skips the form's real children. Compare the direct read to the
1633
+ // cached Node.prototype getter — when the form's named-property
1634
+ // getter intercepts the read, the two values differ and we flag
1635
+ // the form. This catches every clobbering child type (input,
1636
+ // select, etc.) regardless of whether the named child happens to
1637
+ // carry a numeric .length, which a typeof-based probe would miss
1638
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
1639
+ element.childNodes !== getChildNodes(element);
899
1640
  };
900
1641
  /**
901
- * Checks whether the given object is a DOM node.
1642
+ * Checks whether the given value is a DocumentFragment from any realm.
1643
+ *
1644
+ * The realm-independent replacement reads `nodeType` through the cached
1645
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1646
+ * constant (11). nodeType is a numeric value resolved from the node's
1647
+ * internal slot, identical across realms for the same kind of node.
1648
+ *
1649
+ * @param value object to check
1650
+ * @return true if value is a DocumentFragment-shaped node from any realm
1651
+ */
1652
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1653
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1654
+ return false;
1655
+ }
1656
+ try {
1657
+ return getNodeType(value) === NODE_TYPE.documentFragment;
1658
+ } catch (_) {
1659
+ return false;
1660
+ }
1661
+ };
1662
+ /**
1663
+ * Checks whether the given object is a DOM node, including nodes that
1664
+ * originate from a different window/realm (e.g. an iframe's
1665
+ * contentDocument). The previous `value instanceof Node` check was
1666
+ * realm-bound: nodes from a different window failed it, causing
1667
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1668
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
902
1669
  *
903
1670
  * @param value object to check whether it's a DOM node
904
- * @return true is object is a DOM node
1671
+ * @return true if value is a DOM node from any realm
905
1672
  */
906
1673
  const _isNode = function _isNode(value) {
907
- return typeof Node === 'function' && value instanceof Node;
1674
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1675
+ return false;
1676
+ }
1677
+ try {
1678
+ return typeof getNodeType(value) === 'number';
1679
+ } catch (_) {
1680
+ return false;
1681
+ }
908
1682
  };
909
1683
  function _executeHooks(hooks, currentNode, data) {
1684
+ if (hooks.length === 0) {
1685
+ return;
1686
+ }
910
1687
  arrayForEach(hooks, hook => {
911
1688
  hook.call(DOMPurify, currentNode, data, CONFIG);
912
1689
  });
913
1690
  }
1691
+ /**
1692
+ * Structural-threat checks that condemn a node regardless of the
1693
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1694
+ * processing instructions, markup-bearing comments. Pure predicate;
1695
+ * the caller removes. Check order is load-bearing.
1696
+ *
1697
+ * @param currentNode the node to inspect
1698
+ * @param tagName the node's transformCaseFunc'd tag name
1699
+ * @return true if the node must be removed
1700
+ */
1701
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1702
+ /* Detect mXSS attempts abusing namespace confusion */
1703
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1704
+ return true;
1705
+ }
1706
+ /* Remove rawtext/literal-text elements whose literal serialization
1707
+ re-opens markup on an HTML reparse - shapes (a) and (b) documented at
1708
+ LITERAL_TEXT_ELEMENTS. Both are invisible to rule 1 above (which
1709
+ self-disables once there is an element child, and whose second probe
1710
+ reads the innerHTML an XML/XHTML document serializes escaped), which
1711
+ is why both probes here read textContent instead. Previously only
1712
+ `style`-with-element-child was covered; every element in
1713
+ LITERAL_TEXT_ELEMENTS shares this literal serialization and is
1714
+ equally affected. */
1715
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && LITERAL_TEXT_ELEMENTS[tagName] && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === 'string' && regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent))) {
1716
+ return true;
1717
+ }
1718
+ /* Remove any occurrence of processing instructions */
1719
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1720
+ return true;
1721
+ }
1722
+ /* Remove any kind of possibly harmful comments */
1723
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1724
+ return true;
1725
+ }
1726
+ return false;
1727
+ };
1728
+ /**
1729
+ * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate
1730
+ * function, per the validation in _parseConfig) against a name.
1731
+ * Additional arguments are forwarded to predicate functions - the
1732
+ * attributeNameCheck predicate receives the tag name as its second
1733
+ * argument. A null/absent check never matches.
1734
+ *
1735
+ * @param check the configured tagNameCheck / attributeNameCheck value
1736
+ * @param name the name to test
1737
+ * @param args extra arguments forwarded to a predicate function
1738
+ * @return true if the check matches the name
1739
+ */
1740
+ const _matchesNameCheck = function _matchesNameCheck(check, name) {
1741
+ if (check instanceof RegExp) {
1742
+ return regExpTest(check, name);
1743
+ }
1744
+ if (check instanceof Function) {
1745
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1746
+ args[_key - 2] = arguments[_key];
1747
+ }
1748
+ return Boolean(check(name, ...args));
1749
+ }
1750
+ return false;
1751
+ };
1752
+ /**
1753
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1754
+ * allowed custom elements (false return exits _sanitizeElements
1755
+ * early - the namespace and fallback-tag removal checks are
1756
+ * intentionally skipped for kept custom elements), else hoist
1757
+ * content per KEEP_CONTENT and remove.
1758
+ *
1759
+ * A kept custom element is the ONLY case in which this function
1760
+ * returns false, so the caller uses that return value to run the
1761
+ * afterSanitizeElements hook on the kept element and keep the
1762
+ * element-hook lifecycle consistent with normal allowlisted
1763
+ * elements (GHSA-c2j3-45gr-mqc4).
1764
+ *
1765
+ * @param currentNode the disallowed node
1766
+ * @param tagName the node's transformCaseFunc'd tag name
1767
+ * @return true if the node was removed, false if kept
1768
+ */
1769
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {
1770
+ /* Check if we have a custom element to handle */
1771
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1772
+ return false;
1773
+ }
1774
+ /* Keep content except for bad-listed elements.
1775
+ Use the cached prototype getters exclusively — the previous code
1776
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1777
+ fallbacks, but the cached getters always return the canonical
1778
+ value (or null for a real parent-less node), so the fallback
1779
+ path was dead in safe cases and a clobbering surface in unsafe
1780
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1781
+ parentNode)` check already gates correctly. */
1782
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1783
+ const parentNode = getParentNode(currentNode);
1784
+ const childNodes = getChildNodes(currentNode);
1785
+ if (childNodes && parentNode) {
1786
+ const childCount = childNodes.length;
1787
+ /* Hoist by moving each child up one level rather than deep-cloning
1788
+ it. Moving transfers every descendant exactly once, so a chain of
1789
+ nested disallowed elements costs O(n) instead of the O(n^2) that
1790
+ re-cloning the shrinking subtree at each level produced; it also
1791
+ empties the removed original, so `DOMPurify.removed` no longer
1792
+ pins whole subtrees. Moving preserves the in-place guarantee too:
1793
+ an original carrying already-queued resource events (`<img
1794
+ onerror>`, `<video>`/`<audio>` error, lazy/`onload`, …) is
1795
+ relocated and sanitised rather than left detached but still armed.
1796
+ The sole case that must clone is removing the walk root itself.
1797
+ The result is serialised from the root's subtree, so a restrictive
1798
+ ALLOWED_TAGS that strips the root (`body` on the string path) must
1799
+ leave the content inside it, which only cloning does. In IN_PLACE
1800
+ the root is pre-validated as an allowed tag and so is never removed
1801
+ here, so that path always takes the move branch.
1802
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1803
+ valid whether we move (drops the trailing entry) or clone (leaves
1804
+ the list intact). */
1805
+ for (let i = childCount - 1; i >= 0; --i) {
1806
+ const hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];
1807
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1808
+ }
1809
+ }
1810
+ }
1811
+ _forceRemove(currentNode);
1812
+ return true;
1813
+ };
1814
+ /**
1815
+ * Fork a hook-mutable allowlist off its shared binding the first time a
1816
+ * (possibly lazily-installed) uponSanitize* hook is about to see it, so the
1817
+ * hook cannot widen the per-instance default or the setConfig binding by
1818
+ * reference and leak past the call. Returns the set unchanged once it is
1819
+ * already call-local, so repeated calls across elements are idempotent.
1820
+ *
1821
+ * @param hookList the uponSanitize* hook array for this event
1822
+ * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding
1823
+ * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant
1824
+ * @param setConfigSet the captured setConfig() binding, or null
1825
+ * @return a call-local clone if a hook is present and set is still shared,
1826
+ * else set unchanged
1827
+ */
1828
+ const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {
1829
+ if (hookList.length === 0) {
1830
+ return set;
1831
+ }
1832
+ return set === defaultSet || set === setConfigSet ? clone(set) : set;
1833
+ };
1834
+ /**
1835
+ * Shared guard for a node that a hook has detached from the walk tree,
1836
+ * used after each element-hook site in _sanitizeElements. Detaching is a
1837
+ * long-standing user pattern (issue #469; draw.io-style foreignObject
1838
+ * filtering). Per the cached, unclobberable parentNode getter the node is
1839
+ * genuinely out of the tree, so it can reach neither the serialized
1840
+ * output nor an IN_PLACE live tree; treat it as removed and stop
1841
+ * processing it. Without this guard, the unsafe-node / namespace checks
1842
+ * would call _forceRemove on a parentless node and hit the REPORT-3
1843
+ * fail-closed throw — which exists for nodes DOMPurify wants gone but
1844
+ * *cannot* detach (clobbered / parentless roots), the opposite of a node
1845
+ * that is already safely gone. The walk root is exempt: a detached
1846
+ * IN_PLACE root is legitimate input and must still be fully sanitized,
1847
+ * and a kill-decision on it must keep hitting the REPORT-3 throw.
1848
+ *
1849
+ * Nodes detached by hooks stay the hook's responsibility for placement:
1850
+ * they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE
1851
+ * pass (which iterates DOMPurify.removed) does not reach them. But a
1852
+ * hook-detached subtree can still hold a queued resource-event handler -
1853
+ * e.g. an <img onload> that began loading when the caller built the live
1854
+ * tree - which fires in page scope after sanitize returns even though the
1855
+ * handler never reached the returned tree. That is the audit-5 F1 hazard,
1856
+ * and the documented node.remove() hook pattern walks straight into it.
1857
+ * So on the IN_PLACE path we neutralize the detached subtree inline,
1858
+ * stripping its non-allow-listed attributes before returning, exactly as
1859
+ * the post-walk pass does for _forceRemove'd subtrees.
1860
+ *
1861
+ * @param currentNode the node a hook may have detached
1862
+ * @param root the current walk root
1863
+ * @return true if the node is detached and now handled, false otherwise
1864
+ */
1865
+ const _handleHookDetachedNode = function _handleHookDetachedNode(currentNode, root) {
1866
+ if (currentNode === root || getParentNode(currentNode) !== null) {
1867
+ return false;
1868
+ }
1869
+ if (IN_PLACE) {
1870
+ _neutralizeSubtree(currentNode);
1871
+ }
1872
+ return true;
1873
+ };
914
1874
  /**
915
1875
  * _sanitizeElements
916
1876
  *
@@ -920,81 +1880,81 @@
920
1880
  * @param currentNode to check for permission to exist
921
1881
  * @return true if node was killed, false if left alive
922
1882
  */
923
- const _sanitizeElements = function _sanitizeElements(currentNode) {
924
- let content = null;
1883
+ const _sanitizeElements = function _sanitizeElements(currentNode, root) {
925
1884
  /* Execute a hook if present */
926
1885
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1886
+ /* A hook may have detached the node - treat it as removed (see
1887
+ _handleHookDetachedNode for the full rationale). */
1888
+ if (_handleHookDetachedNode(currentNode, root)) {
1889
+ return true;
1890
+ }
927
1891
  /* Check if element is clobbered or can clobber */
928
1892
  if (_isClobbered(currentNode)) {
929
1893
  _forceRemove(currentNode);
930
1894
  return true;
931
1895
  }
932
1896
  /* Now let's check the element's type and name */
933
- const tagName = transformCaseFunc(currentNode.nodeName);
1897
+ const tagName = transformCaseFunc(_readNodeName(currentNode));
1898
+ /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement
1899
+ hook may have been installed after that guard sampled the hook arrays
1900
+ (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still
1901
+ aliasing a shared binding that a widening hook would mutate by
1902
+ reference. Fork it before exposing it to the hook. */
1903
+ ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);
934
1904
  /* Execute a hook if present */
935
1905
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
936
1906
  tagName,
937
- allowedTags: ALLOWED_TAGS
938
- });
939
- /* Detect mXSS attempts abusing namespace confusion */
940
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
941
- _forceRemove(currentNode);
942
- return true;
943
- }
944
- /* Remove any occurrence of processing instructions */
945
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
946
- _forceRemove(currentNode);
1907
+ allowedTags: ALLOWED_TAGS
1908
+ });
1909
+ /* The uponSanitizeElement hook may have detached the node, exactly as
1910
+ above (see _handleHookDetachedNode for the full rationale). */
1911
+ if (_handleHookDetachedNode(currentNode, root)) {
947
1912
  return true;
948
1913
  }
949
- /* Remove any kind of possibly harmful comments */
950
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1914
+ /* Remove mXSS vectors, processing instructions and risky comments */
1915
+ if (_isUnsafeNode(currentNode, tagName)) {
951
1916
  _forceRemove(currentNode);
952
1917
  return true;
953
1918
  }
954
1919
  /* Remove element if anything forbids its presence */
955
- if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {
956
- /* Check if we have a custom element to handle */
957
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
958
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
959
- return false;
960
- }
961
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
962
- return false;
963
- }
964
- }
965
- /* Keep content except for bad-listed elements */
966
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
967
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
968
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
969
- if (childNodes && parentNode) {
970
- const childCount = childNodes.length;
971
- for (let i = childCount - 1; i >= 0; --i) {
972
- const childClone = cloneNode(childNodes[i], true);
973
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
974
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
975
- }
976
- }
1920
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1921
+ const removed = _sanitizeDisallowedNode(currentNode, tagName, root);
1922
+ /* A false return means the node is a custom element kept via
1923
+ CUSTOM_ELEMENT_HANDLING - the only keep path through
1924
+ _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
1925
+ element-hook lifecycle matches normal allowlisted elements: a
1926
+ security policy applied in this hook (e.g. stripping an attribute
1927
+ from every surviving element) must not silently skip kept custom
1928
+ elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
1929
+ tail below - the hook runs, then the walker's subsequent
1930
+ _sanitizeAttributes pass sanitizes the element's attributes. The
1931
+ deliberately skipped namespace and fallback-tag removal checks stay
1932
+ skipped; they are removal decisions, not the hook contract. */
1933
+ if (removed === false) {
1934
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
977
1935
  }
978
- _forceRemove(currentNode);
979
- return true;
980
- }
981
- /* Check whether element has a valid namespace */
982
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1936
+ return removed;
1937
+ }
1938
+ /* Check whether element has a valid namespace.
1939
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
1940
+ nodeType getter rather than `instanceof Element`, which is realm-
1941
+ bound and short-circuits to false for any node minted in a different
1942
+ realm — letting a foreign-realm element with a forbidden namespace
1943
+ slip past the namespace check entirely. */
1944
+ const nt = _readNodeType(currentNode);
1945
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
983
1946
  _forceRemove(currentNode);
984
1947
  return true;
985
1948
  }
986
1949
  /* Make sure that older browsers don't get fallback-tag mXSS */
987
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1950
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
988
1951
  _forceRemove(currentNode);
989
1952
  return true;
990
1953
  }
991
1954
  /* Sanitize element content to be template-safe */
992
1955
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
993
1956
  /* Get the element's text content */
994
- content = currentNode.textContent;
995
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
996
- content = stringReplace(content, expr, ' ');
997
- });
1957
+ const content = _stripTemplateExpressions(currentNode.textContent);
998
1958
  if (currentNode.textContent !== content) {
999
1959
  arrayPush(DOMPurify.removed, {
1000
1960
  element: currentNode.cloneNode()
@@ -1016,31 +1976,96 @@
1016
1976
  */
1017
1977
  // eslint-disable-next-line complexity
1018
1978
  const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1979
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1980
+ if (FORBID_ATTR[lcName]) {
1981
+ return false;
1982
+ }
1983
+ /* Reject declarative-partial-updates patch-linkage attributes
1984
+ (https://github.com/WICG/declarative-partial-updates).
1985
+ Empirical note (Chrome 150, verified — see
1986
+ test/declarative-patch-probe-v3.html): expansion is NOT applied after
1987
+ sanitization. For the string path it fires during sanitize()'s own
1988
+ parse, so the walk sees and sanitizes the fully materialized expanded
1989
+ tree — teleports into MathML/SVG integration points included; a
1990
+ weaponized `<template for>`->`<img onerror>` comes back with the handler
1991
+ stripped. For the IN_PLACE path it fires on connection, before the walk.
1992
+ Either way DOMPurify is NOT blind to the patch.
1993
+ This removal is therefore defense-in-depth rather than the sole barrier:
1994
+ it prevents live linkage from surviving into the OUTPUT and re-expanding
1995
+ in the caller's context, and keeps behaviour deterministic if a future
1996
+ engine defers expansion. `for` is legitimate only on <label>/<output>;
1997
+ anywhere else (notably <template for>) it links the element to a patch
1998
+ target and teleports or removes an arbitrary DOM range by id/marker name.
1999
+ `patchsrc` fetches remote markup and is treated as a script-loading
2000
+ mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
2001
+ other structural-threat checks and stays overridable, consistent with
2002
+ the rest of the codebase. PI range markers are already removed by
2003
+ _isUnsafeNode. */
2004
+ if (_isPatchLinkageAttribute(lcName, lcTag)) {
2005
+ return false;
2006
+ }
1019
2007
  /* Make sure attribute cannot clobber */
1020
2008
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1021
2009
  return false;
1022
2010
  }
2011
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1023
2012
  /* Allow valid data-* attributes: At least one character after "-"
1024
2013
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1025
2014
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1026
2015
  We don't need to check the value; it's always URI safe. */
1027
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1028
- if (
1029
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1030
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1031
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1032
- _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)) ||
1033
- // Alternative, second condition checks if it's an `is`-attribute, AND
1034
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1035
- 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 {
1036
- return false;
1037
- }
1038
- /* Check value is safe. First, is attr inert? If so, is safe */
1039
- } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
1040
- return false;
1041
- } else ;
1042
- return true;
2016
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) {
2017
+ return true;
2018
+ }
2019
+ /* Allow valid aria-* attributes, the value is always URI safe */
2020
+ if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) {
2021
+ return true;
2022
+ }
2023
+ /* A name outside the allowlist is acceptable on custom-element terms
2024
+ only. The value checks below are intentionally skipped in that case:
2025
+ if the user supplied a tagNameCheck we also allow derived custom
2026
+ elements using the same test, and attributes passing the configured
2027
+ attributeNameCheck are allowed as custom elements define these at
2028
+ their own discretion. */
2029
+ if (!nameIsPermitted) {
2030
+ return (
2031
+ // Condition a) covers a basically valid custom element tag name whose
2032
+ // tag passes the configured tagNameCheck and whose attribute name
2033
+ // passes the configured attributeNameCheck ...
2034
+ _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) ||
2035
+ // Condition b) covers an `is` attribute whose value passes the
2036
+ // configured tagNameCheck while customized built-in elements are
2037
+ // allowed.
2038
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)
2039
+ );
2040
+ }
2041
+ /* Check value is safe. First, is attr inert? If so, is safe */
2042
+ if (URI_SAFE_ATTRIBUTES[lcName]) {
2043
+ return true;
2044
+ }
2045
+ /* Check no script, data or unknown possibly unsafe URI
2046
+ unless we know URI values are safe for that attribute */
2047
+ if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
2048
+ return true;
2049
+ }
2050
+ /* Keep image data URIs alive if src/xlink:href is allowed */
2051
+ /* Further prevent gadget XSS for dynamically built script tags */
2052
+ if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) {
2053
+ return true;
2054
+ }
2055
+ /* Allow unknown protocols: This provides support for links that
2056
+ are handled by protocol handlers which may be unknown ahead of
2057
+ time, e.g. fb:, spotify: */
2058
+ if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
2059
+ return true;
2060
+ }
2061
+ /* Only an empty (binary) value remains safe at this point;
2062
+ anything else is presumed unsafe, do not add it back */
2063
+ return !value;
1043
2064
  };
2065
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
2066
+ * never be treated as basic custom elements even when a permissive
2067
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
2068
+ 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']);
1044
2069
  /**
1045
2070
  * _isBasicCustomElement
1046
2071
  * checks if at least one dash is included in tagName, and it's not the first char
@@ -1050,7 +2075,75 @@
1050
2075
  * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1051
2076
  */
1052
2077
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1053
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
2078
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
2079
+ };
2080
+ /**
2081
+ * Wrap an attribute value in the matching Trusted Types object when
2082
+ * the active policy requires it. Namespaced attributes pass through
2083
+ * unchanged (no TT support yet, see
2084
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
2085
+ *
2086
+ * @param lcTag lowercase tag name of the containing element
2087
+ * @param lcName lowercase attribute name
2088
+ * @param namespaceURI the attribute's namespace, if any
2089
+ * @param value the attribute value to wrap
2090
+ * @return the value, wrapped when Trusted Types demand it
2091
+ */
2092
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
2093
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
2094
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
2095
+ case 'TrustedHTML':
2096
+ {
2097
+ return _createTrustedHTML(value);
2098
+ }
2099
+ case 'TrustedScriptURL':
2100
+ {
2101
+ return _createTrustedScriptURL(value);
2102
+ }
2103
+ }
2104
+ }
2105
+ return value;
2106
+ };
2107
+ /**
2108
+ * Write a modified attribute value back onto the element. On
2109
+ * success, re-probe for clobbering introduced by the new value and
2110
+ * remove the element when found; otherwise, when this writeback is the
2111
+ * recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the
2112
+ * removal entry that path recorded so it does not show as removed. On
2113
+ * failure, remove the attribute instead.
2114
+ *
2115
+ * Returns true only on a clean write (the value was set and the new value
2116
+ * introduced no clobbering). The caller uses that, together with its own
2117
+ * knowledge of whether this attribute pushed a DOMPurify.removed record, to
2118
+ * decide whether to pop that record. The pop must happen ONLY for the
2119
+ * named-prop remove-and-recreate; popping on any other value change (trim,
2120
+ * template scrubbing, Trusted Types) would consume an unrelated _forceRemove
2121
+ * subtree-cleanup record and let that detached subtree keep a live event
2122
+ * handler through the IN_PLACE neutralization pass (SO-001).
2123
+ *
2124
+ * @param currentNode the element carrying the attribute
2125
+ * @param name the attribute name as present on the element
2126
+ * @param namespaceURI the attribute's namespace, if any
2127
+ * @param value the new attribute value
2128
+ * @return true if the value was written without introducing clobbering
2129
+ */
2130
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
2131
+ try {
2132
+ if (namespaceURI) {
2133
+ currentNode.setAttributeNS(namespaceURI, name, value);
2134
+ } else {
2135
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
2136
+ currentNode.setAttribute(name, value);
2137
+ }
2138
+ if (_isClobbered(currentNode)) {
2139
+ _forceRemove(currentNode);
2140
+ return false;
2141
+ }
2142
+ return true;
2143
+ } catch (_) {
2144
+ _removeAttribute(name, currentNode);
2145
+ return false;
2146
+ }
1054
2147
  };
1055
2148
  /**
1056
2149
  * _sanitizeAttributes
@@ -1062,16 +2155,18 @@
1062
2155
  *
1063
2156
  * @param currentNode to sanitize
1064
2157
  */
2158
+ // eslint-disable-next-line complexity
1065
2159
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1066
2160
  /* Execute a hook if present */
1067
2161
  _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1068
- const {
1069
- attributes
1070
- } = currentNode;
2162
+ const attributes = currentNode.attributes;
1071
2163
  /* Check if we have attributes; if not we might have a text node */
1072
2164
  if (!attributes || _isClobbered(currentNode)) {
1073
2165
  return;
1074
2166
  }
2167
+ /* Same lazy-install guard as uponSanitizeElement (see there): fork the
2168
+ attribute allowlist off its shared binding before a hook can see it. */
2169
+ ALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);
1075
2170
  const hookEvent = {
1076
2171
  attrName: '',
1077
2172
  attrValue: '',
@@ -1080,17 +2175,25 @@
1080
2175
  forceKeepAttr: undefined
1081
2176
  };
1082
2177
  let l = attributes.length;
2178
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1083
2179
  /* Go backwards over all attributes; safely remove bad ones */
1084
2180
  while (l--) {
1085
2181
  const attr = attributes[l];
1086
- const {
1087
- name,
1088
- namespaceURI,
1089
- value: attrValue
1090
- } = attr;
2182
+ const name = attr.name,
2183
+ namespaceURI = attr.namespaceURI,
2184
+ attrValue = attr.value;
1091
2185
  const lcName = transformCaseFunc(name);
1092
2186
  const initValue = attrValue;
1093
2187
  let value = name === 'value' ? initValue : stringTrim(initValue);
2188
+ /* Tracks whether this specific attribute pushed a DOMPurify.removed
2189
+ record that a later _setAttributeValue() writeback is expected to pop
2190
+ back off (the SANITIZE_NAMED_PROPS remove-and-recreate below is the
2191
+ only path that does). A value that merely changed via trim, template
2192
+ scrubbing, or Trusted Types pushes no such record, so its writeback
2193
+ must NOT pop — otherwise it consumes an unrelated _forceRemove subtree
2194
+ record and that detached subtree escapes the IN_PLACE handler-
2195
+ neutralization pass (SO-001). */
2196
+ let recreatedNamedProp = false;
1094
2197
  /* Execute a hook if present */
1095
2198
  hookEvent.attrName = lcName;
1096
2199
  hookEvent.attrValue = value;
@@ -1101,81 +2204,61 @@
1101
2204
  /* Full DOM Clobbering protection via namespace isolation,
1102
2205
  * Prefix id and name attributes with `user-content-`
1103
2206
  */
1104
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
2207
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1105
2208
  // Remove the attribute with this value
1106
- _removeAttribute(name, currentNode);
2209
+ _removeAttribute(name, currentNode, attr);
1107
2210
  // Prefix the value and later re-create the attribute with the sanitized value
1108
2211
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
2212
+ // This attribute owns the record just pushed; its recreate writeback
2213
+ // is the one allowed to pop it back off.
2214
+ recreatedNamedProp = true;
1109
2215
  }
2216
+ // Else: already prefixed, leave the attribute alone — the prefix is
2217
+ // itself the clobbering protection, and re-applying it is incorrect.
1110
2218
  /* Work around a security issue with comments inside attributes */
1111
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) {
1112
- _removeAttribute(name, currentNode);
2219
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
2220
+ _removeAttribute(name, currentNode, attr);
1113
2221
  continue;
1114
2222
  }
1115
2223
  /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1116
2224
  if (lcName === 'attributename' && stringMatch(value, 'href')) {
1117
- _removeAttribute(name, currentNode);
2225
+ _removeAttribute(name, currentNode, attr);
1118
2226
  continue;
1119
2227
  }
1120
- /* Did the hooks approve of the attribute? */
2228
+ /* Did the hooks force-keep the attribute? */
1121
2229
  if (hookEvent.forceKeepAttr) {
1122
2230
  continue;
1123
2231
  }
1124
2232
  /* Did the hooks approve of the attribute? */
1125
2233
  if (!hookEvent.keepAttr) {
1126
- _removeAttribute(name, currentNode);
2234
+ _removeAttribute(name, currentNode, attr);
1127
2235
  continue;
1128
2236
  }
1129
2237
  /* Work around a security issue in jQuery 3.0 */
1130
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1131
- _removeAttribute(name, currentNode);
2238
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
2239
+ _removeAttribute(name, currentNode, attr);
1132
2240
  continue;
1133
2241
  }
1134
2242
  /* Sanitize attribute content to be template-safe */
1135
2243
  if (SAFE_FOR_TEMPLATES) {
1136
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1137
- value = stringReplace(value, expr, ' ');
1138
- });
2244
+ value = _stripTemplateExpressions(value);
1139
2245
  }
1140
2246
  /* Is `value` valid for this attribute? */
1141
- const lcTag = transformCaseFunc(currentNode.nodeName);
1142
2247
  if (!_isValidAttribute(lcTag, lcName, value)) {
1143
- _removeAttribute(name, currentNode);
2248
+ _removeAttribute(name, currentNode, attr);
1144
2249
  continue;
1145
2250
  }
1146
2251
  /* Handle attributes that require Trusted Types */
1147
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1148
- if (namespaceURI) ; else {
1149
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1150
- case 'TrustedHTML':
1151
- {
1152
- value = trustedTypesPolicy.createHTML(value);
1153
- break;
1154
- }
1155
- case 'TrustedScriptURL':
1156
- {
1157
- value = trustedTypesPolicy.createScriptURL(value);
1158
- break;
1159
- }
1160
- }
1161
- }
1162
- }
2252
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1163
2253
  /* Handle invalid data-* attribute set by try-catching it */
1164
2254
  if (value !== initValue) {
1165
- try {
1166
- if (namespaceURI) {
1167
- currentNode.setAttributeNS(namespaceURI, name, value);
1168
- } else {
1169
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1170
- currentNode.setAttribute(name, value);
1171
- }
1172
- if (_isClobbered(currentNode)) {
1173
- _forceRemove(currentNode);
1174
- } else {
1175
- arrayPop(DOMPurify.removed);
1176
- }
1177
- } catch (_) {
1178
- _removeAttribute(name, currentNode);
2255
+ const cleanWrite = _setAttributeValue(currentNode, name, namespaceURI, value);
2256
+ /* Only the named-prop remove-and-recreate owns a DOMPurify.removed
2257
+ record to pop; a plain trim/template/Trusted-Types writeback owns
2258
+ none, so popping here would drop an unrelated subtree's cleanup
2259
+ record (SO-001). */
2260
+ if (cleanWrite && recreatedNamedProp) {
2261
+ arrayPop(DOMPurify.removed);
1179
2262
  }
1180
2263
  }
1181
2264
  }
@@ -1187,7 +2270,7 @@
1187
2270
  *
1188
2271
  * @param fragment to iterate over recursively
1189
2272
  */
1190
- const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
2273
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1191
2274
  let shadowNode = null;
1192
2275
  const shadowIterator = _createNodeIterator(fragment);
1193
2276
  /* Execute a hook if present */
@@ -1196,17 +2279,135 @@
1196
2279
  /* Execute a hook if present */
1197
2280
  _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1198
2281
  /* Sanitize tags and elements */
1199
- _sanitizeElements(shadowNode);
2282
+ _sanitizeElements(shadowNode, fragment);
1200
2283
  /* Check attributes next */
1201
2284
  _sanitizeAttributes(shadowNode);
1202
- /* Deep shadow DOM detected */
1203
- if (shadowNode.content instanceof DocumentFragment) {
1204
- _sanitizeShadowDOM(shadowNode.content);
2285
+ /* Deep shadow DOM detected.
2286
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
2287
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
2288
+ recurse into <template>.content from foreign realms too. */
2289
+ if (_isDocumentFragment(shadowNode.content)) {
2290
+ _sanitizeShadowDOM2(shadowNode.content);
2291
+ }
2292
+ /* An element iterated here may itself host an attached
2293
+ shadow root. The default NodeIterator does not enter shadow
2294
+ trees, so a shadow root nested inside template.content was
2295
+ previously reached by no walk at all (the pre-pass at
2296
+ _sanitizeAttachedShadowRoots descends via childNodes, which
2297
+ doesn't enter template.content; the template-content recursion
2298
+ above iterates the content but never inspected shadowRoot).
2299
+ Walk it explicitly. The nodeType guard avoids reading
2300
+ shadowRoot off text / comment / CDATA / PI nodes that the
2301
+ iterator also surfaces. */
2302
+ if (_readNodeType(shadowNode) === NODE_TYPE.element) {
2303
+ const innerSr = getShadowRoot(shadowNode);
2304
+ if (_isDocumentFragment(innerSr)) {
2305
+ _sanitizeAttachedShadowRoots(innerSr);
2306
+ _sanitizeShadowDOM2(innerSr);
2307
+ }
1205
2308
  }
1206
2309
  }
1207
2310
  /* Execute a hook if present */
1208
2311
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1209
2312
  };
2313
+ /**
2314
+ * _sanitizeAttachedShadowRoots
2315
+ *
2316
+ * Walks `root` and feeds every attached shadow root we encounter into
2317
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
2318
+ * does not descend into shadow trees, so nodes inside an attached
2319
+ * shadow root would otherwise be skipped entirely.
2320
+ *
2321
+ * Two real input paths put attached shadow roots in front of us:
2322
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
2323
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
2324
+ * shadow root because it was created with `clonable: true`.
2325
+ *
2326
+ * This pass runs once, up front, so the main iteration loop (and the
2327
+ * existing _sanitizeShadowDOM template-content recursion) stay
2328
+ * untouched — string-input paths are not affected.
2329
+ *
2330
+ * @param root the subtree root to walk for attached shadow roots
2331
+ */
2332
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
2333
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
2334
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
2335
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
2336
+ call-stack budget would otherwise overflow native recursion here and
2337
+ throw at the IN_PLACE entry pre-pass, before a single node is
2338
+ sanitized, leaving the caller's live tree untouched (fail-open). See
2339
+ campaign-3 F4. A heap stack keeps depth off the call stack.
2340
+ Each work item is either a node to descend into, or a deferred
2341
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
2342
+ form preserves the original post-order discipline: a shadow root's
2343
+ nested shadow roots are discovered before the outer shadow is
2344
+ sanitized (which may remove hosts). Pushes are in reverse of the
2345
+ desired processing order (LIFO): template content, then children, then
2346
+ the shadow-sanitize, then the shadow walk — so the order matches the
2347
+ previous recursion exactly. */
2348
+ const stack = [{
2349
+ node: root,
2350
+ shadow: null
2351
+ }];
2352
+ while (stack.length > 0) {
2353
+ const item = stack.pop();
2354
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
2355
+ if (item.shadow) {
2356
+ _sanitizeShadowDOM2(item.shadow);
2357
+ continue;
2358
+ }
2359
+ const node = item.node;
2360
+ const nodeType = _readNodeType(node);
2361
+ const isElement = nodeType === NODE_TYPE.element;
2362
+ /* (pushed last → processed first) Children, snapshotted in reverse so
2363
+ the first child is processed first. Snapshotting matters because a
2364
+ hook may detach siblings mid-walk. */
2365
+ const childNodes = getChildNodes(node);
2366
+ if (childNodes) {
2367
+ for (let i = childNodes.length - 1; i >= 0; --i) {
2368
+ stack.push({
2369
+ node: childNodes[i],
2370
+ shadow: null
2371
+ });
2372
+ }
2373
+ }
2374
+ /* (pushed before children → processed after them, matching the old
2375
+ "template content last" order) When the node is a <template>,
2376
+ descend into its content. */
2377
+ if (isElement) {
2378
+ const rootName = getNodeName ? getNodeName(node) : null;
2379
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
2380
+ const content = node.content;
2381
+ if (_isDocumentFragment(content)) {
2382
+ stack.push({
2383
+ node: content,
2384
+ shadow: null
2385
+ });
2386
+ }
2387
+ }
2388
+ }
2389
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
2390
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2391
+ rather than `instanceof DocumentFragment`, which is realm-bound and
2392
+ silently skipped foreign-realm shadow roots (e.g.
2393
+ iframe.contentDocument attachShadow). */
2394
+ if (isElement) {
2395
+ const sr = getShadowRoot(node);
2396
+ if (_isDocumentFragment(sr)) {
2397
+ /* Push the deferred sanitise first so it pops after the shadow
2398
+ walk we push next, i.e. nested shadow roots are discovered
2399
+ before this one is sanitised. */
2400
+ stack.push({
2401
+ node: null,
2402
+ shadow: sr
2403
+ }, {
2404
+ node: sr,
2405
+ shadow: null
2406
+ });
2407
+ }
2408
+ }
2409
+ }
2410
+ };
1210
2411
  // eslint-disable-next-line complexity
1211
2412
  DOMPurify.sanitize = function (dirty) {
1212
2413
  let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -1223,13 +2424,9 @@
1223
2424
  }
1224
2425
  /* Stringify, in case dirty is an object */
1225
2426
  if (typeof dirty !== 'string' && !_isNode(dirty)) {
1226
- if (typeof dirty.toString === 'function') {
1227
- dirty = dirty.toString();
1228
- if (typeof dirty !== 'string') {
1229
- throw typeErrorCreate('dirty is not a string, aborting');
1230
- }
1231
- } else {
1232
- throw typeErrorCreate('toString is not a function');
2427
+ dirty = stringifyValue(dirty);
2428
+ if (typeof dirty !== 'string') {
2429
+ throw typeErrorCreate('dirty is not a string, aborting');
1233
2430
  }
1234
2431
  }
1235
2432
  /* Return dirty HTML if DOMPurify cannot run */
@@ -1237,24 +2434,90 @@
1237
2434
  return dirty;
1238
2435
  }
1239
2436
  /* Assign config vars */
1240
- if (!SET_CONFIG) {
2437
+ if (SET_CONFIG) {
2438
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
2439
+ * not re-derived per call. Restore them from the pristine bindings
2440
+ * captured at setConfig() time so a previous call's hook clone (mutated
2441
+ * below) does not carry over. */
2442
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2443
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2444
+ } else {
1241
2445
  _parseConfig(cfg);
1242
2446
  }
2447
+ /* Clone the hook-mutable allowlists before the walk whenever an
2448
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2449
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2450
+ * a hook that widens them would otherwise mutate the shared set
2451
+ * permanently: across later calls and across every element. Cloning per
2452
+ * walk keeps documented in-call widening working while scoping it to the
2453
+ * call. A single guard for both config paths - the per-call path rebinds
2454
+ * the sets in _parseConfig each call, the persistent path restores them
2455
+ * from the captured bindings just above - so the two cannot diverge. */
2456
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2457
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2458
+ }
2459
+ if (hooks.uponSanitizeAttribute.length > 0) {
2460
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2461
+ }
1243
2462
  /* Clean up removed elements */
1244
2463
  DOMPurify.removed = [];
1245
- /* Check if dirty is correctly typed for IN_PLACE */
1246
- if (typeof dirty === 'string') {
1247
- IN_PLACE = false;
1248
- }
1249
- if (IN_PLACE) {
1250
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1251
- if (dirty.nodeName) {
1252
- const tagName = transformCaseFunc(dirty.nodeName);
2464
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2465
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2466
+ where _parseConfig is skipped on later calls: a single string call would
2467
+ disable in-place mode for every subsequent node call, returning a
2468
+ sanitized copy while leaving the caller's node — which in-place callers
2469
+ keep using and whose return value they ignore unsanitized. REPORT-2. */
2470
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2471
+ if (inPlace) {
2472
+ /* Declarative-partial-updates / streaming pre-pass: sever every patch
2473
+ linkage across the live tree BEFORE the walk, so no patch can fire
2474
+ mid-walk and inject into an already-processed region. Runs first, so
2475
+ it also covers the forbidden/clobbered roots that throw below. */
2476
+ _neutralizePatchLinkage(dirty);
2477
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
2478
+ Read nodeName through the cached prototype getter — a clobbering
2479
+ child named "nodeName" on the form root would otherwise shadow
2480
+ the property and let this check skip the root-allowlist
2481
+ validation entirely. */
2482
+ const nn = _readNodeName(dirty);
2483
+ if (typeof nn === 'string') {
2484
+ const tagName = transformCaseFunc(nn);
1253
2485
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
2486
+ /* Fail closed on a live root: neutralize handlers/children before
2487
+ throwing, exactly as the mid-walk abort path does. */
2488
+ _neutralizeRoot(dirty);
1254
2489
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1255
2490
  }
1256
2491
  }
1257
- } else if (dirty instanceof Node) {
2492
+ /* Pre-flight the root through _isClobbered. The iterator-driven
2493
+ removal path can not detach a parent-less root: _forceRemove
2494
+ falls through to Element.prototype.remove(), which per spec
2495
+ is a no-op on a node with no parent. A clobbered root would
2496
+ then survive the main loop with its attributes uninspected,
2497
+ because _sanitizeAttributes early-returns on _isClobbered. The
2498
+ result would be an attacker-controlled form, complete with any
2499
+ event-handler attributes the caller passed in, handed back to
2500
+ the application unsanitized. Refuse to sanitize such a root
2501
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2502
+ if (_isClobbered(dirty)) {
2503
+ /* Fail closed on a live clobbered root before throwing.
2504
+ _neutralizeRoot's reads are clobber-safe (cached getters); the
2505
+ form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
2506
+ _neutralizeRoot(dirty);
2507
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2508
+ }
2509
+ /* Sanitize attached shadow roots before the main iterator runs.
2510
+ The iterator does not descend into shadow trees. Same fail-closed
2511
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2512
+ inside a shadow root could abort this pre-pass before the walk runs,
2513
+ which would otherwise leave the entire live tree unsanitized. */
2514
+ try {
2515
+ _sanitizeAttachedShadowRoots(dirty);
2516
+ } catch (error) {
2517
+ _neutralizeRoot(dirty);
2518
+ throw error;
2519
+ }
2520
+ } else if (_isNode(dirty)) {
1258
2521
  /* If dirty is a DOM element, append to an empty document to avoid
1259
2522
  elements being stripped by the parser */
1260
2523
  body = _initDocument('<!---->');
@@ -1268,12 +2531,25 @@
1268
2531
  // eslint-disable-next-line unicorn/prefer-dom-node-append
1269
2532
  body.appendChild(importedNode);
1270
2533
  }
2534
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
2535
+ them before the main iterator runs, since the iterator does not
2536
+ descend into shadow trees. The walk routes every read through a
2537
+ cached prototype getter so clobbering descendants on a form root
2538
+ cannot hide a shadow host from this pass.
2539
+ Traverse from `body`, not `importedNode`: when importedNode is a
2540
+ DocumentFragment, the appendChild() above moves its children into
2541
+ `body` and leaves the fragment empty, so walking importedNode would
2542
+ scan nothing and miss every attached shadow host now under `body`
2543
+ (SO-003). In the BODY/HTML branches `body === importedNode`, so this
2544
+ is equivalent there; in the element branch `body` contains the
2545
+ appended element and its descendants. `body` covers all three. */
2546
+ _sanitizeAttachedShadowRoots(body);
1271
2547
  } else {
1272
2548
  /* Exit directly if we have nothing to do */
1273
2549
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1274
2550
  // eslint-disable-next-line unicorn/prefer-includes
1275
2551
  dirty.indexOf('<') === -1) {
1276
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
2552
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
1277
2553
  }
1278
2554
  /* Initialize the document to work on */
1279
2555
  body = _initDocument(dirty);
@@ -1287,24 +2563,72 @@
1287
2563
  _forceRemove(body.firstChild);
1288
2564
  }
1289
2565
  /* Get node iterator */
1290
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1291
- /* Now start iterating over the created document */
1292
- while (currentNode = nodeIterator.nextNode()) {
1293
- /* Sanitize tags and elements */
1294
- _sanitizeElements(currentNode);
1295
- /* Check attributes next */
1296
- _sanitizeAttributes(currentNode);
1297
- /* Shadow DOM detected, sanitize it */
1298
- if (currentNode.content instanceof DocumentFragment) {
1299
- _sanitizeShadowDOM(currentNode.content);
2566
+ const walkRoot = inPlace ? dirty : body;
2567
+ /* Now start iterating over the created document.
2568
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2569
+ engine/custom-element mutation can detach a node mid-walk so
2570
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2571
+ barrier the caller's in-place tree would be left half-sanitized with the
2572
+ unvisited tail still armed. _createNodeIterator itself is inside the
2573
+ barrier too: constructing the iterator dereferences the root's document,
2574
+ and any failure there (e.g. an exotic/clobbered root) must still fail
2575
+ closed rather than skip the neutralize. On any throw we fail closed -
2576
+ strip the in-place root bare - then rethrow so the existing throw
2577
+ contract is preserved. (String/DOM-copy paths never return the partial
2578
+ body, so the propagating throw is already fail-closed there.) */
2579
+ try {
2580
+ const nodeIterator = _createNodeIterator(walkRoot);
2581
+ while (currentNode = nodeIterator.nextNode()) {
2582
+ /* Sanitize tags and elements */
2583
+ _sanitizeElements(currentNode, walkRoot);
2584
+ /* Check attributes next */
2585
+ _sanitizeAttributes(currentNode);
2586
+ /* Shadow DOM detected, sanitize it.
2587
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2588
+ instead of instanceof, so foreign-realm <template>.content is
2589
+ walked correctly. */
2590
+ if (_isDocumentFragment(currentNode.content)) {
2591
+ _sanitizeShadowDOM2(currentNode.content);
2592
+ }
2593
+ }
2594
+ } catch (error) {
2595
+ if (inPlace) {
2596
+ _neutralizeRoot(dirty);
2597
+ /* Nodes _forceRemove'd earlier in the aborted walk are already
2598
+ detached from the root, so _neutralizeRoot's subtree pass does not
2599
+ reach them. Defuse them too, mirroring the success-path loop below. */
2600
+ arrayForEach(DOMPurify.removed, entry => {
2601
+ if (entry.element) {
2602
+ _neutralizeSubtree(entry.element);
2603
+ }
2604
+ });
1300
2605
  }
2606
+ throw error;
1301
2607
  }
1302
2608
  /* If we sanitized `dirty` in-place, return it. */
1303
- if (IN_PLACE) {
2609
+ if (inPlace) {
2610
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2611
+ the caller's live tree is detached but may still hold a queued
2612
+ resource-event handler that fires in page scope after we return. The
2613
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2614
+ non-allow-listed attributes off every other removed subtree (clobber,
2615
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2616
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2617
+ arrayForEach(DOMPurify.removed, entry => {
2618
+ if (entry.element) {
2619
+ _neutralizeSubtree(entry.element);
2620
+ }
2621
+ });
2622
+ if (SAFE_FOR_TEMPLATES) {
2623
+ _scrubTemplateExpressions2(dirty);
2624
+ }
1304
2625
  return dirty;
1305
2626
  }
1306
2627
  /* Return sanitized string or DOM */
1307
2628
  if (RETURN_DOM) {
2629
+ if (SAFE_FOR_TEMPLATES) {
2630
+ _scrubTemplateExpressions2(body);
2631
+ }
1308
2632
  if (RETURN_DOM_FRAGMENT) {
1309
2633
  returnNode = createDocumentFragment.call(body.ownerDocument);
1310
2634
  while (body.firstChild) {
@@ -1333,20 +2657,28 @@
1333
2657
  }
1334
2658
  /* Sanitize final string template-safe */
1335
2659
  if (SAFE_FOR_TEMPLATES) {
1336
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1337
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1338
- });
2660
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1339
2661
  }
1340
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
2662
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1341
2663
  };
1342
2664
  DOMPurify.setConfig = function () {
1343
2665
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1344
2666
  _parseConfig(cfg);
1345
2667
  SET_CONFIG = true;
2668
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2669
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
1346
2670
  };
1347
2671
  DOMPurify.clearConfig = function () {
1348
2672
  CONFIG = null;
1349
2673
  SET_CONFIG = false;
2674
+ SET_CONFIG_ALLOWED_TAGS = null;
2675
+ SET_CONFIG_ALLOWED_ATTR = null;
2676
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2677
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2678
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2679
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2680
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2681
+ emptyHTML = '';
1350
2682
  };
1351
2683
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1352
2684
  /* Initialize shared config vars if necessary. */
@@ -1361,9 +2693,19 @@
1361
2693
  if (typeof hookFunction !== 'function') {
1362
2694
  return;
1363
2695
  }
2696
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2697
+ * '__proto__') indexes off the prototype chain rather than a real
2698
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2699
+ * with an own-property check against the known hook names. */
2700
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2701
+ return;
2702
+ }
1364
2703
  arrayPush(hooks[entryPoint], hookFunction);
1365
2704
  };
1366
2705
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
2706
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2707
+ return undefined;
2708
+ }
1367
2709
  if (hookFunction !== undefined) {
1368
2710
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1369
2711
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -1371,6 +2713,9 @@
1371
2713
  return arrayPop(hooks[entryPoint]);
1372
2714
  };
1373
2715
  DOMPurify.removeHooks = function (entryPoint) {
2716
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2717
+ return;
2718
+ }
1374
2719
  hooks[entryPoint] = [];
1375
2720
  };
1376
2721
  DOMPurify.removeAllHooks = function () {
@@ -3807,7 +5152,7 @@
3807
5152
  * @returns {string} html sanitized.
3808
5153
  * @static
3809
5154
  */ static htmlSanitize(html) {
3810
- const annotationRegex = /\<annotation.+\<\/annotation\>/;
5155
+ const annotationRegex = /(<annotation [^>]*>)([\s\S]*?)(<\/annotation>)/i;
3811
5156
  // Get all the annotation content including the tags.
3812
5157
  const annotation = html.match(annotationRegex);
3813
5158
  // Sanitize html code without removing our supported MathML tags and attributes.
@@ -3826,8 +5171,17 @@
3826
5171
  "stackalign"
3827
5172
  ]
3828
5173
  });
3829
- // Readd old annotation content.
3830
- return html.replace(annotationRegex, annotation);
5174
+ if (annotation) {
5175
+ const startTag = annotation[1];
5176
+ const content = annotation[2];
5177
+ const endTag = annotation[3];
5178
+ // Encode strictly <, >, and & to their HTML entities to force the browser to render any HTML as text.
5179
+ const safeContent = content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5180
+ const safeAnnotation = startTag + safeContent + endTag;
5181
+ // Re-insert the safely encoded annotation content.
5182
+ html = html.replace(annotationRegex, safeAnnotation);
5183
+ }
5184
+ return html;
3831
5185
  }
3832
5186
  /**
3833
5187
  * Parses a text and replaces all the HTML entities by their characters.
@@ -11297,49 +12651,68 @@
11297
12651
  * @param {String} mathml MathML to update old one or insert
11298
12652
  * @returns {module:engine/model/element~Element} The model element corresponding to the inserted image
11299
12653
  */ insertMathml(mathml) {
11300
- // This returns the value returned by the callback function (writer => {...})
11301
12654
  return this.editorObject.model.change((writer)=>{
11302
- const core = this.getCore();
12655
+ const { isNewElement, temporalImage } = this.getCore().editionProperties;
11303
12656
  const selection = this.editorObject.model.document.selection;
12657
+ const attributes = Object.fromEntries(selection.getAttributes());
11304
12658
  const modelElementNew = writer.createElement("mathml", {
11305
12659
  formula: mathml,
11306
- ...Object.fromEntries(selection.getAttributes())
12660
+ ...attributes
11307
12661
  });
11308
- // Obtain the DOM <span><img ... /></span> object corresponding to the formula
11309
- if (core.editionProperties.isNewElement) {
11310
- // Don't bother inserting anything at all if the MathML is empty.
11311
- if (!mathml) return;
11312
- const viewSelection = this.core.editionProperties.selection || this.editorObject.editing.view.document.selection;
11313
- const modelPosition = this.editorObject.editing.mapper.toModelPosition(viewSelection.getLastPosition());
11314
- this.editorObject.model.insertObject(modelElementNew, modelPosition);
11315
- // Remove selection
11316
- if (!viewSelection.isCollapsed) {
11317
- for (const range of viewSelection.getRanges()){
11318
- const modelRange = this.editorObject.editing.mapper.toModelRange(range);
11319
- const modelSelection = this.editorObject.model.createSelection(modelRange);
11320
- this.editorObject.model.deleteContent(modelSelection);
11321
- }
11322
- }
11323
- // Set carret after the formula
11324
- const position = this.editorObject.model.createPositionAfter(modelElementNew);
11325
- writer.setSelection(position);
11326
- } else {
11327
- const img = core.editionProperties.temporalImage;
11328
- const viewElement = this.editorObject.editing.view.domConverter.domToView(img).parent;
11329
- const modelElementOld = this.editorObject.editing.mapper.toModelElement(viewElement);
11330
- // Insert the new <mathml> and remove the old one
11331
- const position = this.editorObject.model.createPositionBefore(modelElementOld);
11332
- // If the given MathML is empty, don't insert a new formula.
11333
- if (mathml) {
11334
- this.editorObject.model.insertObject(modelElementNew, position);
11335
- }
11336
- this.editorObject.model.deleteContent(this.editorObject.model.createSelection(modelElementOld, 'on'));
12662
+ if (isNewElement) {
12663
+ return this.insertNewFormula(writer, mathml, modelElementNew);
11337
12664
  }
11338
- // eslint-disable-next-line consistent-return
11339
- return modelElementNew;
12665
+ return this.replaceExistingFormula(mathml, modelElementNew, temporalImage);
11340
12666
  });
11341
12667
  }
11342
12668
  /**
12669
+ * Inserts a new formula at the current selection position.
12670
+ */ insertNewFormula(writer, mathml, modelElement) {
12671
+ if (!mathml) {
12672
+ return;
12673
+ }
12674
+ const viewSelection = this.core.editionProperties.selection || this.editorObject.editing.view.document.selection;
12675
+ const modelPosition = this.editorObject.editing.mapper.toModelPosition(viewSelection.getLastPosition());
12676
+ this.editorObject.model.insertObject(modelElement, modelPosition);
12677
+ this.deleteViewSelection(viewSelection);
12678
+ // Set carret after the formula.
12679
+ const position = this.editorObject.model.createPositionAfter(modelElement);
12680
+ writer.setSelection(position);
12681
+ return modelElement;
12682
+ }
12683
+ deleteViewSelection(viewSelection) {
12684
+ if (viewSelection.isCollapsed) {
12685
+ return;
12686
+ }
12687
+ for (const range of viewSelection.getRanges()){
12688
+ const modelRange = this.editorObject.editing.mapper.toModelRange(range);
12689
+ const modelSelection = this.editorObject.model.createSelection(modelRange);
12690
+ this.editorObject.model.deleteContent(modelSelection);
12691
+ }
12692
+ }
12693
+ /**
12694
+ * Replaces an existing formula with updated MathML.
12695
+ */ replaceExistingFormula(mathml, modelElement, temporalImage) {
12696
+ const viewNode = this.editorObject.editing.view.domConverter.domToView(temporalImage);
12697
+ // Check if image exists in view to do standard formula editing
12698
+ if (viewNode?.parent) {
12699
+ const modelElementOld = this.editorObject.editing.mapper.toModelElement(viewNode.parent);
12700
+ // Insert the new <mathml> and remove the old one
12701
+ const position = this.editorObject.model.createPositionBefore(modelElementOld);
12702
+ if (mathml) {
12703
+ this.editorObject.model.insertObject(modelElement, position);
12704
+ }
12705
+ this.editorObject.model.deleteContent(this.editorObject.model.createSelection(modelElementOld, "on"));
12706
+ return modelElement;
12707
+ }
12708
+ // Otherwise it's LaTeX editing, so we insert at current selection
12709
+ if (!mathml) {
12710
+ return;
12711
+ }
12712
+ this.editorObject.model.insertContent(modelElement);
12713
+ return modelElement;
12714
+ }
12715
+ /**
11343
12716
  * Finds the text node corresponding to given DOM text element.
11344
12717
  * @param {element} viewElement Element to find corresponding text node of.
11345
12718
  * @returns {module:engine/model/text~Text|undefined} Text node corresponding to the given element or undefined if it doesn't exist.
@@ -11366,81 +12739,26 @@
11366
12739
  }
11367
12740
  }
11368
12741
  }
11369
- /** @inheritdoc */ insertFormula(focusElement, windowTarget, mathml, wirisProperties) {
12742
+ /** @inheritdoc */ insertFormula(_focusElement, windowTarget, mathml, _wirisProperties) {
11370
12743
  // eslint-disable-line no-unused-vars
11371
12744
  const returnObject = {};
11372
12745
  let mathmlOrigin;
11373
12746
  if (!mathml) {
11374
12747
  this.insertMathml("");
11375
12748
  } else if (this.core.editMode === "latex") {
11376
- returnObject.latex = Latex.getLatexFromMathML(mathml);
11377
- returnObject.node = windowTarget.document.createTextNode(`$$${returnObject.latex}$$`);
11378
- this.editorObject.model.change((writer)=>{
11379
- const { latexRange } = this.core.editionProperties;
11380
- // Add null check for latexRange.
11381
- // When the editor is initialized in a textarea element, latexRange may not be set on initial load.
11382
- // This check ensures formulas can still be inserted by falling back to MathML insertion if latexRange is not available.
11383
- if (!latexRange) {
11384
- // Fallback to regular MathML insertion if latexRange is not available
11385
- this.insertMathml(mathml);
11386
- return;
11387
- }
11388
- const startNode = this.findText(latexRange.startContainer);
11389
- const endNode = this.findText(latexRange.endContainer);
11390
- let startPosition = writer.createPositionAt(startNode.parent, startNode.startOffset + latexRange.startOffset);
11391
- let endPosition = writer.createPositionAt(endNode.parent, endNode.startOffset + latexRange.endOffset);
11392
- let range = writer.createRange(startPosition, endPosition);
11393
- // When Latex is next to image/formula.
11394
- if (latexRange.startContainer.nodeType === 3 && latexRange.startContainer.previousSibling?.nodeType === 1) {
11395
- // Get the position of the latex to be replaced.
11396
- const latexEdited = `$$${Latex.getLatexFromMathML(MathML.safeXmlDecode(this.core.editionProperties.temporalImage.dataset.mathml))}$$`;
11397
- let data = latexRange.startContainer.data;
11398
- // Remove invisible characters.
11399
- data = data.replaceAll(String.fromCharCode(8288), "");
11400
- // Get to the start of the latex we are editing.
11401
- const offset = data.indexOf(latexEdited);
11402
- const dataOffset = data.substring(offset);
11403
- const second$ = dataOffset.substring(2).indexOf("$$") + 4;
11404
- const substring = dataOffset.substr(0, second$);
11405
- data = data.replace(substring, "");
11406
- if (!data) {
11407
- startPosition = writer.createPositionBefore(startNode);
11408
- range = startNode;
11409
- } else {
11410
- startPosition = startPosition = writer.createPositionAt(startNode.parent, startNode.startOffset + offset);
11411
- endPosition = writer.createPositionAt(endNode.parent, endNode.startOffset + second$ + offset);
11412
- range = writer.createRange(startPosition, endPosition);
11413
- }
11414
- }
11415
- const modelSelection = this.editorObject.model.createSelection(range);
11416
- this.editorObject.model.deleteContent(modelSelection);
11417
- writer.insertText(`$$${returnObject.latex}$$`, startNode.getAttributes(), startPosition);
11418
- });
12749
+ this.handleLatexInsertion(returnObject, windowTarget, mathml);
11419
12750
  } else {
11420
- mathmlOrigin = this.core.editionProperties.temporalImage?.dataset.mathml;
11421
- try {
11422
- returnObject.node = this.editorObject.editing.view.domConverter.viewToDom(this.editorObject.editing.mapper.toViewElement(this.insertMathml(mathml)), windowTarget.document);
11423
- } catch (e) {
11424
- const x = e.toString();
11425
- if (x.includes("CKEditorError: Cannot read property 'parent' of undefined")) {
11426
- this.core.modalDialog.cancelAction();
11427
- }
11428
- }
12751
+ mathmlOrigin = this.handleMathmlInsertion(returnObject, windowTarget, mathml);
11429
12752
  }
11430
- // Build the telemeter payload separated to delete null/undefined entries.
11431
12753
  const payload = {
11432
- mathml_origin: mathmlOrigin ? MathML.safeXmlDecode(mathmlOrigin) : mathmlOrigin,
11433
- mathml: mathml ? MathML.safeXmlDecode(mathml) : mathml,
12754
+ mathml: mathml ? MathML.safeXmlDecode(mathml) : undefined,
11434
12755
  elapsed_time: Date.now() - this.core.editionProperties.editionStartTime,
11435
- editor_origin: null,
11436
12756
  toolbar: this.core.modalDialog.contentManager.toolbar,
11437
12757
  size: mathml?.length
11438
12758
  };
11439
- // Remove desired null keys.
11440
- Object.keys(payload).forEach((key)=>{
11441
- if (key === "mathml_origin" || key === "editor_origin") !payload[key] ? delete payload[key] : {};
11442
- });
11443
- // Call Telemetry service to track the event.
12759
+ if (mathmlOrigin) {
12760
+ payload.mathml_origin = MathML.safeXmlDecode(mathmlOrigin);
12761
+ }
11444
12762
  try {
11445
12763
  Telemeter.telemeter.track("INSERTED_FORMULA", {
11446
12764
  ...payload
@@ -11448,15 +12766,312 @@
11448
12766
  } catch (error) {
11449
12767
  console.error("Error tracking INSERTED_FORMULA", error);
11450
12768
  }
11451
- /* Due to PLUGINS-1329, we add the onChange event to the CK4 insertFormula.
11452
- We probably should add it here as well, but we should look further into how */ // this.editorObject.fire('change');
11453
- // Remove temporal image of inserted formula
11454
12769
  this.core.editionProperties.temporalImage = null;
11455
12770
  return returnObject;
11456
12771
  }
12772
+ handleLatexInsertion(returnObject, windowTarget, mathml) {
12773
+ returnObject.latex = Latex.getLatexFromMathML(mathml);
12774
+ returnObject.node = windowTarget.document.createTextNode(`$$${returnObject.latex}$$`);
12775
+ const { latexRange } = this.core.editionProperties;
12776
+ // When latexRange exists (meaning the whole LaTeX was selected or the editor was opened),
12777
+ // find the node contaning the LaTeX and replace it fully.
12778
+ if (latexRange) {
12779
+ const startNode = this.findText(latexRange.startContainer);
12780
+ const endNode = this.findText(latexRange.endContainer);
12781
+ // If nodes found, use standard replacement.
12782
+ if (startNode && endNode) {
12783
+ this.replaceLatexWithNodes(startNode, endNode, latexRange, returnObject.latex);
12784
+ return;
12785
+ }
12786
+ }
12787
+ this.replaceLatexUsingModelSearch(returnObject.latex);
12788
+ }
12789
+ handleMathmlInsertion(returnObject, windowTarget, mathml) {
12790
+ const mathmlOrigin = this.core.editionProperties.temporalImage?.dataset.mathml;
12791
+ try {
12792
+ const modelElement = this.insertMathml(mathml);
12793
+ const viewElement = this.editorObject.editing.mapper.toViewElement(modelElement);
12794
+ returnObject.node = this.editorObject.editing.view.domConverter.viewToDom(viewElement, windowTarget.document);
12795
+ } catch (error) {
12796
+ if (error.toString().includes("Cannot read property 'parent' of undefined")) {
12797
+ this.core.modalDialog.cancelAction();
12798
+ }
12799
+ }
12800
+ return mathmlOrigin;
12801
+ }
11457
12802
  /**
11458
- * Function called when the content submits an action.
11459
- */ notifyWindowClosed() {
12803
+ * Gets selection attributes excluding track changes tags.
12804
+ */ getCleanSelectionAttributes() {
12805
+ const attributes = {};
12806
+ for (const [key, value] of this.editorObject.model.document.selection.getAttributes()){
12807
+ if (!key.startsWith("suggestion:") && !key.startsWith("comment:")) {
12808
+ attributes[key] = value;
12809
+ }
12810
+ }
12811
+ return attributes;
12812
+ }
12813
+ /**
12814
+ * Searches for the original LaTeX in the model and replaces it.
12815
+ * Fallback when findText() cannot locate DOM nodes (like when there are track changes modifications).
12816
+ */ replaceLatexUsingModelSearch(newLatex) {
12817
+ const foundRange = this.findLatexBlockNearSelection();
12818
+ if (foundRange) {
12819
+ this.editorObject.model.change((writer)=>writer.setSelection(foundRange));
12820
+ this.replaceRangeWithLatex(newLatex);
12821
+ } else {
12822
+ // Insert at current position as a last resort.
12823
+ this.editorObject.model.change((writer)=>{
12824
+ const newLatexText = writer.createText(`$$${newLatex}$$`, this.getCleanSelectionAttributes());
12825
+ this.editorObject.model.insertContent(newLatexText);
12826
+ });
12827
+ }
12828
+ this.core.editionProperties.extractedLatex = null;
12829
+ }
12830
+ /**
12831
+ * Checks if a text proxy has a track changes deletion marker.
12832
+ */ isDeletedText(text) {
12833
+ for (const [key, value] of text.getAttributes()){
12834
+ if (key.startsWith("suggestion:") && value === "deletion") {
12835
+ return true;
12836
+ }
12837
+ }
12838
+ return false;
12839
+ }
12840
+ /**
12841
+ * Finds a LaTeX block ($$...$$) near the current selection.
12842
+ * Handles track changes by considering the "accepted" version of text.
12843
+ */ findLatexBlockNearSelection() {
12844
+ const position = this.editorObject.model.document.selection.getFirstPosition();
12845
+ if (!position?.parent) {
12846
+ return;
12847
+ }
12848
+ // Build LaTeX with track changes accepted suggestions, if any.
12849
+ const { textParts, acceptedText } = this.collectTextParts(position.parent);
12850
+ if (!acceptedText.includes("$$")) {
12851
+ return;
12852
+ }
12853
+ // To handle multiple LaTeX on same line.
12854
+ const targetLatex = this.core.editionProperties.extractedLatex;
12855
+ const fullLatex = `$$${targetLatex}$$`;
12856
+ const startIndex = acceptedText.indexOf(fullLatex);
12857
+ if (startIndex === -1) {
12858
+ return;
12859
+ }
12860
+ const latexBoundaries = {
12861
+ start: startIndex,
12862
+ end: startIndex + fullLatex.length
12863
+ };
12864
+ return this.convertAcceptedOffsetsToModelRange(textParts, latexBoundaries);
12865
+ }
12866
+ /**
12867
+ * Collects all text fragments from a paragraph, tracking both model and accepted text positions.
12868
+ * This is necessary to handle track changes where some LaTeX may have suggestions.
12869
+ */ collectTextParts(paragraph) {
12870
+ const textParts = [];
12871
+ let acceptedTextOffset = 0;
12872
+ let acceptedText = "";
12873
+ for (const item of this.editorObject.model.createRangeIn(paragraph).getItems()){
12874
+ if (item.is("$textProxy")) {
12875
+ const isDeleted = this.isDeletedText(item);
12876
+ textParts.push({
12877
+ text: item.data,
12878
+ startOffset: item.startOffset,
12879
+ endOffset: item.startOffset + item.data.length,
12880
+ parent: item.textNode.parent,
12881
+ acceptedStart: isDeleted ? null : acceptedTextOffset,
12882
+ acceptedEnd: isDeleted ? null : acceptedTextOffset + item.data.length,
12883
+ isDeleted
12884
+ });
12885
+ if (!isDeleted) {
12886
+ acceptedText += item.data;
12887
+ acceptedTextOffset += item.data.length;
12888
+ }
12889
+ }
12890
+ }
12891
+ return {
12892
+ textParts,
12893
+ acceptedText
12894
+ };
12895
+ }
12896
+ /**
12897
+ * Converts LaTeX with track changes accepted suggestions to a CKEditor model Range.
12898
+ */ convertAcceptedOffsetsToModelRange(textParts, latexBoundaries) {
12899
+ let startPartIndex = -1, endPartIndex = -1;
12900
+ let startOffsetInPart = 0, endOffsetInPart = 0;
12901
+ // Find which text parts contain the LaTeX block boundaries
12902
+ for(let i = 0; i < textParts.length; i++){
12903
+ const part = textParts[i];
12904
+ if (part.isDeleted) continue;
12905
+ if (startPartIndex === -1 && latexBoundaries.start >= part.acceptedStart && latexBoundaries.start <= part.acceptedEnd) {
12906
+ startPartIndex = i;
12907
+ startOffsetInPart = latexBoundaries.start - part.acceptedStart;
12908
+ }
12909
+ if (latexBoundaries.end >= part.acceptedStart && latexBoundaries.end <= part.acceptedEnd) {
12910
+ endPartIndex = i;
12911
+ endOffsetInPart = latexBoundaries.end - part.acceptedStart;
12912
+ }
12913
+ }
12914
+ if (startPartIndex === -1 || endPartIndex === -1) {
12915
+ return;
12916
+ }
12917
+ // Extend range to include any consecutive deleted parts after the block.
12918
+ let finalEndIndex = endPartIndex;
12919
+ let finalEndOffset = endOffsetInPart;
12920
+ for(let i = endPartIndex + 1; i < textParts.length && textParts[i].isDeleted; i++){
12921
+ finalEndIndex = i;
12922
+ finalEndOffset = textParts[i].text.length;
12923
+ }
12924
+ const startPart = textParts[startPartIndex];
12925
+ const endPart = textParts[finalEndIndex];
12926
+ return this.editorObject.model.createRange(this.editorObject.model.createPositionAt(startPart.parent, startPart.startOffset + startOffsetInPart), this.editorObject.model.createPositionAt(endPart.parent, endPart.startOffset + finalEndOffset));
12927
+ }
12928
+ replaceRangeWithLatex(newLatex) {
12929
+ this.editorObject.model.change((writer)=>{
12930
+ this.editorObject.model.deleteContent(this.editorObject.model.document.selection);
12931
+ const newLatexText = writer.createText(`$$${newLatex}$$`, this.getCleanSelectionAttributes());
12932
+ this.editorObject.model.insertContent(newLatexText);
12933
+ });
12934
+ }
12935
+ /**
12936
+ * Replaces the whole LaTeX in the CKEditor5 model.
12937
+ */ replaceLatexWithNodes(startNode, endNode, latexRange, newLatex) {
12938
+ this.editorObject.model.change((writer)=>{
12939
+ const startOffset = startNode.startOffset + latexRange.startOffset;
12940
+ const endOffset = endNode.startOffset + latexRange.endOffset;
12941
+ let startPosition = writer.createPositionAt(startNode.parent, startOffset);
12942
+ let endPosition = writer.createPositionAt(endNode.parent, endOffset);
12943
+ // Adjust positions when LaTeX is adjacent to a formula.
12944
+ const startContainer = latexRange.startContainer;
12945
+ if (startContainer.nodeType === Node.TEXT_NODE && startContainer.previousSibling?.nodeType === Node.ELEMENT_NODE) {
12946
+ const originalLatex = `$$${Latex.getLatexFromMathML(MathML.safeXmlDecode(this.core.editionProperties.temporalImage.dataset.mathml))}$$`;
12947
+ const textData = startContainer.data.replaceAll(String.fromCodePoint(8288), "");
12948
+ const latexOffset = textData.indexOf(originalLatex);
12949
+ if (latexOffset !== -1) {
12950
+ const closingDelimiterOffset = textData.substring(latexOffset + 2).indexOf("$$") + 4;
12951
+ startPosition = writer.createPositionAt(startNode.parent, startNode.startOffset + latexOffset);
12952
+ endPosition = writer.createPositionAt(endNode.parent, endNode.startOffset + closingDelimiterOffset + latexOffset);
12953
+ }
12954
+ }
12955
+ writer.setSelection(writer.createRange(startPosition, endPosition));
12956
+ });
12957
+ this.replaceRangeWithLatex(newLatex);
12958
+ }
12959
+ /**
12960
+ * Inherited method from IntegrationModel.
12961
+ * Gets the MathML from a text node containing LaTeX.
12962
+ * Handles track changes by simulating "accept all changes" before conversion.
12963
+ */ getMathmlFromTextNode(textNode, caretPosition) {
12964
+ const standardResult = Latex.getLatexFromTextNode(textNode, caretPosition);
12965
+ const acceptedLatex = this.extractAcceptedLatexFromDOM(textNode, caretPosition);
12966
+ // Prioritize accepted LaTeX if it differs from standard extraction (for track changes compatibility).
12967
+ // Important node: use explicit undefined check to allow empty LaTeX strings, otherwise it would not detect $$$$ as valid LaTeX.
12968
+ const latex = acceptedLatex !== undefined && acceptedLatex !== standardResult?.latex ? acceptedLatex : standardResult?.latex;
12969
+ // Do not continue if no LaTeX found by either method.
12970
+ // This is necessary since both parameters can be independently undefined in some edge cases.
12971
+ if (latex === undefined && acceptedLatex === undefined) {
12972
+ return;
12973
+ }
12974
+ // Verify caret is inside LaTeX block for track changes edge cases.
12975
+ if (!standardResult && acceptedLatex !== undefined && !this.isCaretInsideLatexBlock(textNode, caretPosition)) {
12976
+ return;
12977
+ }
12978
+ const finalLatex = latex === undefined ? acceptedLatex : latex;
12979
+ this.storeLatexRangeWithFallback(textNode, caretPosition, finalLatex);
12980
+ return Latex.getMathMLFromLatex(finalLatex);
12981
+ }
12982
+ isCaretInsideLatexBlock(textNode, caretPosition = 0) {
12983
+ // If LaTeX is found, the caret is inside one.
12984
+ return this.extractAcceptedLatexFromDOM(textNode, caretPosition) !== undefined;
12985
+ }
12986
+ /**
12987
+ * Stores the LaTeX range for its replacement later.
12988
+ */ storeLatexRangeWithFallback(textNode, caretPosition, latex) {
12989
+ const parentTag = textNode.parentElement?.tagName?.toLowerCase();
12990
+ if (!textNode.parentElement || parentTag === "textarea") {
12991
+ return;
12992
+ }
12993
+ const latexResult = Latex.getLatexFromTextNode(textNode, caretPosition);
12994
+ if (latexResult) {
12995
+ const range = document.createRange();
12996
+ range.setStart(latexResult.startNode, latexResult.startPosition);
12997
+ range.setEnd(latexResult.endNode, latexResult.endPosition);
12998
+ this.core.editionProperties.latexRange = range;
12999
+ } else {
13000
+ this.core.editionProperties.latexRange = null;
13001
+ }
13002
+ this.core.editionProperties.extractedLatex = latex;
13003
+ }
13004
+ /**
13005
+ * Finds a container element containing a complete LaTeX block.
13006
+ * Necessary for track changes handling, to find the full LaTeX even with the suggestions.
13007
+ */ findLatexContainerElement(textNode) {
13008
+ const MAX_DEPTH = 10; // Prevent excessive loops.
13009
+ let element = textNode.parentElement;
13010
+ for(let i = 0; i < MAX_DEPTH && element; i++){
13011
+ const text = element.textContent || "";
13012
+ const openDelim = text.indexOf("$$");
13013
+ if (openDelim !== -1 && text.includes("$$", openDelim + 2)) {
13014
+ return element;
13015
+ }
13016
+ element = element.parentElement;
13017
+ }
13018
+ return null;
13019
+ }
13020
+ /**
13021
+ * Extracts LaTeX from DOM, skipping track changes deletion markers.
13022
+ */ extractAcceptedLatexFromDOM(textNode, caretPositionInNode = 0) {
13023
+ const container = this.findLatexContainerElement(textNode);
13024
+ if (!container) {
13025
+ return;
13026
+ }
13027
+ const acceptedText = this.getAcceptedTextContent(container);
13028
+ // Calculate caret offset that will be used later to find the correct LaTeX block.
13029
+ // This includes all accepted text before textNode, plus the caret position within textNode.
13030
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
13031
+ let node = walker.nextNode();
13032
+ let caretOffset = 0;
13033
+ while(node && node !== textNode){
13034
+ if (!node.parentElement?.classList?.contains("ck-suggestion-marker-deletion")) {
13035
+ caretOffset += node.textContent?.length || 0;
13036
+ }
13037
+ node = walker.nextNode();
13038
+ }
13039
+ // Add the caret position within the text node, only if textNode is not deleted by Track Changes.
13040
+ if (node === textNode && !textNode.parentElement?.classList?.contains("ck-suggestion-marker-deletion")) {
13041
+ caretOffset += caretPositionInNode;
13042
+ }
13043
+ // Find the LaTeX block that contains the caret.
13044
+ let nextSearchIndex = 0;
13045
+ while(nextSearchIndex < acceptedText.length){
13046
+ const openDelim = acceptedText.indexOf("$$", nextSearchIndex);
13047
+ if (openDelim === -1) {
13048
+ break;
13049
+ }
13050
+ const closeDelim = acceptedText.indexOf("$$", openDelim + 2);
13051
+ if (closeDelim === -1) {
13052
+ break;
13053
+ }
13054
+ if (caretOffset >= openDelim && caretOffset <= closeDelim + 2) {
13055
+ return acceptedText.substring(openDelim + 2, closeDelim);
13056
+ }
13057
+ nextSearchIndex = closeDelim + 2;
13058
+ }
13059
+ }
13060
+ /**
13061
+ * Recursively extracts text content, skipping track changes tags.
13062
+ */ getAcceptedTextContent(node) {
13063
+ if (node.nodeType === Node.TEXT_NODE) {
13064
+ return node.textContent || "";
13065
+ }
13066
+ if (node.nodeType === Node.ELEMENT_NODE) {
13067
+ if (node.classList?.contains("ck-suggestion-marker-deletion")) {
13068
+ return "";
13069
+ }
13070
+ return Array.from(node.childNodes).map((child)=>this.getAcceptedTextContent(child)).join("");
13071
+ }
13072
+ return "";
13073
+ }
13074
+ /** Called when the modal window is closed. */ notifyWindowClosed() {
11460
13075
  this.editorObject.editing.view.focus();
11461
13076
  }
11462
13077
  }
@@ -11534,7 +13149,7 @@
11534
13149
 
11535
13150
  var chemIcon = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->\n<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\t viewBox=\"0 0 40.3 49.5\" style=\"enable-background:new 0 0 40.3 49.5;\" xml:space=\"preserve\">\n<style type=\"text/css\">\n\t.st0{fill:#A4CF61;}\n</style>\n<path class=\"st0\" d=\"M39.2,12.1c0-1.9-1.1-3.6-2.7-4.4L24.5,0.9l0,0c-0.7-0.4-1.5-0.6-2.4-0.6c-0.9,0-1.7,0.2-2.4,0.6l0,0L2.3,10.8\n\tl0,0C0.9,11.7,0,13.2,0,14.9h0v19.6h0c0,1.7,0.9,3.3,2.3,4.1l0,0l17.4,9.9l0,0c0.7,0.4,1.5,0.6,2.4,0.6c0.9,0,1.7-0.2,2.4-0.6l0,0\n\tl12.2-6.9h0c1.5-0.8,2.6-2.5,2.6-4.3c0-2.7-2.2-4.9-4.9-4.9c-0.9,0-1.8,0.3-2.5,0.7l0,0l-9.7,5.6l-12.3-7V17.8l12.3-7l9.9,5.7l0,0\n\tc0.7,0.4,1.5,0.6,2.4,0.6C37,17,39.2,14.8,39.2,12.1\"/>\n</svg>\n";
11536
13151
 
11537
- var version = "8.15.1";
13152
+ var version = "8.15.3";
11538
13153
  var packageInfo = {
11539
13154
  version: version};
11540
13155
 
@@ -11886,11 +13501,7 @@
11886
13501
  * we must create a new EmptyElement which is independent of the
11887
13502
  * DataProcessor being used by this editor instance
11888
13503
  */ if (imgElement) {
11889
- return viewWriter.createEmptyElement("img", imgElement.getAttributes(), {
11890
- renderUnsafeAttributes: [
11891
- "src"
11892
- ]
11893
- });
13504
+ return viewWriter.createEmptyElement("img", imgElement.getAttributes());
11894
13505
  }
11895
13506
  return null;
11896
13507
  }
@@ -11988,8 +13599,10 @@
11988
13599
  e.return = MathML.removeSafeXMLSemantics(previewOutput);
11989
13600
  return;
11990
13601
  }
11991
- // In save mode, convert formula images back to clean MathML
11992
- const parsedResult = Parser.endParse(output);
13602
+ // Clean track changes markers only from LaTeX content before converting to MathML.
13603
+ const latexParsedOutput = this._endParseEditModeWithTrackChangesSupport(output);
13604
+ // Convert formula images to MathML. It's important to use the save mode to prevent issues.
13605
+ const parsedResult = Parser.endParseSaveMode(latexParsedOutput);
11993
13606
  // Remove all semantic annotations (including handwritten data points)
11994
13607
  // to ensure clean, standard MathML format for storage
11995
13608
  e.return = MathML.removeSafeXMLSemantics(parsedResult);
@@ -12031,6 +13644,38 @@
12031
13644
  });
12032
13645
  }
12033
13646
  /**
13647
+ * When track changes markers are present inside a LaTeX block:
13648
+ * - The LaTeX is preserved as text (not converted to MathML) to maintain suggestions.
13649
+ * - It also prevents the issue where the suggestions were placed as MathML tags.
13650
+ *
13651
+ * When no track changes markers are inside a LaTeX block:
13652
+ * - The LaTeX is converted to MathML normally. (previous default behavior)
13653
+ *
13654
+ * This is to ensure that:
13655
+ * 1. LaTeX without suggestions gets converted to MathML for final output.
13656
+ * 2. LaTeX with pending suggestions is preserved so setData(getData()) works correctly.
13657
+ */ _endParseEditModeWithTrackChangesSupport(code) {
13658
+ if (!Configuration.get("parseModes").includes("latex")) {
13659
+ return code;
13660
+ }
13661
+ const latexBlockRegex = /\$\$([\s\S]*?)\$\$/g;
13662
+ const trackChangesRegex = /<(suggestion|comment)-(start|end)/i;
13663
+ //TODO: Validate if replace all is needed instead of just replace when it is all implemented.
13664
+ return code.replace(latexBlockRegex, (fullMatch, latexContent)=>{
13665
+ // Check if this LaTeX contains track changes markers to prevent conversion.
13666
+ if (trackChangesRegex.test(latexContent)) {
13667
+ return fullMatch;
13668
+ }
13669
+ // When LaTeX has no suggestion, it can be converted to MathML.
13670
+ const decodedLatex = Util.htmlEntitiesDecode(latexContent);
13671
+ let mathml = Util.htmlSanitize(Latex.getMathMLFromLatex(decodedLatex, true));
13672
+ if (!Configuration.get("saveHandTraces")) {
13673
+ mathml = MathML.removeAnnotation(mathml, "application/json");
13674
+ }
13675
+ return mathml;
13676
+ });
13677
+ }
13678
+ /**
12034
13679
  * Expose the WirisPlugin variable to the window
12035
13680
  */ // eslint-disable-next-line class-methods-use-this
12036
13681
  _exposeWiris() {
@@ -12057,8 +13702,21 @@
12057
13702
  // Adds custom label replacing the default 'mathml'.
12058
13703
  // Handles both singular and plural forms.
12059
13704
  trackChangesEditing.descriptionFactory.registerElementLabel("mathml", (quantity)=>(quantity > 1 ? `${quantity} ` : "") + StringManager.get(quantity > 1 ? "formulas" : "formula", integration?.getLanguage() || "en"));
13705
+ this._registerLatexTrackChangesAdapter(integration);
12060
13706
  }
12061
13707
  }
13708
+ /**
13709
+ * Register a custom adapter for handling LaTeX text changes.
13710
+ * This ensures that LaTeX formulas ($$...$$) are treated as atomic units
13711
+ * when used by the track changes feature and avoid partial edits.
13712
+ */ _registerLatexTrackChangesAdapter(integration) {
13713
+ const { editor } = this;
13714
+ editor.model.document.on("change:data", ()=>{
13715
+ if (integration) {
13716
+ integration._trackChangesEnabled = editor.commands.get("trackChanges")?.value ?? false;
13717
+ }
13718
+ });
13719
+ }
12062
13720
  }
12063
13721
 
12064
13722
  exports.CKEditor5Integration = CKEditor5Integration;