Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
galaxyproject
GitHub Repository: galaxyproject/training-material
Path: blob/main/assets/js/dompurify/purify.es.js
1678 views
1
/*! @license DOMPurify 3.0.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.6/LICENSE */
2
3
const {
4
entries,
5
setPrototypeOf,
6
isFrozen,
7
getPrototypeOf,
8
getOwnPropertyDescriptor
9
} = Object;
10
let {
11
freeze,
12
seal,
13
create
14
} = Object; // eslint-disable-line import/no-mutable-exports
15
16
let {
17
apply,
18
construct
19
} = typeof Reflect !== 'undefined' && Reflect;
20
21
if (!freeze) {
22
freeze = function freeze(x) {
23
return x;
24
};
25
}
26
27
if (!seal) {
28
seal = function seal(x) {
29
return x;
30
};
31
}
32
33
if (!apply) {
34
apply = function apply(fun, thisValue, args) {
35
return fun.apply(thisValue, args);
36
};
37
}
38
39
if (!construct) {
40
construct = function construct(Func, args) {
41
return new Func(...args);
42
};
43
}
44
45
const arrayForEach = unapply(Array.prototype.forEach);
46
const arrayPop = unapply(Array.prototype.pop);
47
const arrayPush = unapply(Array.prototype.push);
48
const stringToLowerCase = unapply(String.prototype.toLowerCase);
49
const stringToString = unapply(String.prototype.toString);
50
const stringMatch = unapply(String.prototype.match);
51
const stringReplace = unapply(String.prototype.replace);
52
const stringIndexOf = unapply(String.prototype.indexOf);
53
const stringTrim = unapply(String.prototype.trim);
54
const regExpTest = unapply(RegExp.prototype.test);
55
const typeErrorCreate = unconstruct(TypeError);
56
/**
57
* Creates a new function that calls the given function with a specified thisArg and arguments.
58
*
59
* @param {Function} func - The function to be wrapped and called.
60
* @returns {Function} A new function that calls the given function with a specified thisArg and arguments.
61
*/
62
63
function unapply(func) {
64
return function (thisArg) {
65
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
66
args[_key - 1] = arguments[_key];
67
}
68
69
return apply(func, thisArg, args);
70
};
71
}
72
/**
73
* Creates a new function that constructs an instance of the given constructor function with the provided arguments.
74
*
75
* @param {Function} func - The constructor function to be wrapped and called.
76
* @returns {Function} A new function that constructs an instance of the given constructor function with the provided arguments.
77
*/
78
79
80
function unconstruct(func) {
81
return function () {
82
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
83
args[_key2] = arguments[_key2];
84
}
85
86
return construct(func, args);
87
};
88
}
89
/**
90
* Add properties to a lookup table
91
*
92
* @param {Object} set - The set to which elements will be added.
93
* @param {Array} array - The array containing elements to be added to the set.
94
* @param {Function} transformCaseFunc - An optional function to transform the case of each element before adding to the set.
95
* @returns {Object} The modified set with added elements.
96
*/
97
98
99
function addToSet(set, array) {
100
let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
101
102
if (setPrototypeOf) {
103
// Make 'in' and truthy checks like Boolean(set.constructor)
104
// independent of any properties defined on Object.prototype.
105
// Prevent prototype setters from intercepting set as a this value.
106
setPrototypeOf(set, null);
107
}
108
109
let l = array.length;
110
111
while (l--) {
112
let element = array[l];
113
114
if (typeof element === 'string') {
115
const lcElement = transformCaseFunc(element);
116
117
if (lcElement !== element) {
118
// Config presets (e.g. tags.js, attrs.js) are immutable.
119
if (!isFrozen(array)) {
120
array[l] = lcElement;
121
}
122
123
element = lcElement;
124
}
125
}
126
127
set[element] = true;
128
}
129
130
return set;
131
}
132
/**
133
* Shallow clone an object
134
*
135
* @param {Object} object - The object to be cloned.
136
* @returns {Object} A new object that copies the original.
137
*/
138
139
140
function clone(object) {
141
const newObject = create(null);
142
143
for (const [property, value] of entries(object)) {
144
if (getOwnPropertyDescriptor(object, property) !== undefined) {
145
newObject[property] = value;
146
}
147
}
148
149
return newObject;
150
}
151
/**
152
* This method automatically checks if the prop is function or getter and behaves accordingly.
153
*
154
* @param {Object} object - The object to look up the getter function in its prototype chain.
155
* @param {String} prop - The property name for which to find the getter function.
156
* @returns {Function} The getter function found in the prototype chain or a fallback function.
157
*/
158
159
function lookupGetter(object, prop) {
160
while (object !== null) {
161
const desc = getOwnPropertyDescriptor(object, prop);
162
163
if (desc) {
164
if (desc.get) {
165
return unapply(desc.get);
166
}
167
168
if (typeof desc.value === 'function') {
169
return unapply(desc.value);
170
}
171
}
172
173
object = getPrototypeOf(object);
174
}
175
176
function fallbackValue(element) {
177
console.warn('fallback value for', element);
178
return null;
179
}
180
181
return fallbackValue;
182
}
183
184
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', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG
185
186
const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
187
const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
188
// We still need to know them so that we can do namespace
189
// checks properly in case one wants to add them to
190
// allow-list.
191
192
const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
193
const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); // Similarly to SVG, we want to know all MathML elements,
194
// even those that we disallow by default.
195
196
const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
197
const text = freeze(['#text']);
198
199
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', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
200
const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', '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']);
201
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']);
202
const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
203
204
const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
205
206
const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
207
const TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
208
const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
209
210
const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
211
212
const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
213
);
214
const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
215
const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
216
);
217
const DOCTYPE_NAME = seal(/^html$/i);
218
219
var EXPRESSIONS = /*#__PURE__*/Object.freeze({
220
__proto__: null,
221
MUSTACHE_EXPR: MUSTACHE_EXPR,
222
ERB_EXPR: ERB_EXPR,
223
TMPLIT_EXPR: TMPLIT_EXPR,
224
DATA_ATTR: DATA_ATTR,
225
ARIA_ATTR: ARIA_ATTR,
226
IS_ALLOWED_URI: IS_ALLOWED_URI,
227
IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
228
ATTR_WHITESPACE: ATTR_WHITESPACE,
229
DOCTYPE_NAME: DOCTYPE_NAME
230
});
231
232
const getGlobal = function getGlobal() {
233
return typeof window === 'undefined' ? null : window;
234
};
235
/**
236
* Creates a no-op policy for internal use only.
237
* Don't export this function outside this module!
238
* @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
239
* @param {HTMLScriptElement} purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
240
* @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
241
* are not supported or creating the policy failed).
242
*/
243
244
245
const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
246
if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
247
return null;
248
} // Allow the callers to control the unique policy name
249
// by adding a data-tt-policy-suffix to the script element with the DOMPurify.
250
// Policy creation with duplicate names throws in Trusted Types.
251
252
253
let suffix = null;
254
const ATTR_NAME = 'data-tt-policy-suffix';
255
256
if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
257
suffix = purifyHostElement.getAttribute(ATTR_NAME);
258
}
259
260
const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
261
262
try {
263
return trustedTypes.createPolicy(policyName, {
264
createHTML(html) {
265
return html;
266
},
267
268
createScriptURL(scriptUrl) {
269
return scriptUrl;
270
}
271
272
});
273
} catch (_) {
274
// Policy creation failed (most likely another DOMPurify script has
275
// already run). Skip creating the policy, as this will only cause errors
276
// if TT are enforced.
277
console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
278
return null;
279
}
280
};
281
282
function createDOMPurify() {
283
let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
284
285
const DOMPurify = root => createDOMPurify(root);
286
/**
287
* Version label, exposed for easier checks
288
* if DOMPurify is up to date or not
289
*/
290
291
292
DOMPurify.version = '3.0.6';
293
/**
294
* Array of elements that DOMPurify removed during sanitation.
295
* Empty if nothing was removed.
296
*/
297
298
DOMPurify.removed = [];
299
300
if (!window || !window.document || window.document.nodeType !== 9) {
301
// Not running in a browser, provide a factory function
302
// so that you can pass your own Window
303
DOMPurify.isSupported = false;
304
return DOMPurify;
305
}
306
307
let {
308
document
309
} = window;
310
const originalDocument = document;
311
const currentScript = originalDocument.currentScript;
312
const {
313
DocumentFragment,
314
HTMLTemplateElement,
315
Node,
316
Element,
317
NodeFilter,
318
NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
319
HTMLFormElement,
320
DOMParser,
321
trustedTypes
322
} = window;
323
const ElementPrototype = Element.prototype;
324
const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
325
const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
326
const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
327
const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
328
// new document created via createHTMLDocument. As per the spec
329
// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
330
// a new empty registry is used when creating a template contents owner
331
// document, so we use that as our parent document to ensure nothing
332
// is inherited.
333
334
if (typeof HTMLTemplateElement === 'function') {
335
const template = document.createElement('template');
336
337
if (template.content && template.content.ownerDocument) {
338
document = template.content.ownerDocument;
339
}
340
}
341
342
let trustedTypesPolicy;
343
let emptyHTML = '';
344
const {
345
implementation,
346
createNodeIterator,
347
createDocumentFragment,
348
getElementsByTagName
349
} = document;
350
const {
351
importNode
352
} = originalDocument;
353
let hooks = {};
354
/**
355
* Expose whether this browser supports running the full DOMPurify.
356
*/
357
358
DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
359
const {
360
MUSTACHE_EXPR,
361
ERB_EXPR,
362
TMPLIT_EXPR,
363
DATA_ATTR,
364
ARIA_ATTR,
365
IS_SCRIPT_OR_DATA,
366
ATTR_WHITESPACE
367
} = EXPRESSIONS;
368
let {
369
IS_ALLOWED_URI: IS_ALLOWED_URI$1
370
} = EXPRESSIONS;
371
/**
372
* We consider the elements and attributes below to be safe. Ideally
373
* don't add any new ones but feel free to remove unwanted ones.
374
*/
375
376
/* allowed element names */
377
378
let ALLOWED_TAGS = null;
379
const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
380
/* Allowed attribute names */
381
382
let ALLOWED_ATTR = null;
383
const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
384
/*
385
* Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
386
* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
387
* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
388
* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
389
*/
390
391
let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
392
tagNameCheck: {
393
writable: true,
394
configurable: false,
395
enumerable: true,
396
value: null
397
},
398
attributeNameCheck: {
399
writable: true,
400
configurable: false,
401
enumerable: true,
402
value: null
403
},
404
allowCustomizedBuiltInElements: {
405
writable: true,
406
configurable: false,
407
enumerable: true,
408
value: false
409
}
410
}));
411
/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
412
413
let FORBID_TAGS = null;
414
/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
415
416
let FORBID_ATTR = null;
417
/* Decide if ARIA attributes are okay */
418
419
let ALLOW_ARIA_ATTR = true;
420
/* Decide if custom data attributes are okay */
421
422
let ALLOW_DATA_ATTR = true;
423
/* Decide if unknown protocols are okay */
424
425
let ALLOW_UNKNOWN_PROTOCOLS = false;
426
/* Decide if self-closing tags in attributes are allowed.
427
* Usually removed due to a mXSS issue in jQuery 3.0 */
428
429
let ALLOW_SELF_CLOSE_IN_ATTR = true;
430
/* Output should be safe for common template engines.
431
* This means, DOMPurify removes data attributes, mustaches and ERB
432
*/
433
434
let SAFE_FOR_TEMPLATES = false;
435
/* Decide if document with <html>... should be returned */
436
437
let WHOLE_DOCUMENT = false;
438
/* Track whether config is already set on this instance of DOMPurify. */
439
440
let SET_CONFIG = false;
441
/* Decide if all elements (e.g. style, script) must be children of
442
* document.body. By default, browsers might move them to document.head */
443
444
let FORCE_BODY = false;
445
/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
446
* string (or a TrustedHTML object if Trusted Types are supported).
447
* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
448
*/
449
450
let RETURN_DOM = false;
451
/* Decide if a DOM `DocumentFragment` should be returned, instead of a html
452
* string (or a TrustedHTML object if Trusted Types are supported) */
453
454
let RETURN_DOM_FRAGMENT = false;
455
/* Try to return a Trusted Type object instead of a string, return a string in
456
* case Trusted Types are not supported */
457
458
let RETURN_TRUSTED_TYPE = false;
459
/* Output should be free from DOM clobbering attacks?
460
* This sanitizes markups named with colliding, clobberable built-in DOM APIs.
461
*/
462
463
let SANITIZE_DOM = true;
464
/* Achieve full DOM Clobbering protection by isolating the namespace of named
465
* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
466
*
467
* HTML/DOM spec rules that enable DOM Clobbering:
468
* - Named Access on Window (§7.3.3)
469
* - DOM Tree Accessors (§3.1.5)
470
* - Form Element Parent-Child Relations (§4.10.3)
471
* - Iframe srcdoc / Nested WindowProxies (§4.8.5)
472
* - HTMLCollection (§4.2.10.2)
473
*
474
* Namespace isolation is implemented by prefixing `id` and `name` attributes
475
* with a constant string, i.e., `user-content-`
476
*/
477
478
let SANITIZE_NAMED_PROPS = false;
479
const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
480
/* Keep element content when removing element? */
481
482
let KEEP_CONTENT = true;
483
/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
484
* of importing it into a new Document and returning a sanitized copy */
485
486
let IN_PLACE = false;
487
/* Allow usage of profiles like html, svg and mathMl */
488
489
let USE_PROFILES = {};
490
/* Tags to ignore content of when KEEP_CONTENT is true */
491
492
let FORBID_CONTENTS = null;
493
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']);
494
/* Tags that are safe for data: URIs */
495
496
let DATA_URI_TAGS = null;
497
const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
498
/* Attributes safe for values like "javascript:" */
499
500
let URI_SAFE_ATTRIBUTES = null;
501
const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
502
const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
503
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
504
const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
505
/* Document namespace */
506
507
let NAMESPACE = HTML_NAMESPACE;
508
let IS_EMPTY_INPUT = false;
509
/* Allowed XHTML+XML namespaces */
510
511
let ALLOWED_NAMESPACES = null;
512
const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
513
/* Parsing of strict XHTML documents */
514
515
let PARSER_MEDIA_TYPE = null;
516
const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
517
const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
518
let transformCaseFunc = null;
519
/* Keep a reference to config to pass to hooks */
520
521
let CONFIG = null;
522
/* Ideally, do not touch anything below this line */
523
524
/* ______________________________________________ */
525
526
const formElement = document.createElement('form');
527
528
const isRegexOrFunction = function isRegexOrFunction(testValue) {
529
return testValue instanceof RegExp || testValue instanceof Function;
530
};
531
/**
532
* _parseConfig
533
*
534
* @param {Object} cfg optional config literal
535
*/
536
// eslint-disable-next-line complexity
537
538
539
const _parseConfig = function _parseConfig() {
540
let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
541
542
if (CONFIG && CONFIG === cfg) {
543
return;
544
}
545
/* Shield configuration object from tampering */
546
547
548
if (!cfg || typeof cfg !== 'object') {
549
cfg = {};
550
}
551
/* Shield configuration object from prototype pollution */
552
553
554
cfg = clone(cfg);
555
PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
556
SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
557
558
transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
559
/* Set configuration parameters */
560
561
ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
562
ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
563
ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
564
URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent
565
cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent
566
transformCaseFunc // eslint-disable-line indent
567
) // eslint-disable-line indent
568
: DEFAULT_URI_SAFE_ATTRIBUTES;
569
DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent
570
cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent
571
transformCaseFunc // eslint-disable-line indent
572
) // eslint-disable-line indent
573
: DEFAULT_DATA_URI_TAGS;
574
FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
575
FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
576
FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
577
USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
578
ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
579
580
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
581
582
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
583
584
ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
585
586
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
587
588
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
589
590
RETURN_DOM = cfg.RETURN_DOM || false; // Default false
591
592
RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
593
594
RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
595
596
FORCE_BODY = cfg.FORCE_BODY || false; // Default false
597
598
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
599
600
SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
601
602
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
603
604
IN_PLACE = cfg.IN_PLACE || false; // Default false
605
606
IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
607
NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
608
CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
609
610
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
611
CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
612
}
613
614
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
615
CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
616
}
617
618
if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
619
CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
620
}
621
622
if (SAFE_FOR_TEMPLATES) {
623
ALLOW_DATA_ATTR = false;
624
}
625
626
if (RETURN_DOM_FRAGMENT) {
627
RETURN_DOM = true;
628
}
629
/* Parse profile info */
630
631
632
if (USE_PROFILES) {
633
ALLOWED_TAGS = addToSet({}, [...text]);
634
ALLOWED_ATTR = [];
635
636
if (USE_PROFILES.html === true) {
637
addToSet(ALLOWED_TAGS, html$1);
638
addToSet(ALLOWED_ATTR, html);
639
}
640
641
if (USE_PROFILES.svg === true) {
642
addToSet(ALLOWED_TAGS, svg$1);
643
addToSet(ALLOWED_ATTR, svg);
644
addToSet(ALLOWED_ATTR, xml);
645
}
646
647
if (USE_PROFILES.svgFilters === true) {
648
addToSet(ALLOWED_TAGS, svgFilters);
649
addToSet(ALLOWED_ATTR, svg);
650
addToSet(ALLOWED_ATTR, xml);
651
}
652
653
if (USE_PROFILES.mathMl === true) {
654
addToSet(ALLOWED_TAGS, mathMl$1);
655
addToSet(ALLOWED_ATTR, mathMl);
656
addToSet(ALLOWED_ATTR, xml);
657
}
658
}
659
/* Merge configuration parameters */
660
661
662
if (cfg.ADD_TAGS) {
663
if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
664
ALLOWED_TAGS = clone(ALLOWED_TAGS);
665
}
666
667
addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
668
}
669
670
if (cfg.ADD_ATTR) {
671
if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
672
ALLOWED_ATTR = clone(ALLOWED_ATTR);
673
}
674
675
addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
676
}
677
678
if (cfg.ADD_URI_SAFE_ATTR) {
679
addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
680
}
681
682
if (cfg.FORBID_CONTENTS) {
683
if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
684
FORBID_CONTENTS = clone(FORBID_CONTENTS);
685
}
686
687
addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
688
}
689
/* Add #text in case KEEP_CONTENT is set to true */
690
691
692
if (KEEP_CONTENT) {
693
ALLOWED_TAGS['#text'] = true;
694
}
695
/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
696
697
698
if (WHOLE_DOCUMENT) {
699
addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
700
}
701
/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
702
703
704
if (ALLOWED_TAGS.table) {
705
addToSet(ALLOWED_TAGS, ['tbody']);
706
delete FORBID_TAGS.tbody;
707
}
708
709
if (cfg.TRUSTED_TYPES_POLICY) {
710
if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
711
throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
712
}
713
714
if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
715
throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
716
} // Overwrite existing TrustedTypes policy.
717
718
719
trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; // Sign local variables required by `sanitize`.
720
721
emptyHTML = trustedTypesPolicy.createHTML('');
722
} else {
723
// Uninitialized policy, attempt to initialize the internal dompurify policy.
724
if (trustedTypesPolicy === undefined) {
725
trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
726
} // If creating the internal policy succeeded sign internal variables.
727
728
729
if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
730
emptyHTML = trustedTypesPolicy.createHTML('');
731
}
732
} // Prevent further manipulation of configuration.
733
// Not available in IE8, Safari 5, etc.
734
735
736
if (freeze) {
737
freeze(cfg);
738
}
739
740
CONFIG = cfg;
741
};
742
743
const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
744
const HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
745
// namespace. We need to specify them explicitly
746
// so that they don't get erroneously deleted from
747
// HTML namespace.
748
749
const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
750
/* Keep track of all possible SVG and MathML tags
751
* so that we can perform the namespace checks
752
* correctly. */
753
754
const ALL_SVG_TAGS = addToSet({}, svg$1);
755
addToSet(ALL_SVG_TAGS, svgFilters);
756
addToSet(ALL_SVG_TAGS, svgDisallowed);
757
const ALL_MATHML_TAGS = addToSet({}, mathMl$1);
758
addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
759
/**
760
* @param {Element} element a DOM element whose namespace is being checked
761
* @returns {boolean} Return false if the element has a
762
* namespace that a spec-compliant parser would never
763
* return. Return true otherwise.
764
*/
765
766
const _checkValidNamespace = function _checkValidNamespace(element) {
767
let parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
768
// can be null. We just simulate parent in this case.
769
770
if (!parent || !parent.tagName) {
771
parent = {
772
namespaceURI: NAMESPACE,
773
tagName: 'template'
774
};
775
}
776
777
const tagName = stringToLowerCase(element.tagName);
778
const parentTagName = stringToLowerCase(parent.tagName);
779
780
if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
781
return false;
782
}
783
784
if (element.namespaceURI === SVG_NAMESPACE) {
785
// The only way to switch from HTML namespace to SVG
786
// is via <svg>. If it happens via any other tag, then
787
// it should be killed.
788
if (parent.namespaceURI === HTML_NAMESPACE) {
789
return tagName === 'svg';
790
} // The only way to switch from MathML to SVG is via`
791
// svg if parent is either <annotation-xml> or MathML
792
// text integration points.
793
794
795
if (parent.namespaceURI === MATHML_NAMESPACE) {
796
return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
797
} // We only allow elements that are defined in SVG
798
// spec. All others are disallowed in SVG namespace.
799
800
801
return Boolean(ALL_SVG_TAGS[tagName]);
802
}
803
804
if (element.namespaceURI === MATHML_NAMESPACE) {
805
// The only way to switch from HTML namespace to MathML
806
// is via <math>. If it happens via any other tag, then
807
// it should be killed.
808
if (parent.namespaceURI === HTML_NAMESPACE) {
809
return tagName === 'math';
810
} // The only way to switch from SVG to MathML is via
811
// <math> and HTML integration points
812
813
814
if (parent.namespaceURI === SVG_NAMESPACE) {
815
return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
816
} // We only allow elements that are defined in MathML
817
// spec. All others are disallowed in MathML namespace.
818
819
820
return Boolean(ALL_MATHML_TAGS[tagName]);
821
}
822
823
if (element.namespaceURI === HTML_NAMESPACE) {
824
// The only way to switch from SVG to HTML is via
825
// HTML integration points, and from MathML to HTML
826
// is via MathML text integration points
827
if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
828
return false;
829
}
830
831
if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
832
return false;
833
} // We disallow tags that are specific for MathML
834
// or SVG and should never appear in HTML namespace
835
836
837
return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
838
} // For XHTML and XML documents that support custom namespaces
839
840
841
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
842
return true;
843
} // The code should never reach this place (this means
844
// that the element somehow got namespace that is not
845
// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
846
// Return false just in case.
847
848
849
return false;
850
};
851
/**
852
* _forceRemove
853
*
854
* @param {Node} node a DOM node
855
*/
856
857
858
const _forceRemove = function _forceRemove(node) {
859
arrayPush(DOMPurify.removed, {
860
element: node
861
});
862
863
try {
864
// eslint-disable-next-line unicorn/prefer-dom-node-remove
865
node.parentNode.removeChild(node);
866
} catch (_) {
867
node.remove();
868
}
869
};
870
/**
871
* _removeAttribute
872
*
873
* @param {String} name an Attribute name
874
* @param {Node} node a DOM node
875
*/
876
877
878
const _removeAttribute = function _removeAttribute(name, node) {
879
try {
880
arrayPush(DOMPurify.removed, {
881
attribute: node.getAttributeNode(name),
882
from: node
883
});
884
} catch (_) {
885
arrayPush(DOMPurify.removed, {
886
attribute: null,
887
from: node
888
});
889
}
890
891
node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes
892
893
if (name === 'is' && !ALLOWED_ATTR[name]) {
894
if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
895
try {
896
_forceRemove(node);
897
} catch (_) {}
898
} else {
899
try {
900
node.setAttribute(name, '');
901
} catch (_) {}
902
}
903
}
904
};
905
/**
906
* _initDocument
907
*
908
* @param {String} dirty a string of dirty markup
909
* @return {Document} a DOM, filled with the dirty markup
910
*/
911
912
913
const _initDocument = function _initDocument(dirty) {
914
/* Create a HTML document */
915
let doc = null;
916
let leadingWhitespace = null;
917
918
if (FORCE_BODY) {
919
dirty = '<remove></remove>' + dirty;
920
} else {
921
/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
922
const matches = stringMatch(dirty, /^[\r\n\t ]+/);
923
leadingWhitespace = matches && matches[0];
924
}
925
926
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
927
// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
928
dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
929
}
930
931
const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
932
/*
933
* Use the DOMParser API by default, fallback later if needs be
934
* DOMParser not work for svg when has multiple root element.
935
*/
936
937
if (NAMESPACE === HTML_NAMESPACE) {
938
try {
939
doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
940
} catch (_) {}
941
}
942
/* Use createHTMLDocument in case DOMParser is not available */
943
944
945
if (!doc || !doc.documentElement) {
946
doc = implementation.createDocument(NAMESPACE, 'template', null);
947
948
try {
949
doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
950
} catch (_) {// Syntax error if dirtyPayload is invalid xml
951
}
952
}
953
954
const body = doc.body || doc.documentElement;
955
956
if (dirty && leadingWhitespace) {
957
body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
958
}
959
/* Work on whole document or just its body */
960
961
962
if (NAMESPACE === HTML_NAMESPACE) {
963
return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
964
}
965
966
return WHOLE_DOCUMENT ? doc.documentElement : body;
967
};
968
/**
969
* Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
970
*
971
* @param {Node} root The root element or node to start traversing on.
972
* @return {NodeIterator} The created NodeIterator
973
*/
974
975
976
const _createNodeIterator = function _createNodeIterator(root) {
977
return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
978
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null);
979
};
980
/**
981
* _isClobbered
982
*
983
* @param {Node} elm element to check for clobbering attacks
984
* @return {Boolean} true if clobbered, false if safe
985
*/
986
987
988
const _isClobbered = function _isClobbered(elm) {
989
return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function');
990
};
991
/**
992
* Checks whether the given object is a DOM node.
993
*
994
* @param {Node} object object to check whether it's a DOM node
995
* @return {Boolean} true is object is a DOM node
996
*/
997
998
999
const _isNode = function _isNode(object) {
1000
return typeof Node === 'function' && object instanceof Node;
1001
};
1002
/**
1003
* _executeHook
1004
* Execute user configurable hooks
1005
*
1006
* @param {String} entryPoint Name of the hook's entry point
1007
* @param {Node} currentNode node to work on with the hook
1008
* @param {Object} data additional hook parameters
1009
*/
1010
1011
1012
const _executeHook = function _executeHook(entryPoint, currentNode, data) {
1013
if (!hooks[entryPoint]) {
1014
return;
1015
}
1016
1017
arrayForEach(hooks[entryPoint], hook => {
1018
hook.call(DOMPurify, currentNode, data, CONFIG);
1019
});
1020
};
1021
/**
1022
* _sanitizeElements
1023
*
1024
* @protect nodeName
1025
* @protect textContent
1026
* @protect removeChild
1027
*
1028
* @param {Node} currentNode to check for permission to exist
1029
* @return {Boolean} true if node was killed, false if left alive
1030
*/
1031
1032
1033
const _sanitizeElements = function _sanitizeElements(currentNode) {
1034
let content = null;
1035
/* Execute a hook if present */
1036
1037
_executeHook('beforeSanitizeElements', currentNode, null);
1038
/* Check if element is clobbered or can clobber */
1039
1040
1041
if (_isClobbered(currentNode)) {
1042
_forceRemove(currentNode);
1043
1044
return true;
1045
}
1046
/* Now let's check the element's type and name */
1047
1048
1049
const tagName = transformCaseFunc(currentNode.nodeName);
1050
/* Execute a hook if present */
1051
1052
_executeHook('uponSanitizeElement', currentNode, {
1053
tagName,
1054
allowedTags: ALLOWED_TAGS
1055
});
1056
/* Detect mXSS attempts abusing namespace confusion */
1057
1058
1059
if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
1060
_forceRemove(currentNode);
1061
1062
return true;
1063
}
1064
/* Remove element if anything forbids its presence */
1065
1066
1067
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1068
/* Check if we have a custom element to handle */
1069
if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1070
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1071
return false;
1072
}
1073
1074
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1075
return false;
1076
}
1077
}
1078
/* Keep content except for bad-listed elements */
1079
1080
1081
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1082
const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1083
const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1084
1085
if (childNodes && parentNode) {
1086
const childCount = childNodes.length;
1087
1088
for (let i = childCount - 1; i >= 0; --i) {
1089
parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
1090
}
1091
}
1092
}
1093
1094
_forceRemove(currentNode);
1095
1096
return true;
1097
}
1098
/* Check whether element has a valid namespace */
1099
1100
1101
if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1102
_forceRemove(currentNode);
1103
1104
return true;
1105
}
1106
/* Make sure that older browsers don't get fallback-tag mXSS */
1107
1108
1109
if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1110
_forceRemove(currentNode);
1111
1112
return true;
1113
}
1114
/* Sanitize element content to be template-safe */
1115
1116
1117
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
1118
/* Get the element's text content */
1119
content = currentNode.textContent;
1120
arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1121
content = stringReplace(content, expr, ' ');
1122
});
1123
1124
if (currentNode.textContent !== content) {
1125
arrayPush(DOMPurify.removed, {
1126
element: currentNode.cloneNode()
1127
});
1128
currentNode.textContent = content;
1129
}
1130
}
1131
/* Execute a hook if present */
1132
1133
1134
_executeHook('afterSanitizeElements', currentNode, null);
1135
1136
return false;
1137
};
1138
/**
1139
* _isValidAttribute
1140
*
1141
* @param {string} lcTag Lowercase tag name of containing element.
1142
* @param {string} lcName Lowercase attribute name.
1143
* @param {string} value Attribute value.
1144
* @return {Boolean} Returns true if `value` is valid, otherwise false.
1145
*/
1146
// eslint-disable-next-line complexity
1147
1148
1149
const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1150
/* Make sure attribute cannot clobber */
1151
if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1152
return false;
1153
}
1154
/* Allow valid data-* attributes: At least one character after "-"
1155
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1156
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1157
We don't need to check the value; it's always URI safe. */
1158
1159
1160
if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
1161
if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1162
// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1163
// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1164
_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)) || // Alternative, second condition checks if it's an `is`-attribute, AND
1165
// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1166
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 {
1167
return false;
1168
}
1169
/* Check value is safe. First, is attr inert? If so, is safe */
1170
1171
} 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) {
1172
return false;
1173
} else ;
1174
1175
return true;
1176
};
1177
/**
1178
* _isBasicCustomElement
1179
* checks if at least one dash is included in tagName, and it's not the first char
1180
* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1181
*
1182
* @param {string} tagName name of the tag of the node to sanitize
1183
* @returns {boolean} Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1184
*/
1185
1186
1187
const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1188
return tagName.indexOf('-') > 0;
1189
};
1190
/**
1191
* _sanitizeAttributes
1192
*
1193
* @protect attributes
1194
* @protect nodeName
1195
* @protect removeAttribute
1196
* @protect setAttribute
1197
*
1198
* @param {Node} currentNode to sanitize
1199
*/
1200
1201
1202
const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1203
/* Execute a hook if present */
1204
_executeHook('beforeSanitizeAttributes', currentNode, null);
1205
1206
const {
1207
attributes
1208
} = currentNode;
1209
/* Check if we have attributes; if not we might have a text node */
1210
1211
if (!attributes) {
1212
return;
1213
}
1214
1215
const hookEvent = {
1216
attrName: '',
1217
attrValue: '',
1218
keepAttr: true,
1219
allowedAttributes: ALLOWED_ATTR
1220
};
1221
let l = attributes.length;
1222
/* Go backwards over all attributes; safely remove bad ones */
1223
1224
while (l--) {
1225
const attr = attributes[l];
1226
const {
1227
name,
1228
namespaceURI,
1229
value: attrValue
1230
} = attr;
1231
const lcName = transformCaseFunc(name);
1232
let value = name === 'value' ? attrValue : stringTrim(attrValue);
1233
/* Execute a hook if present */
1234
1235
hookEvent.attrName = lcName;
1236
hookEvent.attrValue = value;
1237
hookEvent.keepAttr = true;
1238
hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1239
1240
_executeHook('uponSanitizeAttribute', currentNode, hookEvent);
1241
1242
value = hookEvent.attrValue;
1243
/* Did the hooks approve of the attribute? */
1244
1245
if (hookEvent.forceKeepAttr) {
1246
continue;
1247
}
1248
/* Remove attribute */
1249
1250
1251
_removeAttribute(name, currentNode);
1252
/* Did the hooks approve of the attribute? */
1253
1254
1255
if (!hookEvent.keepAttr) {
1256
continue;
1257
}
1258
/* Work around a security issue in jQuery 3.0 */
1259
1260
1261
if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1262
_removeAttribute(name, currentNode);
1263
1264
continue;
1265
}
1266
/* Sanitize attribute content to be template-safe */
1267
1268
1269
if (SAFE_FOR_TEMPLATES) {
1270
arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1271
value = stringReplace(value, expr, ' ');
1272
});
1273
}
1274
/* Is `value` valid for this attribute? */
1275
1276
1277
const lcTag = transformCaseFunc(currentNode.nodeName);
1278
1279
if (!_isValidAttribute(lcTag, lcName, value)) {
1280
continue;
1281
}
1282
/* Full DOM Clobbering protection via namespace isolation,
1283
* Prefix id and name attributes with `user-content-`
1284
*/
1285
1286
1287
if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
1288
// Remove the attribute with this value
1289
_removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value
1290
1291
1292
value = SANITIZE_NAMED_PROPS_PREFIX + value;
1293
}
1294
/* Handle attributes that require Trusted Types */
1295
1296
1297
if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1298
if (namespaceURI) ; else {
1299
switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1300
case 'TrustedHTML':
1301
{
1302
value = trustedTypesPolicy.createHTML(value);
1303
break;
1304
}
1305
1306
case 'TrustedScriptURL':
1307
{
1308
value = trustedTypesPolicy.createScriptURL(value);
1309
break;
1310
}
1311
}
1312
}
1313
}
1314
/* Handle invalid data-* attribute set by try-catching it */
1315
1316
1317
try {
1318
if (namespaceURI) {
1319
currentNode.setAttributeNS(namespaceURI, name, value);
1320
} else {
1321
/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1322
currentNode.setAttribute(name, value);
1323
}
1324
1325
arrayPop(DOMPurify.removed);
1326
} catch (_) {}
1327
}
1328
/* Execute a hook if present */
1329
1330
1331
_executeHook('afterSanitizeAttributes', currentNode, null);
1332
};
1333
/**
1334
* _sanitizeShadowDOM
1335
*
1336
* @param {DocumentFragment} fragment to iterate over recursively
1337
*/
1338
1339
1340
const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
1341
let shadowNode = null;
1342
1343
const shadowIterator = _createNodeIterator(fragment);
1344
/* Execute a hook if present */
1345
1346
1347
_executeHook('beforeSanitizeShadowDOM', fragment, null);
1348
1349
while (shadowNode = shadowIterator.nextNode()) {
1350
/* Execute a hook if present */
1351
_executeHook('uponSanitizeShadowNode', shadowNode, null);
1352
/* Sanitize tags and elements */
1353
1354
1355
if (_sanitizeElements(shadowNode)) {
1356
continue;
1357
}
1358
/* Deep shadow DOM detected */
1359
1360
1361
if (shadowNode.content instanceof DocumentFragment) {
1362
_sanitizeShadowDOM(shadowNode.content);
1363
}
1364
/* Check attributes, sanitize if necessary */
1365
1366
1367
_sanitizeAttributes(shadowNode);
1368
}
1369
/* Execute a hook if present */
1370
1371
1372
_executeHook('afterSanitizeShadowDOM', fragment, null);
1373
};
1374
/**
1375
* Sanitize
1376
* Public method providing core sanitation functionality
1377
*
1378
* @param {String|Node} dirty string or DOM node
1379
* @param {Object} cfg object
1380
*/
1381
// eslint-disable-next-line complexity
1382
1383
1384
DOMPurify.sanitize = function (dirty) {
1385
let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1386
let body = null;
1387
let importedNode = null;
1388
let currentNode = null;
1389
let returnNode = null;
1390
/* Make sure we have a string to sanitize.
1391
DO NOT return early, as this will return the wrong type if
1392
the user has requested a DOM object rather than a string */
1393
1394
IS_EMPTY_INPUT = !dirty;
1395
1396
if (IS_EMPTY_INPUT) {
1397
dirty = '<!-->';
1398
}
1399
/* Stringify, in case dirty is an object */
1400
1401
1402
if (typeof dirty !== 'string' && !_isNode(dirty)) {
1403
if (typeof dirty.toString === 'function') {
1404
dirty = dirty.toString();
1405
1406
if (typeof dirty !== 'string') {
1407
throw typeErrorCreate('dirty is not a string, aborting');
1408
}
1409
} else {
1410
throw typeErrorCreate('toString is not a function');
1411
}
1412
}
1413
/* Return dirty HTML if DOMPurify cannot run */
1414
1415
1416
if (!DOMPurify.isSupported) {
1417
return dirty;
1418
}
1419
/* Assign config vars */
1420
1421
1422
if (!SET_CONFIG) {
1423
_parseConfig(cfg);
1424
}
1425
/* Clean up removed elements */
1426
1427
1428
DOMPurify.removed = [];
1429
/* Check if dirty is correctly typed for IN_PLACE */
1430
1431
if (typeof dirty === 'string') {
1432
IN_PLACE = false;
1433
}
1434
1435
if (IN_PLACE) {
1436
/* Do some early pre-sanitization to avoid unsafe root nodes */
1437
if (dirty.nodeName) {
1438
const tagName = transformCaseFunc(dirty.nodeName);
1439
1440
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1441
throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1442
}
1443
}
1444
} else if (dirty instanceof Node) {
1445
/* If dirty is a DOM element, append to an empty document to avoid
1446
elements being stripped by the parser */
1447
body = _initDocument('<!---->');
1448
importedNode = body.ownerDocument.importNode(dirty, true);
1449
1450
if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
1451
/* Node is already a body, use as is */
1452
body = importedNode;
1453
} else if (importedNode.nodeName === 'HTML') {
1454
body = importedNode;
1455
} else {
1456
// eslint-disable-next-line unicorn/prefer-dom-node-append
1457
body.appendChild(importedNode);
1458
}
1459
} else {
1460
/* Exit directly if we have nothing to do */
1461
if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
1462
dirty.indexOf('<') === -1) {
1463
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1464
}
1465
/* Initialize the document to work on */
1466
1467
1468
body = _initDocument(dirty);
1469
/* Check we have a DOM node from the data */
1470
1471
if (!body) {
1472
return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1473
}
1474
}
1475
/* Remove first element node (ours) if FORCE_BODY is set */
1476
1477
1478
if (body && FORCE_BODY) {
1479
_forceRemove(body.firstChild);
1480
}
1481
/* Get node iterator */
1482
1483
1484
const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1485
/* Now start iterating over the created document */
1486
1487
1488
while (currentNode = nodeIterator.nextNode()) {
1489
/* Sanitize tags and elements */
1490
if (_sanitizeElements(currentNode)) {
1491
continue;
1492
}
1493
/* Shadow DOM detected, sanitize it */
1494
1495
1496
if (currentNode.content instanceof DocumentFragment) {
1497
_sanitizeShadowDOM(currentNode.content);
1498
}
1499
/* Check attributes, sanitize if necessary */
1500
1501
1502
_sanitizeAttributes(currentNode);
1503
}
1504
/* If we sanitized `dirty` in-place, return it. */
1505
1506
1507
if (IN_PLACE) {
1508
return dirty;
1509
}
1510
/* Return sanitized string or DOM */
1511
1512
1513
if (RETURN_DOM) {
1514
if (RETURN_DOM_FRAGMENT) {
1515
returnNode = createDocumentFragment.call(body.ownerDocument);
1516
1517
while (body.firstChild) {
1518
// eslint-disable-next-line unicorn/prefer-dom-node-append
1519
returnNode.appendChild(body.firstChild);
1520
}
1521
} else {
1522
returnNode = body;
1523
}
1524
1525
if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1526
/*
1527
AdoptNode() is not used because internal state is not reset
1528
(e.g. the past names map of a HTMLFormElement), this is safe
1529
in theory but we would rather not risk another attack vector.
1530
The state that is cloned by importNode() is explicitly defined
1531
by the specs.
1532
*/
1533
returnNode = importNode.call(originalDocument, returnNode, true);
1534
}
1535
1536
return returnNode;
1537
}
1538
1539
let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1540
/* Serialize doctype if allowed */
1541
1542
if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1543
serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1544
}
1545
/* Sanitize final string template-safe */
1546
1547
1548
if (SAFE_FOR_TEMPLATES) {
1549
arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1550
serializedHTML = stringReplace(serializedHTML, expr, ' ');
1551
});
1552
}
1553
1554
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1555
};
1556
/**
1557
* Public method to set the configuration once
1558
* setConfig
1559
*
1560
* @param {Object} cfg configuration object
1561
*/
1562
1563
1564
DOMPurify.setConfig = function () {
1565
let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1566
1567
_parseConfig(cfg);
1568
1569
SET_CONFIG = true;
1570
};
1571
/**
1572
* Public method to remove the configuration
1573
* clearConfig
1574
*
1575
*/
1576
1577
1578
DOMPurify.clearConfig = function () {
1579
CONFIG = null;
1580
SET_CONFIG = false;
1581
};
1582
/**
1583
* Public method to check if an attribute value is valid.
1584
* Uses last set config, if any. Otherwise, uses config defaults.
1585
* isValidAttribute
1586
*
1587
* @param {String} tag Tag name of containing element.
1588
* @param {String} attr Attribute name.
1589
* @param {String} value Attribute value.
1590
* @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
1591
*/
1592
1593
1594
DOMPurify.isValidAttribute = function (tag, attr, value) {
1595
/* Initialize shared config vars if necessary. */
1596
if (!CONFIG) {
1597
_parseConfig({});
1598
}
1599
1600
const lcTag = transformCaseFunc(tag);
1601
const lcName = transformCaseFunc(attr);
1602
return _isValidAttribute(lcTag, lcName, value);
1603
};
1604
/**
1605
* AddHook
1606
* Public method to add DOMPurify hooks
1607
*
1608
* @param {String} entryPoint entry point for the hook to add
1609
* @param {Function} hookFunction function to execute
1610
*/
1611
1612
1613
DOMPurify.addHook = function (entryPoint, hookFunction) {
1614
if (typeof hookFunction !== 'function') {
1615
return;
1616
}
1617
1618
hooks[entryPoint] = hooks[entryPoint] || [];
1619
arrayPush(hooks[entryPoint], hookFunction);
1620
};
1621
/**
1622
* RemoveHook
1623
* Public method to remove a DOMPurify hook at a given entryPoint
1624
* (pops it from the stack of hooks if more are present)
1625
*
1626
* @param {String} entryPoint entry point for the hook to remove
1627
* @return {Function} removed(popped) hook
1628
*/
1629
1630
1631
DOMPurify.removeHook = function (entryPoint) {
1632
if (hooks[entryPoint]) {
1633
return arrayPop(hooks[entryPoint]);
1634
}
1635
};
1636
/**
1637
* RemoveHooks
1638
* Public method to remove all DOMPurify hooks at a given entryPoint
1639
*
1640
* @param {String} entryPoint entry point for the hooks to remove
1641
*/
1642
1643
1644
DOMPurify.removeHooks = function (entryPoint) {
1645
if (hooks[entryPoint]) {
1646
hooks[entryPoint] = [];
1647
}
1648
};
1649
/**
1650
* RemoveAllHooks
1651
* Public method to remove all DOMPurify hooks
1652
*/
1653
1654
1655
DOMPurify.removeAllHooks = function () {
1656
hooks = {};
1657
};
1658
1659
return DOMPurify;
1660
}
1661
1662
var purify = createDOMPurify();
1663
1664
export { purify as default };
1665
//# sourceMappingURL=purify.es.js.map
1666
1667