dompurify 3.4.1 → 3.4.2

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.
package/src/purify.ts ADDED
@@ -0,0 +1,2184 @@
1
+ /* eslint-disable @typescript-eslint/indent */
2
+
3
+ import type {
4
+ TrustedHTML,
5
+ TrustedTypesWindow,
6
+ } from 'trusted-types/lib/index.js';
7
+ import type { Config, UseProfilesConfig } from './config';
8
+ import * as TAGS from './tags.js';
9
+ import * as ATTRS from './attrs.js';
10
+ import * as EXPRESSIONS from './regexp.js';
11
+ import {
12
+ addToSet,
13
+ clone,
14
+ entries,
15
+ freeze,
16
+ arrayForEach,
17
+ arrayIsArray,
18
+ arrayLastIndexOf,
19
+ arrayPop,
20
+ arrayPush,
21
+ arraySplice,
22
+ stringMatch,
23
+ stringReplace,
24
+ stringToLowerCase,
25
+ stringToString,
26
+ stringIndexOf,
27
+ stringTrim,
28
+ regExpTest,
29
+ isRegex,
30
+ typeErrorCreate,
31
+ lookupGetter,
32
+ create,
33
+ objectHasOwnProperty,
34
+ stringifyValue,
35
+ } from './utils.js';
36
+
37
+ export type { Config } from './config';
38
+
39
+ declare const VERSION: string;
40
+
41
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
42
+ const NODE_TYPE = {
43
+ element: 1,
44
+ attribute: 2,
45
+ text: 3,
46
+ cdataSection: 4,
47
+ entityReference: 5, // Deprecated
48
+ entityNode: 6, // Deprecated
49
+ progressingInstruction: 7,
50
+ comment: 8,
51
+ document: 9,
52
+ documentType: 10,
53
+ documentFragment: 11,
54
+ notation: 12, // Deprecated
55
+ };
56
+
57
+ const getGlobal = function (): WindowLike {
58
+ return typeof window === 'undefined' ? null : window;
59
+ };
60
+
61
+ /**
62
+ * Creates a no-op policy for internal use only.
63
+ * Don't export this function outside this module!
64
+ * @param trustedTypes The policy factory.
65
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
66
+ * @return The policy created (or null, if Trusted Types
67
+ * are not supported or creating the policy failed).
68
+ */
69
+ const _createTrustedTypesPolicy = function (
70
+ trustedTypes: TrustedTypePolicyFactory,
71
+ purifyHostElement: HTMLScriptElement
72
+ ) {
73
+ if (
74
+ typeof trustedTypes !== 'object' ||
75
+ typeof trustedTypes.createPolicy !== 'function'
76
+ ) {
77
+ return null;
78
+ }
79
+
80
+ // Allow the callers to control the unique policy name
81
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
82
+ // Policy creation with duplicate names throws in Trusted Types.
83
+ let suffix = null;
84
+ const ATTR_NAME = 'data-tt-policy-suffix';
85
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
86
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
87
+ }
88
+
89
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
90
+
91
+ try {
92
+ return trustedTypes.createPolicy(policyName, {
93
+ createHTML(html) {
94
+ return html;
95
+ },
96
+ createScriptURL(scriptUrl) {
97
+ return scriptUrl;
98
+ },
99
+ });
100
+ } catch (_) {
101
+ // Policy creation failed (most likely another DOMPurify script has
102
+ // already run). Skip creating the policy, as this will only cause errors
103
+ // if TT are enforced.
104
+ console.warn(
105
+ 'TrustedTypes policy ' + policyName + ' could not be created.'
106
+ );
107
+ return null;
108
+ }
109
+ };
110
+
111
+ const _createHooksMap = function (): HooksMap {
112
+ return {
113
+ afterSanitizeAttributes: [],
114
+ afterSanitizeElements: [],
115
+ afterSanitizeShadowDOM: [],
116
+ beforeSanitizeAttributes: [],
117
+ beforeSanitizeElements: [],
118
+ beforeSanitizeShadowDOM: [],
119
+ uponSanitizeAttribute: [],
120
+ uponSanitizeElement: [],
121
+ uponSanitizeShadowNode: [],
122
+ };
123
+ };
124
+
125
+ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
126
+ const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);
127
+
128
+ DOMPurify.version = VERSION;
129
+
130
+ DOMPurify.removed = [];
131
+
132
+ if (
133
+ !window ||
134
+ !window.document ||
135
+ window.document.nodeType !== NODE_TYPE.document ||
136
+ !window.Element
137
+ ) {
138
+ // Not running in a browser, provide a factory function
139
+ // so that you can pass your own Window
140
+ DOMPurify.isSupported = false;
141
+
142
+ return DOMPurify;
143
+ }
144
+
145
+ let { document } = window;
146
+
147
+ const originalDocument = document;
148
+ const currentScript: HTMLScriptElement =
149
+ originalDocument.currentScript as HTMLScriptElement;
150
+ const {
151
+ DocumentFragment,
152
+ HTMLTemplateElement,
153
+ Node,
154
+ Element,
155
+ NodeFilter,
156
+ NamedNodeMap = window.NamedNodeMap || (window as any).MozNamedAttrMap,
157
+ HTMLFormElement,
158
+ DOMParser,
159
+ trustedTypes,
160
+ } = window;
161
+
162
+ const ElementPrototype = Element.prototype;
163
+
164
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
165
+ const remove = lookupGetter(ElementPrototype, 'remove');
166
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
167
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
168
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
169
+
170
+ // As per issue #47, the web-components registry is inherited by a
171
+ // new document created via createHTMLDocument. As per the spec
172
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
173
+ // a new empty registry is used when creating a template contents owner
174
+ // document, so we use that as our parent document to ensure nothing
175
+ // is inherited.
176
+ if (typeof HTMLTemplateElement === 'function') {
177
+ const template = document.createElement('template');
178
+ if (template.content && template.content.ownerDocument) {
179
+ document = template.content.ownerDocument;
180
+ }
181
+ }
182
+
183
+ let trustedTypesPolicy;
184
+ let emptyHTML = '';
185
+
186
+ const {
187
+ implementation,
188
+ createNodeIterator,
189
+ createDocumentFragment,
190
+ getElementsByTagName,
191
+ } = document;
192
+ const { importNode } = originalDocument;
193
+
194
+ let hooks = _createHooksMap();
195
+
196
+ /**
197
+ * Expose whether this browser supports running the full DOMPurify.
198
+ */
199
+ DOMPurify.isSupported =
200
+ typeof entries === 'function' &&
201
+ typeof getParentNode === 'function' &&
202
+ implementation &&
203
+ implementation.createHTMLDocument !== undefined;
204
+
205
+ const {
206
+ MUSTACHE_EXPR,
207
+ ERB_EXPR,
208
+ TMPLIT_EXPR,
209
+ DATA_ATTR,
210
+ ARIA_ATTR,
211
+ IS_SCRIPT_OR_DATA,
212
+ ATTR_WHITESPACE,
213
+ CUSTOM_ELEMENT,
214
+ } = EXPRESSIONS;
215
+
216
+ let { IS_ALLOWED_URI } = EXPRESSIONS;
217
+
218
+ /**
219
+ * We consider the elements and attributes below to be safe. Ideally
220
+ * don't add any new ones but feel free to remove unwanted ones.
221
+ */
222
+
223
+ /* allowed element names */
224
+ let ALLOWED_TAGS = null;
225
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [
226
+ ...TAGS.html,
227
+ ...TAGS.svg,
228
+ ...TAGS.svgFilters,
229
+ ...TAGS.mathMl,
230
+ ...TAGS.text,
231
+ ]);
232
+
233
+ /* Allowed attribute names */
234
+ let ALLOWED_ATTR = null;
235
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [
236
+ ...ATTRS.html,
237
+ ...ATTRS.svg,
238
+ ...ATTRS.mathMl,
239
+ ...ATTRS.xml,
240
+ ]);
241
+
242
+ /*
243
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
244
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
245
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
246
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
247
+ */
248
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(
249
+ create(null, {
250
+ tagNameCheck: {
251
+ writable: true,
252
+ configurable: false,
253
+ enumerable: true,
254
+ value: null,
255
+ },
256
+ attributeNameCheck: {
257
+ writable: true,
258
+ configurable: false,
259
+ enumerable: true,
260
+ value: null,
261
+ },
262
+ allowCustomizedBuiltInElements: {
263
+ writable: true,
264
+ configurable: false,
265
+ enumerable: true,
266
+ value: false,
267
+ },
268
+ })
269
+ );
270
+
271
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
272
+ let FORBID_TAGS = null;
273
+
274
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
275
+ let FORBID_ATTR = null;
276
+
277
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
278
+ const EXTRA_ELEMENT_HANDLING = Object.seal(
279
+ create(null, {
280
+ tagCheck: {
281
+ writable: true,
282
+ configurable: false,
283
+ enumerable: true,
284
+ value: null,
285
+ },
286
+ attributeCheck: {
287
+ writable: true,
288
+ configurable: false,
289
+ enumerable: true,
290
+ value: null,
291
+ },
292
+ })
293
+ );
294
+
295
+ /* Decide if ARIA attributes are okay */
296
+ let ALLOW_ARIA_ATTR = true;
297
+
298
+ /* Decide if custom data attributes are okay */
299
+ let ALLOW_DATA_ATTR = true;
300
+
301
+ /* Decide if unknown protocols are okay */
302
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
303
+
304
+ /* Decide if self-closing tags in attributes are allowed.
305
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
306
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
307
+
308
+ /* Output should be safe for common template engines.
309
+ * This means, DOMPurify removes data attributes, mustaches and ERB
310
+ */
311
+ let SAFE_FOR_TEMPLATES = false;
312
+
313
+ /* Output should be safe even for XML used within HTML and alike.
314
+ * This means, DOMPurify removes comments when containing risky content.
315
+ */
316
+ let SAFE_FOR_XML = true;
317
+
318
+ /* Decide if document with <html>... should be returned */
319
+ let WHOLE_DOCUMENT = false;
320
+
321
+ /* Track whether config is already set on this instance of DOMPurify. */
322
+ let SET_CONFIG = false;
323
+
324
+ /* Decide if all elements (e.g. style, script) must be children of
325
+ * document.body. By default, browsers might move them to document.head */
326
+ let FORCE_BODY = false;
327
+
328
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
329
+ * string (or a TrustedHTML object if Trusted Types are supported).
330
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
331
+ */
332
+ let RETURN_DOM = false;
333
+
334
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
335
+ * string (or a TrustedHTML object if Trusted Types are supported) */
336
+ let RETURN_DOM_FRAGMENT = false;
337
+
338
+ /* Try to return a Trusted Type object instead of a string, return a string in
339
+ * case Trusted Types are not supported */
340
+ let RETURN_TRUSTED_TYPE = false;
341
+
342
+ /* Output should be free from DOM clobbering attacks?
343
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
344
+ */
345
+ let SANITIZE_DOM = true;
346
+
347
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
348
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
349
+ *
350
+ * HTML/DOM spec rules that enable DOM Clobbering:
351
+ * - Named Access on Window (§7.3.3)
352
+ * - DOM Tree Accessors (§3.1.5)
353
+ * - Form Element Parent-Child Relations (§4.10.3)
354
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
355
+ * - HTMLCollection (§4.2.10.2)
356
+ *
357
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
358
+ * with a constant string, i.e., `user-content-`
359
+ */
360
+ let SANITIZE_NAMED_PROPS = false;
361
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
362
+
363
+ /* Keep element content when removing element? */
364
+ let KEEP_CONTENT = true;
365
+
366
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
367
+ * of importing it into a new Document and returning a sanitized copy */
368
+ let IN_PLACE = false;
369
+
370
+ /* Allow usage of profiles like html, svg and mathMl */
371
+ let USE_PROFILES: UseProfilesConfig | false = {};
372
+
373
+ /* Tags to ignore content of when KEEP_CONTENT is true */
374
+ let FORBID_CONTENTS = null;
375
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, [
376
+ 'annotation-xml',
377
+ 'audio',
378
+ 'colgroup',
379
+ 'desc',
380
+ 'foreignobject',
381
+ 'head',
382
+ 'iframe',
383
+ 'math',
384
+ 'mi',
385
+ 'mn',
386
+ 'mo',
387
+ 'ms',
388
+ 'mtext',
389
+ 'noembed',
390
+ 'noframes',
391
+ 'noscript',
392
+ 'plaintext',
393
+ 'script',
394
+ 'style',
395
+ 'svg',
396
+ 'template',
397
+ 'thead',
398
+ 'title',
399
+ 'video',
400
+ 'xmp',
401
+ ]);
402
+
403
+ /* Tags that are safe for data: URIs */
404
+ let DATA_URI_TAGS = null;
405
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, [
406
+ 'audio',
407
+ 'video',
408
+ 'img',
409
+ 'source',
410
+ 'image',
411
+ 'track',
412
+ ]);
413
+
414
+ /* Attributes safe for values like "javascript:" */
415
+ let URI_SAFE_ATTRIBUTES = null;
416
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [
417
+ 'alt',
418
+ 'class',
419
+ 'for',
420
+ 'id',
421
+ 'label',
422
+ 'name',
423
+ 'pattern',
424
+ 'placeholder',
425
+ 'role',
426
+ 'summary',
427
+ 'title',
428
+ 'value',
429
+ 'style',
430
+ 'xmlns',
431
+ ]);
432
+
433
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
434
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
435
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
436
+ /* Document namespace */
437
+ let NAMESPACE = HTML_NAMESPACE;
438
+ let IS_EMPTY_INPUT = false;
439
+
440
+ /* Allowed XHTML+XML namespaces */
441
+ let ALLOWED_NAMESPACES = null;
442
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet(
443
+ {},
444
+ [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE],
445
+ stringToString
446
+ );
447
+
448
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [
449
+ 'mi',
450
+ 'mo',
451
+ 'mn',
452
+ 'ms',
453
+ 'mtext',
454
+ ]);
455
+
456
+ let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
457
+
458
+ // Certain elements are allowed in both SVG and HTML
459
+ // namespace. We need to specify them explicitly
460
+ // so that they don't get erroneously deleted from
461
+ // HTML namespace.
462
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
463
+ 'title',
464
+ 'style',
465
+ 'font',
466
+ 'a',
467
+ 'script',
468
+ ]);
469
+
470
+ /* Parsing of strict XHTML documents */
471
+ let PARSER_MEDIA_TYPE: null | DOMParserSupportedType = null;
472
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
473
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
474
+ let transformCaseFunc: null | Parameters<typeof addToSet>[2] = null;
475
+
476
+ /* Keep a reference to config to pass to hooks */
477
+ let CONFIG: Config | null = null;
478
+
479
+ /* Ideally, do not touch anything below this line */
480
+ /* ______________________________________________ */
481
+
482
+ const formElement = document.createElement('form');
483
+
484
+ const isRegexOrFunction = function (
485
+ testValue: unknown
486
+ ): testValue is Function | RegExp {
487
+ return testValue instanceof RegExp || testValue instanceof Function;
488
+ };
489
+
490
+ /**
491
+ * _parseConfig
492
+ *
493
+ * @param cfg optional config literal
494
+ */
495
+ // eslint-disable-next-line complexity
496
+ const _parseConfig = function (cfg: Config = {}): void {
497
+ if (CONFIG && CONFIG === cfg) {
498
+ return;
499
+ }
500
+
501
+ /* Shield configuration object from tampering */
502
+ if (!cfg || typeof cfg !== 'object') {
503
+ cfg = {};
504
+ }
505
+
506
+ /* Shield configuration object from prototype pollution */
507
+ cfg = clone(cfg);
508
+
509
+ PARSER_MEDIA_TYPE =
510
+ // eslint-disable-next-line unicorn/prefer-includes
511
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1
512
+ ? DEFAULT_PARSER_MEDIA_TYPE
513
+ : cfg.PARSER_MEDIA_TYPE;
514
+
515
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
516
+ transformCaseFunc =
517
+ PARSER_MEDIA_TYPE === 'application/xhtml+xml'
518
+ ? stringToString
519
+ : stringToLowerCase;
520
+
521
+ /* Set configuration parameters */
522
+ ALLOWED_TAGS =
523
+ objectHasOwnProperty(cfg, 'ALLOWED_TAGS') &&
524
+ arrayIsArray(cfg.ALLOWED_TAGS)
525
+ ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc)
526
+ : DEFAULT_ALLOWED_TAGS;
527
+ ALLOWED_ATTR =
528
+ objectHasOwnProperty(cfg, 'ALLOWED_ATTR') &&
529
+ arrayIsArray(cfg.ALLOWED_ATTR)
530
+ ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc)
531
+ : DEFAULT_ALLOWED_ATTR;
532
+ ALLOWED_NAMESPACES =
533
+ objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') &&
534
+ arrayIsArray(cfg.ALLOWED_NAMESPACES)
535
+ ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString)
536
+ : DEFAULT_ALLOWED_NAMESPACES;
537
+ URI_SAFE_ATTRIBUTES =
538
+ objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') &&
539
+ arrayIsArray(cfg.ADD_URI_SAFE_ATTR)
540
+ ? addToSet(
541
+ clone(DEFAULT_URI_SAFE_ATTRIBUTES),
542
+ cfg.ADD_URI_SAFE_ATTR,
543
+ transformCaseFunc
544
+ )
545
+ : DEFAULT_URI_SAFE_ATTRIBUTES;
546
+ DATA_URI_TAGS =
547
+ objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') &&
548
+ arrayIsArray(cfg.ADD_DATA_URI_TAGS)
549
+ ? addToSet(
550
+ clone(DEFAULT_DATA_URI_TAGS),
551
+ cfg.ADD_DATA_URI_TAGS,
552
+ transformCaseFunc
553
+ )
554
+ : DEFAULT_DATA_URI_TAGS;
555
+ FORBID_CONTENTS =
556
+ objectHasOwnProperty(cfg, 'FORBID_CONTENTS') &&
557
+ arrayIsArray(cfg.FORBID_CONTENTS)
558
+ ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc)
559
+ : DEFAULT_FORBID_CONTENTS;
560
+ FORBID_TAGS =
561
+ objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS)
562
+ ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc)
563
+ : clone({});
564
+ FORBID_ATTR =
565
+ objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR)
566
+ ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc)
567
+ : clone({});
568
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES')
569
+ ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object'
570
+ ? clone(cfg.USE_PROFILES)
571
+ : cfg.USE_PROFILES
572
+ : false;
573
+
574
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
575
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
576
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
577
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
578
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
579
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
580
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
581
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
582
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
583
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
584
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
585
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
586
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
587
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
588
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
589
+ IS_ALLOWED_URI = isRegex(cfg.ALLOWED_URI_REGEXP)
590
+ ? cfg.ALLOWED_URI_REGEXP
591
+ : EXPRESSIONS.IS_ALLOWED_URI; // Default regexp
592
+
593
+ NAMESPACE =
594
+ typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
595
+
596
+ MATHML_TEXT_INTEGRATION_POINTS =
597
+ objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') &&
598
+ cfg.MATHML_TEXT_INTEGRATION_POINTS &&
599
+ typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object'
600
+ ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS)
601
+ : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
602
+
603
+ HTML_INTEGRATION_POINTS =
604
+ objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') &&
605
+ cfg.HTML_INTEGRATION_POINTS &&
606
+ typeof cfg.HTML_INTEGRATION_POINTS === 'object'
607
+ ? clone(cfg.HTML_INTEGRATION_POINTS)
608
+ : addToSet({}, ['annotation-xml']); // Default built-in map
609
+
610
+ const customElementHandling =
611
+ objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') &&
612
+ cfg.CUSTOM_ELEMENT_HANDLING &&
613
+ typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object'
614
+ ? clone(cfg.CUSTOM_ELEMENT_HANDLING)
615
+ : create(null);
616
+
617
+ CUSTOM_ELEMENT_HANDLING = create(null);
618
+
619
+ if (
620
+ objectHasOwnProperty(customElementHandling, 'tagNameCheck') &&
621
+ isRegexOrFunction(customElementHandling.tagNameCheck)
622
+ ) {
623
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
624
+ }
625
+
626
+ if (
627
+ objectHasOwnProperty(customElementHandling, 'attributeNameCheck') &&
628
+ isRegexOrFunction(customElementHandling.attributeNameCheck)
629
+ ) {
630
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck =
631
+ customElementHandling.attributeNameCheck; // Default undefined
632
+ }
633
+
634
+ if (
635
+ objectHasOwnProperty(
636
+ customElementHandling,
637
+ 'allowCustomizedBuiltInElements'
638
+ ) &&
639
+ typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean'
640
+ ) {
641
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements =
642
+ customElementHandling.allowCustomizedBuiltInElements; // Default undefined
643
+ }
644
+
645
+ if (SAFE_FOR_TEMPLATES) {
646
+ ALLOW_DATA_ATTR = false;
647
+ }
648
+
649
+ if (RETURN_DOM_FRAGMENT) {
650
+ RETURN_DOM = true;
651
+ }
652
+
653
+ /* Parse profile info */
654
+ if (USE_PROFILES) {
655
+ ALLOWED_TAGS = addToSet({}, TAGS.text);
656
+ ALLOWED_ATTR = create(null);
657
+ if (USE_PROFILES.html === true) {
658
+ addToSet(ALLOWED_TAGS, TAGS.html);
659
+ addToSet(ALLOWED_ATTR, ATTRS.html);
660
+ }
661
+
662
+ if (USE_PROFILES.svg === true) {
663
+ addToSet(ALLOWED_TAGS, TAGS.svg);
664
+ addToSet(ALLOWED_ATTR, ATTRS.svg);
665
+ addToSet(ALLOWED_ATTR, ATTRS.xml);
666
+ }
667
+
668
+ if (USE_PROFILES.svgFilters === true) {
669
+ addToSet(ALLOWED_TAGS, TAGS.svgFilters);
670
+ addToSet(ALLOWED_ATTR, ATTRS.svg);
671
+ addToSet(ALLOWED_ATTR, ATTRS.xml);
672
+ }
673
+
674
+ if (USE_PROFILES.mathMl === true) {
675
+ addToSet(ALLOWED_TAGS, TAGS.mathMl);
676
+ addToSet(ALLOWED_ATTR, ATTRS.mathMl);
677
+ addToSet(ALLOWED_ATTR, ATTRS.xml);
678
+ }
679
+ }
680
+
681
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
682
+ * leaking across calls when switching from function to array config */
683
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
684
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
685
+
686
+ /* Merge configuration parameters */
687
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
688
+ if (typeof cfg.ADD_TAGS === 'function') {
689
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
690
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
691
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
692
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
693
+ }
694
+
695
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
696
+ }
697
+ }
698
+
699
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
700
+ if (typeof cfg.ADD_ATTR === 'function') {
701
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
702
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
703
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
704
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
705
+ }
706
+
707
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
708
+ }
709
+ }
710
+
711
+ if (
712
+ objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') &&
713
+ arrayIsArray(cfg.ADD_URI_SAFE_ATTR)
714
+ ) {
715
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
716
+ }
717
+
718
+ if (
719
+ objectHasOwnProperty(cfg, 'FORBID_CONTENTS') &&
720
+ arrayIsArray(cfg.FORBID_CONTENTS)
721
+ ) {
722
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
723
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
724
+ }
725
+
726
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
727
+ }
728
+
729
+ if (
730
+ objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') &&
731
+ arrayIsArray(cfg.ADD_FORBID_CONTENTS)
732
+ ) {
733
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
734
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
735
+ }
736
+
737
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
738
+ }
739
+
740
+ /* Add #text in case KEEP_CONTENT is set to true */
741
+ if (KEEP_CONTENT) {
742
+ ALLOWED_TAGS['#text'] = true;
743
+ }
744
+
745
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
746
+ if (WHOLE_DOCUMENT) {
747
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
748
+ }
749
+
750
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
751
+ if (ALLOWED_TAGS.table) {
752
+ addToSet(ALLOWED_TAGS, ['tbody']);
753
+ delete FORBID_TAGS.tbody;
754
+ }
755
+
756
+ if (cfg.TRUSTED_TYPES_POLICY) {
757
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
758
+ throw typeErrorCreate(
759
+ 'TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'
760
+ );
761
+ }
762
+
763
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
764
+ throw typeErrorCreate(
765
+ 'TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'
766
+ );
767
+ }
768
+
769
+ // Overwrite existing TrustedTypes policy.
770
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
771
+
772
+ // Sign local variables required by `sanitize`.
773
+ emptyHTML = trustedTypesPolicy.createHTML('');
774
+ } else {
775
+ // Uninitialized policy, attempt to initialize the internal dompurify policy.
776
+ if (trustedTypesPolicy === undefined) {
777
+ trustedTypesPolicy = _createTrustedTypesPolicy(
778
+ trustedTypes,
779
+ currentScript
780
+ );
781
+ }
782
+
783
+ // If creating the internal policy succeeded sign internal variables.
784
+ if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
785
+ emptyHTML = trustedTypesPolicy.createHTML('');
786
+ }
787
+ }
788
+
789
+ // Prevent further manipulation of configuration.
790
+ // Not available in IE8, Safari 5, etc.
791
+ if (freeze) {
792
+ freeze(cfg);
793
+ }
794
+
795
+ CONFIG = cfg;
796
+ };
797
+
798
+ /* Keep track of all possible SVG and MathML tags
799
+ * so that we can perform the namespace checks
800
+ * correctly. */
801
+ const ALL_SVG_TAGS = addToSet({}, [
802
+ ...TAGS.svg,
803
+ ...TAGS.svgFilters,
804
+ ...TAGS.svgDisallowed,
805
+ ]);
806
+ const ALL_MATHML_TAGS = addToSet({}, [
807
+ ...TAGS.mathMl,
808
+ ...TAGS.mathMlDisallowed,
809
+ ]);
810
+
811
+ /**
812
+ * @param element a DOM element whose namespace is being checked
813
+ * @returns Return false if the element has a
814
+ * namespace that a spec-compliant parser would never
815
+ * return. Return true otherwise.
816
+ */
817
+ const _checkValidNamespace = function (element: Element): boolean {
818
+ let parent = getParentNode(element);
819
+
820
+ // In JSDOM, if we're inside shadow DOM, then parentNode
821
+ // can be null. We just simulate parent in this case.
822
+ if (!parent || !parent.tagName) {
823
+ parent = {
824
+ namespaceURI: NAMESPACE,
825
+ tagName: 'template',
826
+ };
827
+ }
828
+
829
+ const tagName = stringToLowerCase(element.tagName);
830
+ const parentTagName = stringToLowerCase(parent.tagName);
831
+
832
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
833
+ return false;
834
+ }
835
+
836
+ if (element.namespaceURI === SVG_NAMESPACE) {
837
+ // The only way to switch from HTML namespace to SVG
838
+ // is via <svg>. If it happens via any other tag, then
839
+ // it should be killed.
840
+ if (parent.namespaceURI === HTML_NAMESPACE) {
841
+ return tagName === 'svg';
842
+ }
843
+
844
+ // The only way to switch from MathML to SVG is via`
845
+ // svg if parent is either <annotation-xml> or MathML
846
+ // text integration points.
847
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
848
+ return (
849
+ tagName === 'svg' &&
850
+ (parentTagName === 'annotation-xml' ||
851
+ MATHML_TEXT_INTEGRATION_POINTS[parentTagName])
852
+ );
853
+ }
854
+
855
+ // We only allow elements that are defined in SVG
856
+ // spec. All others are disallowed in SVG namespace.
857
+ return Boolean(ALL_SVG_TAGS[tagName]);
858
+ }
859
+
860
+ if (element.namespaceURI === MATHML_NAMESPACE) {
861
+ // The only way to switch from HTML namespace to MathML
862
+ // is via <math>. If it happens via any other tag, then
863
+ // it should be killed.
864
+ if (parent.namespaceURI === HTML_NAMESPACE) {
865
+ return tagName === 'math';
866
+ }
867
+
868
+ // The only way to switch from SVG to MathML is via
869
+ // <math> and HTML integration points
870
+ if (parent.namespaceURI === SVG_NAMESPACE) {
871
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
872
+ }
873
+
874
+ // We only allow elements that are defined in MathML
875
+ // spec. All others are disallowed in MathML namespace.
876
+ return Boolean(ALL_MATHML_TAGS[tagName]);
877
+ }
878
+
879
+ if (element.namespaceURI === HTML_NAMESPACE) {
880
+ // The only way to switch from SVG to HTML is via
881
+ // HTML integration points, and from MathML to HTML
882
+ // is via MathML text integration points
883
+ if (
884
+ parent.namespaceURI === SVG_NAMESPACE &&
885
+ !HTML_INTEGRATION_POINTS[parentTagName]
886
+ ) {
887
+ return false;
888
+ }
889
+
890
+ if (
891
+ parent.namespaceURI === MATHML_NAMESPACE &&
892
+ !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]
893
+ ) {
894
+ return false;
895
+ }
896
+
897
+ // We disallow tags that are specific for MathML
898
+ // or SVG and should never appear in HTML namespace
899
+ return (
900
+ !ALL_MATHML_TAGS[tagName] &&
901
+ (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName])
902
+ );
903
+ }
904
+
905
+ // For XHTML and XML documents that support custom namespaces
906
+ if (
907
+ PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&
908
+ ALLOWED_NAMESPACES[element.namespaceURI]
909
+ ) {
910
+ return true;
911
+ }
912
+
913
+ // The code should never reach this place (this means
914
+ // that the element somehow got namespace that is not
915
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
916
+ // Return false just in case.
917
+ return false;
918
+ };
919
+
920
+ /**
921
+ * _forceRemove
922
+ *
923
+ * @param node a DOM node
924
+ */
925
+ const _forceRemove = function (node: Node): void {
926
+ arrayPush(DOMPurify.removed, { element: node });
927
+
928
+ try {
929
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
930
+ getParentNode(node).removeChild(node);
931
+ } catch (_) {
932
+ remove(node);
933
+ }
934
+ };
935
+
936
+ /**
937
+ * _removeAttribute
938
+ *
939
+ * @param name an Attribute name
940
+ * @param element a DOM node
941
+ */
942
+ const _removeAttribute = function (name: string, element: Element): void {
943
+ try {
944
+ arrayPush(DOMPurify.removed, {
945
+ attribute: element.getAttributeNode(name),
946
+ from: element,
947
+ });
948
+ } catch (_) {
949
+ arrayPush(DOMPurify.removed, {
950
+ attribute: null,
951
+ from: element,
952
+ });
953
+ }
954
+
955
+ element.removeAttribute(name);
956
+
957
+ // We void attribute values for unremovable "is" attributes
958
+ if (name === 'is') {
959
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
960
+ try {
961
+ _forceRemove(element);
962
+ } catch (_) {}
963
+ } else {
964
+ try {
965
+ element.setAttribute(name, '');
966
+ } catch (_) {}
967
+ }
968
+ }
969
+ };
970
+
971
+ /**
972
+ * _initDocument
973
+ *
974
+ * @param dirty - a string of dirty markup
975
+ * @return a DOM, filled with the dirty markup
976
+ */
977
+ const _initDocument = function (dirty: string): Document {
978
+ /* Create a HTML document */
979
+ let doc = null;
980
+ let leadingWhitespace = null;
981
+
982
+ if (FORCE_BODY) {
983
+ dirty = '<remove></remove>' + dirty;
984
+ } else {
985
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
986
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
987
+ leadingWhitespace = matches && matches[0];
988
+ }
989
+
990
+ if (
991
+ PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&
992
+ NAMESPACE === HTML_NAMESPACE
993
+ ) {
994
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
995
+ dirty =
996
+ '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' +
997
+ dirty +
998
+ '</body></html>';
999
+ }
1000
+
1001
+ const dirtyPayload = trustedTypesPolicy
1002
+ ? trustedTypesPolicy.createHTML(dirty)
1003
+ : dirty;
1004
+ /*
1005
+ * Use the DOMParser API by default, fallback later if needs be
1006
+ * DOMParser not work for svg when has multiple root element.
1007
+ */
1008
+ if (NAMESPACE === HTML_NAMESPACE) {
1009
+ try {
1010
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
1011
+ } catch (_) {}
1012
+ }
1013
+
1014
+ /* Use createHTMLDocument in case DOMParser is not available */
1015
+ if (!doc || !doc.documentElement) {
1016
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
1017
+ try {
1018
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT
1019
+ ? emptyHTML
1020
+ : dirtyPayload;
1021
+ } catch (_) {
1022
+ // Syntax error if dirtyPayload is invalid xml
1023
+ }
1024
+ }
1025
+
1026
+ const body = doc.body || doc.documentElement;
1027
+
1028
+ if (dirty && leadingWhitespace) {
1029
+ body.insertBefore(
1030
+ document.createTextNode(leadingWhitespace),
1031
+ body.childNodes[0] || null
1032
+ );
1033
+ }
1034
+
1035
+ /* Work on whole document or just its body */
1036
+ if (NAMESPACE === HTML_NAMESPACE) {
1037
+ return getElementsByTagName.call(
1038
+ doc,
1039
+ WHOLE_DOCUMENT ? 'html' : 'body'
1040
+ )[0];
1041
+ }
1042
+
1043
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
1044
+ };
1045
+
1046
+ /**
1047
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
1048
+ *
1049
+ * @param root The root element or node to start traversing on.
1050
+ * @return The created NodeIterator
1051
+ */
1052
+ const _createNodeIterator = function (root: Node): NodeIterator {
1053
+ return createNodeIterator.call(
1054
+ root.ownerDocument || root,
1055
+ root,
1056
+ // eslint-disable-next-line no-bitwise
1057
+ NodeFilter.SHOW_ELEMENT |
1058
+ NodeFilter.SHOW_COMMENT |
1059
+ NodeFilter.SHOW_TEXT |
1060
+ NodeFilter.SHOW_PROCESSING_INSTRUCTION |
1061
+ NodeFilter.SHOW_CDATA_SECTION,
1062
+ null
1063
+ );
1064
+ };
1065
+
1066
+ /**
1067
+ * _isClobbered
1068
+ *
1069
+ * @param element element to check for clobbering attacks
1070
+ * @return true if clobbered, false if safe
1071
+ */
1072
+ const _isClobbered = function (element: Element): boolean {
1073
+ return (
1074
+ element instanceof HTMLFormElement &&
1075
+ (typeof element.nodeName !== 'string' ||
1076
+ typeof element.textContent !== 'string' ||
1077
+ typeof element.removeChild !== 'function' ||
1078
+ !(element.attributes instanceof NamedNodeMap) ||
1079
+ typeof element.removeAttribute !== 'function' ||
1080
+ typeof element.setAttribute !== 'function' ||
1081
+ typeof element.namespaceURI !== 'string' ||
1082
+ typeof element.insertBefore !== 'function' ||
1083
+ typeof element.hasChildNodes !== 'function')
1084
+ );
1085
+ };
1086
+
1087
+ /**
1088
+ * Checks whether the given object is a DOM node.
1089
+ *
1090
+ * @param value object to check whether it's a DOM node
1091
+ * @return true is object is a DOM node
1092
+ */
1093
+ const _isNode = function (value: unknown): value is Node {
1094
+ return typeof Node === 'function' && value instanceof Node;
1095
+ };
1096
+
1097
+ function _executeHooks<T extends HookFunction>(
1098
+ hooks: HookFunction[],
1099
+ currentNode: Parameters<T>[0],
1100
+ data: Parameters<T>[1]
1101
+ ): void {
1102
+ arrayForEach(hooks, (hook: T) => {
1103
+ hook.call(DOMPurify, currentNode, data, CONFIG);
1104
+ });
1105
+ }
1106
+
1107
+ /**
1108
+ * _sanitizeElements
1109
+ *
1110
+ * @protect nodeName
1111
+ * @protect textContent
1112
+ * @protect removeChild
1113
+ * @param currentNode to check for permission to exist
1114
+ * @return true if node was killed, false if left alive
1115
+ */
1116
+ const _sanitizeElements = function (currentNode: any): boolean {
1117
+ let content = null;
1118
+
1119
+ /* Execute a hook if present */
1120
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1121
+
1122
+ /* Check if element is clobbered or can clobber */
1123
+ if (_isClobbered(currentNode)) {
1124
+ _forceRemove(currentNode);
1125
+ return true;
1126
+ }
1127
+
1128
+ /* Now let's check the element's type and name */
1129
+ const tagName = transformCaseFunc(currentNode.nodeName);
1130
+
1131
+ /* Execute a hook if present */
1132
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
1133
+ tagName,
1134
+ allowedTags: ALLOWED_TAGS,
1135
+ });
1136
+
1137
+ /* Detect mXSS attempts abusing namespace confusion */
1138
+ if (
1139
+ SAFE_FOR_XML &&
1140
+ currentNode.hasChildNodes() &&
1141
+ !_isNode(currentNode.firstElementChild) &&
1142
+ regExpTest(/<[/\w!]/g, currentNode.innerHTML) &&
1143
+ regExpTest(/<[/\w!]/g, currentNode.textContent)
1144
+ ) {
1145
+ _forceRemove(currentNode);
1146
+ return true;
1147
+ }
1148
+
1149
+ /* Remove risky CSS construction leading to mXSS */
1150
+ if (
1151
+ SAFE_FOR_XML &&
1152
+ currentNode.namespaceURI === HTML_NAMESPACE &&
1153
+ tagName === 'style' &&
1154
+ _isNode(currentNode.firstElementChild)
1155
+ ) {
1156
+ _forceRemove(currentNode);
1157
+ return true;
1158
+ }
1159
+
1160
+ /* Remove any occurrence of processing instructions */
1161
+ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1162
+ _forceRemove(currentNode);
1163
+ return true;
1164
+ }
1165
+
1166
+ /* Remove any kind of possibly harmful comments */
1167
+ if (
1168
+ SAFE_FOR_XML &&
1169
+ currentNode.nodeType === NODE_TYPE.comment &&
1170
+ regExpTest(/<[/\w]/g, currentNode.data)
1171
+ ) {
1172
+ _forceRemove(currentNode);
1173
+ return true;
1174
+ }
1175
+
1176
+ /* Remove element if anything forbids its presence */
1177
+ if (
1178
+ FORBID_TAGS[tagName] ||
1179
+ (!(
1180
+ EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function &&
1181
+ EXTRA_ELEMENT_HANDLING.tagCheck(tagName)
1182
+ ) &&
1183
+ !ALLOWED_TAGS[tagName])
1184
+ ) {
1185
+ /* Check if we have a custom element to handle */
1186
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1187
+ if (
1188
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&
1189
+ regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)
1190
+ ) {
1191
+ return false;
1192
+ }
1193
+
1194
+ if (
1195
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&
1196
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)
1197
+ ) {
1198
+ return false;
1199
+ }
1200
+ }
1201
+
1202
+ /* Keep content except for bad-listed elements */
1203
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1204
+ const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1205
+ const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1206
+
1207
+ if (childNodes && parentNode) {
1208
+ const childCount = childNodes.length;
1209
+
1210
+ for (let i = childCount - 1; i >= 0; --i) {
1211
+ const childClone = cloneNode(childNodes[i], true);
1212
+ parentNode.insertBefore(childClone, getNextSibling(currentNode));
1213
+ }
1214
+ }
1215
+ }
1216
+
1217
+ _forceRemove(currentNode);
1218
+ return true;
1219
+ }
1220
+
1221
+ /* Check whether element has a valid namespace */
1222
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1223
+ _forceRemove(currentNode);
1224
+ return true;
1225
+ }
1226
+
1227
+ /* Make sure that older browsers don't get fallback-tag mXSS */
1228
+ if (
1229
+ (tagName === 'noscript' ||
1230
+ tagName === 'noembed' ||
1231
+ tagName === 'noframes') &&
1232
+ regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)
1233
+ ) {
1234
+ _forceRemove(currentNode);
1235
+ return true;
1236
+ }
1237
+
1238
+ /* Sanitize element content to be template-safe */
1239
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1240
+ /* Get the element's text content */
1241
+ content = currentNode.textContent;
1242
+
1243
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {
1244
+ content = stringReplace(content, expr, ' ');
1245
+ });
1246
+
1247
+ if (currentNode.textContent !== content) {
1248
+ arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
1249
+ currentNode.textContent = content;
1250
+ }
1251
+ }
1252
+
1253
+ /* Execute a hook if present */
1254
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1255
+
1256
+ return false;
1257
+ };
1258
+
1259
+ /**
1260
+ * _isValidAttribute
1261
+ *
1262
+ * @param lcTag Lowercase tag name of containing element.
1263
+ * @param lcName Lowercase attribute name.
1264
+ * @param value Attribute value.
1265
+ * @return Returns true if `value` is valid, otherwise false.
1266
+ */
1267
+ // eslint-disable-next-line complexity
1268
+ const _isValidAttribute = function (
1269
+ lcTag: string,
1270
+ lcName: string,
1271
+ value: string
1272
+ ): boolean {
1273
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1274
+ if (FORBID_ATTR[lcName]) {
1275
+ return false;
1276
+ }
1277
+
1278
+ /* Make sure attribute cannot clobber */
1279
+ if (
1280
+ SANITIZE_DOM &&
1281
+ (lcName === 'id' || lcName === 'name') &&
1282
+ (value in document || value in formElement)
1283
+ ) {
1284
+ return false;
1285
+ }
1286
+
1287
+ const nameIsPermitted =
1288
+ ALLOWED_ATTR[lcName] ||
1289
+ (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function &&
1290
+ EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag));
1291
+
1292
+ /* Allow valid data-* attributes: At least one character after "-"
1293
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1294
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1295
+ We don't need to check the value; it's always URI safe. */
1296
+ if (
1297
+ ALLOW_DATA_ATTR &&
1298
+ !FORBID_ATTR[lcName] &&
1299
+ regExpTest(DATA_ATTR, lcName)
1300
+ ) {
1301
+ // This attribute is safe
1302
+ } else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {
1303
+ // This attribute is safe
1304
+ /* Otherwise, check the name is permitted */
1305
+ } else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1306
+ if (
1307
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1308
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1309
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1310
+ (_isBasicCustomElement(lcTag) &&
1311
+ ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&
1312
+ regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag)) ||
1313
+ (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&
1314
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag))) &&
1315
+ ((CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp &&
1316
+ regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName)) ||
1317
+ (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function &&
1318
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)))) ||
1319
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1320
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1321
+ (lcName === 'is' &&
1322
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&
1323
+ ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&
1324
+ regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)) ||
1325
+ (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&
1326
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))))
1327
+ ) {
1328
+ // If user has supplied a regexp or function in CUSTOM_ELEMENT_HANDLING.tagNameCheck, we need to also allow derived custom elements using the same tagName test.
1329
+ // Additionally, we need to allow attributes passing the CUSTOM_ELEMENT_HANDLING.attributeNameCheck user has configured, as custom elements can define these at their own discretion.
1330
+ } else {
1331
+ return false;
1332
+ }
1333
+ /* Check value is safe. First, is attr inert? If so, is safe */
1334
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) {
1335
+ // This attribute is safe
1336
+ /* Check no script, data or unknown possibly unsafe URI
1337
+ unless we know URI values are safe for that attribute */
1338
+ } else if (
1339
+ regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))
1340
+ ) {
1341
+ // This attribute is safe
1342
+ /* Keep image data URIs alive if src/xlink:href is allowed */
1343
+ /* Further prevent gadget XSS for dynamically built script tags */
1344
+ } else if (
1345
+ (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&
1346
+ lcTag !== 'script' &&
1347
+ stringIndexOf(value, 'data:') === 0 &&
1348
+ DATA_URI_TAGS[lcTag]
1349
+ ) {
1350
+ // This attribute is safe
1351
+ /* Allow unknown protocols: This provides support for links that
1352
+ are handled by protocol handlers which may be unknown ahead of
1353
+ time, e.g. fb:, spotify: */
1354
+ } else if (
1355
+ ALLOW_UNKNOWN_PROTOCOLS &&
1356
+ !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))
1357
+ ) {
1358
+ // This attribute is safe
1359
+ /* Check for binary attributes */
1360
+ } else if (value) {
1361
+ return false;
1362
+ } else {
1363
+ // Binary attributes are safe at this point
1364
+ /* Anything else, presume unsafe, do not add it back */
1365
+ }
1366
+
1367
+ return true;
1368
+ };
1369
+
1370
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1371
+ * never be treated as basic custom elements even when a permissive
1372
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1373
+ const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, [
1374
+ 'annotation-xml',
1375
+ 'color-profile',
1376
+ 'font-face',
1377
+ 'font-face-format',
1378
+ 'font-face-name',
1379
+ 'font-face-src',
1380
+ 'font-face-uri',
1381
+ 'missing-glyph',
1382
+ ]);
1383
+
1384
+ /**
1385
+ * _isBasicCustomElement
1386
+ * checks if at least one dash is included in tagName, and it's not the first char
1387
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1388
+ *
1389
+ * @param tagName name of the tag of the node to sanitize
1390
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1391
+ */
1392
+ const _isBasicCustomElement = function (tagName: string): boolean {
1393
+ return (
1394
+ !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] &&
1395
+ regExpTest(CUSTOM_ELEMENT, tagName)
1396
+ );
1397
+ };
1398
+
1399
+ /**
1400
+ * _sanitizeAttributes
1401
+ *
1402
+ * @protect attributes
1403
+ * @protect nodeName
1404
+ * @protect removeAttribute
1405
+ * @protect setAttribute
1406
+ *
1407
+ * @param currentNode to sanitize
1408
+ */
1409
+ const _sanitizeAttributes = function (currentNode: Element): void {
1410
+ /* Execute a hook if present */
1411
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1412
+
1413
+ const { attributes } = currentNode;
1414
+
1415
+ /* Check if we have attributes; if not we might have a text node */
1416
+ if (!attributes || _isClobbered(currentNode)) {
1417
+ return;
1418
+ }
1419
+
1420
+ const hookEvent = {
1421
+ attrName: '',
1422
+ attrValue: '',
1423
+ keepAttr: true,
1424
+ allowedAttributes: ALLOWED_ATTR,
1425
+ forceKeepAttr: undefined,
1426
+ };
1427
+ let l = attributes.length;
1428
+
1429
+ /* Go backwards over all attributes; safely remove bad ones */
1430
+ while (l--) {
1431
+ const attr = attributes[l];
1432
+ const { name, namespaceURI, value: attrValue } = attr;
1433
+ const lcName = transformCaseFunc(name);
1434
+
1435
+ const initValue = attrValue;
1436
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1437
+
1438
+ /* Execute a hook if present */
1439
+ hookEvent.attrName = lcName;
1440
+ hookEvent.attrValue = value;
1441
+ hookEvent.keepAttr = true;
1442
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1443
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1444
+ value = hookEvent.attrValue;
1445
+
1446
+ /* Full DOM Clobbering protection via namespace isolation,
1447
+ * Prefix id and name attributes with `user-content-`
1448
+ */
1449
+ if (
1450
+ SANITIZE_NAMED_PROPS &&
1451
+ (lcName === 'id' || lcName === 'name') &&
1452
+ stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0
1453
+ ) {
1454
+ // Remove the attribute with this value
1455
+ _removeAttribute(name, currentNode);
1456
+ // Prefix the value and later re-create the attribute with the sanitized value
1457
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1458
+ }
1459
+ // Else: already prefixed, leave the attribute alone — the prefix is
1460
+ // itself the clobbering protection, and re-applying it is incorrect.
1461
+
1462
+ /* Work around a security issue with comments inside attributes */
1463
+ if (
1464
+ SAFE_FOR_XML &&
1465
+ regExpTest(
1466
+ /((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,
1467
+ value
1468
+ )
1469
+ ) {
1470
+ _removeAttribute(name, currentNode);
1471
+ continue;
1472
+ }
1473
+
1474
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1475
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1476
+ _removeAttribute(name, currentNode);
1477
+ continue;
1478
+ }
1479
+
1480
+ /* Did the hooks approve of the attribute? */
1481
+ if (hookEvent.forceKeepAttr) {
1482
+ continue;
1483
+ }
1484
+
1485
+ /* Did the hooks approve of the attribute? */
1486
+ if (!hookEvent.keepAttr) {
1487
+ _removeAttribute(name, currentNode);
1488
+ continue;
1489
+ }
1490
+
1491
+ /* Work around a security issue in jQuery 3.0 */
1492
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1493
+ _removeAttribute(name, currentNode);
1494
+ continue;
1495
+ }
1496
+
1497
+ /* Sanitize attribute content to be template-safe */
1498
+ if (SAFE_FOR_TEMPLATES) {
1499
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {
1500
+ value = stringReplace(value, expr, ' ');
1501
+ });
1502
+ }
1503
+
1504
+ /* Is `value` valid for this attribute? */
1505
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1506
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1507
+ _removeAttribute(name, currentNode);
1508
+ continue;
1509
+ }
1510
+
1511
+ /* Handle attributes that require Trusted Types */
1512
+ if (
1513
+ trustedTypesPolicy &&
1514
+ typeof trustedTypes === 'object' &&
1515
+ typeof trustedTypes.getAttributeType === 'function'
1516
+ ) {
1517
+ if (namespaceURI) {
1518
+ /* Namespaces are not yet supported, see https://bugs.chromium.org/p/chromium/issues/detail?id=1305293 */
1519
+ } else {
1520
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1521
+ case 'TrustedHTML': {
1522
+ value = trustedTypesPolicy.createHTML(value);
1523
+ break;
1524
+ }
1525
+
1526
+ case 'TrustedScriptURL': {
1527
+ value = trustedTypesPolicy.createScriptURL(value);
1528
+ break;
1529
+ }
1530
+
1531
+ default: {
1532
+ break;
1533
+ }
1534
+ }
1535
+ }
1536
+ }
1537
+
1538
+ /* Handle invalid data-* attribute set by try-catching it */
1539
+ if (value !== initValue) {
1540
+ try {
1541
+ if (namespaceURI) {
1542
+ currentNode.setAttributeNS(namespaceURI, name, value);
1543
+ } else {
1544
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1545
+ currentNode.setAttribute(name, value);
1546
+ }
1547
+
1548
+ if (_isClobbered(currentNode)) {
1549
+ _forceRemove(currentNode);
1550
+ } else {
1551
+ arrayPop(DOMPurify.removed);
1552
+ }
1553
+ } catch (_) {
1554
+ _removeAttribute(name, currentNode);
1555
+ }
1556
+ }
1557
+ }
1558
+
1559
+ /* Execute a hook if present */
1560
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1561
+ };
1562
+
1563
+ /**
1564
+ * _sanitizeShadowDOM
1565
+ *
1566
+ * @param fragment to iterate over recursively
1567
+ */
1568
+ const _sanitizeShadowDOM = function (fragment: DocumentFragment): void {
1569
+ let shadowNode = null;
1570
+ const shadowIterator = _createNodeIterator(fragment);
1571
+
1572
+ /* Execute a hook if present */
1573
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1574
+
1575
+ while ((shadowNode = shadowIterator.nextNode())) {
1576
+ /* Execute a hook if present */
1577
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1578
+
1579
+ /* Sanitize tags and elements */
1580
+ _sanitizeElements(shadowNode);
1581
+
1582
+ /* Check attributes next */
1583
+ _sanitizeAttributes(shadowNode);
1584
+
1585
+ /* Deep shadow DOM detected */
1586
+ if (shadowNode.content instanceof DocumentFragment) {
1587
+ _sanitizeShadowDOM(shadowNode.content);
1588
+ }
1589
+ }
1590
+
1591
+ /* Execute a hook if present */
1592
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1593
+ };
1594
+
1595
+ // eslint-disable-next-line complexity
1596
+ DOMPurify.sanitize = function (dirty, cfg = {}) {
1597
+ let body = null;
1598
+ let importedNode = null;
1599
+ let currentNode = null;
1600
+ let returnNode = null;
1601
+ /* Make sure we have a string to sanitize.
1602
+ DO NOT return early, as this will return the wrong type if
1603
+ the user has requested a DOM object rather than a string */
1604
+ IS_EMPTY_INPUT = !dirty;
1605
+ if (IS_EMPTY_INPUT) {
1606
+ dirty = '<!-->';
1607
+ }
1608
+
1609
+ /* Stringify, in case dirty is an object */
1610
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1611
+ dirty = stringifyValue(dirty);
1612
+
1613
+ if (typeof dirty !== 'string') {
1614
+ throw typeErrorCreate('dirty is not a string, aborting');
1615
+ }
1616
+ }
1617
+
1618
+ /* Return dirty HTML if DOMPurify cannot run */
1619
+ if (!DOMPurify.isSupported) {
1620
+ return dirty;
1621
+ }
1622
+
1623
+ /* Assign config vars */
1624
+ if (!SET_CONFIG) {
1625
+ _parseConfig(cfg);
1626
+ }
1627
+
1628
+ /* Clean up removed elements */
1629
+ DOMPurify.removed = [];
1630
+
1631
+ /* Check if dirty is correctly typed for IN_PLACE */
1632
+ if (typeof dirty === 'string') {
1633
+ IN_PLACE = false;
1634
+ }
1635
+
1636
+ if (IN_PLACE) {
1637
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1638
+ const nn = (dirty as Node).nodeName;
1639
+ if (typeof nn === 'string') {
1640
+ const tagName = transformCaseFunc(nn);
1641
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1642
+ throw typeErrorCreate(
1643
+ 'root node is forbidden and cannot be sanitized in-place'
1644
+ );
1645
+ }
1646
+ }
1647
+ } else if (dirty instanceof Node) {
1648
+ /* If dirty is a DOM element, append to an empty document to avoid
1649
+ elements being stripped by the parser */
1650
+ body = _initDocument('<!---->');
1651
+ importedNode = body.ownerDocument.importNode(dirty, true);
1652
+ if (
1653
+ importedNode.nodeType === NODE_TYPE.element &&
1654
+ importedNode.nodeName === 'BODY'
1655
+ ) {
1656
+ /* Node is already a body, use as is */
1657
+ body = importedNode;
1658
+ } else if (importedNode.nodeName === 'HTML') {
1659
+ body = importedNode;
1660
+ } else {
1661
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1662
+ body.appendChild(importedNode);
1663
+ }
1664
+ } else {
1665
+ /* Exit directly if we have nothing to do */
1666
+ if (
1667
+ !RETURN_DOM &&
1668
+ !SAFE_FOR_TEMPLATES &&
1669
+ !WHOLE_DOCUMENT &&
1670
+ // eslint-disable-next-line unicorn/prefer-includes
1671
+ dirty.indexOf('<') === -1
1672
+ ) {
1673
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE
1674
+ ? trustedTypesPolicy.createHTML(dirty)
1675
+ : dirty;
1676
+ }
1677
+
1678
+ /* Initialize the document to work on */
1679
+ body = _initDocument(dirty);
1680
+
1681
+ /* Check we have a DOM node from the data */
1682
+ if (!body) {
1683
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1684
+ }
1685
+ }
1686
+
1687
+ /* Remove first element node (ours) if FORCE_BODY is set */
1688
+ if (body && FORCE_BODY) {
1689
+ _forceRemove(body.firstChild);
1690
+ }
1691
+
1692
+ /* Get node iterator */
1693
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1694
+
1695
+ /* Now start iterating over the created document */
1696
+ while ((currentNode = nodeIterator.nextNode())) {
1697
+ /* Sanitize tags and elements */
1698
+ _sanitizeElements(currentNode);
1699
+
1700
+ /* Check attributes next */
1701
+ _sanitizeAttributes(currentNode);
1702
+
1703
+ /* Shadow DOM detected, sanitize it */
1704
+ if (currentNode.content instanceof DocumentFragment) {
1705
+ _sanitizeShadowDOM(currentNode.content);
1706
+ }
1707
+ }
1708
+
1709
+ /* If we sanitized `dirty` in-place, return it. */
1710
+ if (IN_PLACE) {
1711
+ return dirty;
1712
+ }
1713
+
1714
+ /* Return sanitized string or DOM */
1715
+ if (RETURN_DOM) {
1716
+ if (SAFE_FOR_TEMPLATES) {
1717
+ body.normalize();
1718
+ let html = body.innerHTML;
1719
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {
1720
+ html = stringReplace(html, expr, ' ');
1721
+ });
1722
+ body.innerHTML = html;
1723
+ }
1724
+
1725
+ if (RETURN_DOM_FRAGMENT) {
1726
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1727
+
1728
+ while (body.firstChild) {
1729
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1730
+ returnNode.appendChild(body.firstChild);
1731
+ }
1732
+ } else {
1733
+ returnNode = body;
1734
+ }
1735
+
1736
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1737
+ /*
1738
+ AdoptNode() is not used because internal state is not reset
1739
+ (e.g. the past names map of a HTMLFormElement), this is safe
1740
+ in theory but we would rather not risk another attack vector.
1741
+ The state that is cloned by importNode() is explicitly defined
1742
+ by the specs.
1743
+ */
1744
+ returnNode = importNode.call(originalDocument, returnNode, true);
1745
+ }
1746
+
1747
+ return returnNode;
1748
+ }
1749
+
1750
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1751
+
1752
+ /* Serialize doctype if allowed */
1753
+ if (
1754
+ WHOLE_DOCUMENT &&
1755
+ ALLOWED_TAGS['!doctype'] &&
1756
+ body.ownerDocument &&
1757
+ body.ownerDocument.doctype &&
1758
+ body.ownerDocument.doctype.name &&
1759
+ regExpTest(EXPRESSIONS.DOCTYPE_NAME, body.ownerDocument.doctype.name)
1760
+ ) {
1761
+ serializedHTML =
1762
+ '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1763
+ }
1764
+
1765
+ /* Sanitize final string template-safe */
1766
+ if (SAFE_FOR_TEMPLATES) {
1767
+ arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {
1768
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1769
+ });
1770
+ }
1771
+
1772
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE
1773
+ ? trustedTypesPolicy.createHTML(serializedHTML)
1774
+ : serializedHTML;
1775
+ };
1776
+
1777
+ DOMPurify.setConfig = function (cfg = {}) {
1778
+ _parseConfig(cfg);
1779
+ SET_CONFIG = true;
1780
+ };
1781
+
1782
+ DOMPurify.clearConfig = function () {
1783
+ CONFIG = null;
1784
+ SET_CONFIG = false;
1785
+ };
1786
+
1787
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1788
+ /* Initialize shared config vars if necessary. */
1789
+ if (!CONFIG) {
1790
+ _parseConfig({});
1791
+ }
1792
+
1793
+ const lcTag = transformCaseFunc(tag);
1794
+ const lcName = transformCaseFunc(attr);
1795
+ return _isValidAttribute(lcTag, lcName, value);
1796
+ };
1797
+
1798
+ DOMPurify.addHook = function (
1799
+ entryPoint: keyof HooksMap,
1800
+ hookFunction: HookFunction
1801
+ ) {
1802
+ if (typeof hookFunction !== 'function') {
1803
+ return;
1804
+ }
1805
+
1806
+ arrayPush(hooks[entryPoint], hookFunction);
1807
+ };
1808
+
1809
+ DOMPurify.removeHook = function (
1810
+ entryPoint: keyof HooksMap,
1811
+ hookFunction: HookFunction
1812
+ ) {
1813
+ if (hookFunction !== undefined) {
1814
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1815
+
1816
+ return index === -1
1817
+ ? undefined
1818
+ : arraySplice(hooks[entryPoint], index, 1)[0];
1819
+ }
1820
+
1821
+ return arrayPop(hooks[entryPoint]);
1822
+ };
1823
+
1824
+ DOMPurify.removeHooks = function (entryPoint: keyof HooksMap) {
1825
+ hooks[entryPoint] = [];
1826
+ };
1827
+
1828
+ DOMPurify.removeAllHooks = function () {
1829
+ hooks = _createHooksMap();
1830
+ };
1831
+
1832
+ return DOMPurify;
1833
+ }
1834
+
1835
+ export default createDOMPurify();
1836
+
1837
+ export interface DOMPurify {
1838
+ /**
1839
+ * Creates a DOMPurify instance using the given window-like object. Defaults to `window`.
1840
+ */
1841
+ (root?: WindowLike): DOMPurify;
1842
+
1843
+ /**
1844
+ * Version label, exposed for easier checks
1845
+ * if DOMPurify is up to date or not
1846
+ */
1847
+ version: string;
1848
+
1849
+ /**
1850
+ * Array of elements that DOMPurify removed during sanitation.
1851
+ * Empty if nothing was removed.
1852
+ */
1853
+ removed: Array<RemovedElement | RemovedAttribute>;
1854
+
1855
+ /**
1856
+ * Expose whether this browser supports running the full DOMPurify.
1857
+ */
1858
+ isSupported: boolean;
1859
+
1860
+ /**
1861
+ * Set the configuration once.
1862
+ *
1863
+ * @param cfg configuration object
1864
+ */
1865
+ setConfig(cfg?: Config): void;
1866
+
1867
+ /**
1868
+ * Removes the configuration.
1869
+ */
1870
+ clearConfig(): void;
1871
+
1872
+ /**
1873
+ * Provides core sanitation functionality.
1874
+ *
1875
+ * @param dirty string or DOM node
1876
+ * @param cfg object
1877
+ * @returns Sanitized TrustedHTML.
1878
+ */
1879
+ sanitize(
1880
+ dirty: string | Node,
1881
+ cfg: Config & { RETURN_TRUSTED_TYPE: true }
1882
+ ): TrustedHTML;
1883
+
1884
+ /**
1885
+ * Provides core sanitation functionality.
1886
+ *
1887
+ * @param dirty DOM node
1888
+ * @param cfg object
1889
+ * @returns Sanitized DOM node.
1890
+ */
1891
+ sanitize(dirty: Node, cfg: Config & { IN_PLACE: true }): Node;
1892
+
1893
+ /**
1894
+ * Provides core sanitation functionality.
1895
+ *
1896
+ * @param dirty string or DOM node
1897
+ * @param cfg object
1898
+ * @returns Sanitized DOM node.
1899
+ */
1900
+ sanitize(dirty: string | Node, cfg: Config & { RETURN_DOM: true }): Node;
1901
+
1902
+ /**
1903
+ * Provides core sanitation functionality.
1904
+ *
1905
+ * @param dirty string or DOM node
1906
+ * @param cfg object
1907
+ * @returns Sanitized document fragment.
1908
+ */
1909
+ sanitize(
1910
+ dirty: string | Node,
1911
+ cfg: Config & { RETURN_DOM_FRAGMENT: true }
1912
+ ): DocumentFragment;
1913
+
1914
+ /**
1915
+ * Provides core sanitation functionality.
1916
+ *
1917
+ * @param dirty string or DOM node
1918
+ * @param cfg object
1919
+ * @returns Sanitized string.
1920
+ */
1921
+ sanitize(dirty: string | Node, cfg?: Config): string;
1922
+
1923
+ /**
1924
+ * Checks if an attribute value is valid.
1925
+ * Uses last set config, if any. Otherwise, uses config defaults.
1926
+ *
1927
+ * @param tag Tag name of containing element.
1928
+ * @param attr Attribute name.
1929
+ * @param value Attribute value.
1930
+ * @returns Returns true if `value` is valid. Otherwise, returns false.
1931
+ */
1932
+ isValidAttribute(tag: string, attr: string, value: string): boolean;
1933
+
1934
+ /**
1935
+ * Adds a DOMPurify hook.
1936
+ *
1937
+ * @param entryPoint entry point for the hook to add
1938
+ * @param hookFunction function to execute
1939
+ */
1940
+ addHook(entryPoint: BasicHookName, hookFunction: NodeHook): void;
1941
+
1942
+ /**
1943
+ * Adds a DOMPurify hook.
1944
+ *
1945
+ * @param entryPoint entry point for the hook to add
1946
+ * @param hookFunction function to execute
1947
+ */
1948
+ addHook(entryPoint: ElementHookName, hookFunction: ElementHook): void;
1949
+
1950
+ /**
1951
+ * Adds a DOMPurify hook.
1952
+ *
1953
+ * @param entryPoint entry point for the hook to add
1954
+ * @param hookFunction function to execute
1955
+ */
1956
+ addHook(
1957
+ entryPoint: DocumentFragmentHookName,
1958
+ hookFunction: DocumentFragmentHook
1959
+ ): void;
1960
+
1961
+ /**
1962
+ * Adds a DOMPurify hook.
1963
+ *
1964
+ * @param entryPoint entry point for the hook to add
1965
+ * @param hookFunction function to execute
1966
+ */
1967
+ addHook(
1968
+ entryPoint: 'uponSanitizeElement',
1969
+ hookFunction: UponSanitizeElementHook
1970
+ ): void;
1971
+
1972
+ /**
1973
+ * Adds a DOMPurify hook.
1974
+ *
1975
+ * @param entryPoint entry point for the hook to add
1976
+ * @param hookFunction function to execute
1977
+ */
1978
+ addHook(
1979
+ entryPoint: 'uponSanitizeAttribute',
1980
+ hookFunction: UponSanitizeAttributeHook
1981
+ ): void;
1982
+
1983
+ /**
1984
+ * Remove a DOMPurify hook at a given entryPoint
1985
+ * (pops it from the stack of hooks if hook not specified)
1986
+ *
1987
+ * @param entryPoint entry point for the hook to remove
1988
+ * @param hookFunction optional specific hook to remove
1989
+ * @returns removed hook
1990
+ */
1991
+ removeHook(
1992
+ entryPoint: BasicHookName,
1993
+ hookFunction?: NodeHook
1994
+ ): NodeHook | undefined;
1995
+
1996
+ /**
1997
+ * Remove a DOMPurify hook at a given entryPoint
1998
+ * (pops it from the stack of hooks if hook not specified)
1999
+ *
2000
+ * @param entryPoint entry point for the hook to remove
2001
+ * @param hookFunction optional specific hook to remove
2002
+ * @returns removed hook
2003
+ */
2004
+ removeHook(
2005
+ entryPoint: ElementHookName,
2006
+ hookFunction?: ElementHook
2007
+ ): ElementHook | undefined;
2008
+
2009
+ /**
2010
+ * Remove a DOMPurify hook at a given entryPoint
2011
+ * (pops it from the stack of hooks if hook not specified)
2012
+ *
2013
+ * @param entryPoint entry point for the hook to remove
2014
+ * @param hookFunction optional specific hook to remove
2015
+ * @returns removed hook
2016
+ */
2017
+ removeHook(
2018
+ entryPoint: DocumentFragmentHookName,
2019
+ hookFunction?: DocumentFragmentHook
2020
+ ): DocumentFragmentHook | undefined;
2021
+
2022
+ /**
2023
+ * Remove a DOMPurify hook at a given entryPoint
2024
+ * (pops it from the stack of hooks if hook not specified)
2025
+ *
2026
+ * @param entryPoint entry point for the hook to remove
2027
+ * @param hookFunction optional specific hook to remove
2028
+ * @returns removed hook
2029
+ */
2030
+ removeHook(
2031
+ entryPoint: 'uponSanitizeElement',
2032
+ hookFunction?: UponSanitizeElementHook
2033
+ ): UponSanitizeElementHook | undefined;
2034
+
2035
+ /**
2036
+ * Remove a DOMPurify hook at a given entryPoint
2037
+ * (pops it from the stack of hooks if hook not specified)
2038
+ *
2039
+ * @param entryPoint entry point for the hook to remove
2040
+ * @param hookFunction optional specific hook to remove
2041
+ * @returns removed hook
2042
+ */
2043
+ removeHook(
2044
+ entryPoint: 'uponSanitizeAttribute',
2045
+ hookFunction?: UponSanitizeAttributeHook
2046
+ ): UponSanitizeAttributeHook | undefined;
2047
+
2048
+ /**
2049
+ * Removes all DOMPurify hooks at a given entryPoint
2050
+ *
2051
+ * @param entryPoint entry point for the hooks to remove
2052
+ */
2053
+ removeHooks(entryPoint: HookName): void;
2054
+
2055
+ /**
2056
+ * Removes all DOMPurify hooks.
2057
+ */
2058
+ removeAllHooks(): void;
2059
+ }
2060
+
2061
+ /**
2062
+ * An element removed by DOMPurify.
2063
+ */
2064
+ export interface RemovedElement {
2065
+ /**
2066
+ * The element that was removed.
2067
+ */
2068
+ element: Node;
2069
+ }
2070
+
2071
+ /**
2072
+ * An element removed by DOMPurify.
2073
+ */
2074
+ export interface RemovedAttribute {
2075
+ /**
2076
+ * The attribute that was removed.
2077
+ */
2078
+ attribute: Attr | null;
2079
+
2080
+ /**
2081
+ * The element that the attribute was removed.
2082
+ */
2083
+ from: Node;
2084
+ }
2085
+
2086
+ type BasicHookName =
2087
+ | 'beforeSanitizeElements'
2088
+ | 'afterSanitizeElements'
2089
+ | 'uponSanitizeShadowNode';
2090
+ type ElementHookName = 'beforeSanitizeAttributes' | 'afterSanitizeAttributes';
2091
+ type DocumentFragmentHookName =
2092
+ | 'beforeSanitizeShadowDOM'
2093
+ | 'afterSanitizeShadowDOM';
2094
+ type UponSanitizeElementHookName = 'uponSanitizeElement';
2095
+ type UponSanitizeAttributeHookName = 'uponSanitizeAttribute';
2096
+
2097
+ interface HooksMap {
2098
+ beforeSanitizeElements: NodeHook[];
2099
+ afterSanitizeElements: NodeHook[];
2100
+ beforeSanitizeShadowDOM: DocumentFragmentHook[];
2101
+ uponSanitizeShadowNode: NodeHook[];
2102
+ afterSanitizeShadowDOM: DocumentFragmentHook[];
2103
+ beforeSanitizeAttributes: ElementHook[];
2104
+ afterSanitizeAttributes: ElementHook[];
2105
+ uponSanitizeElement: UponSanitizeElementHook[];
2106
+ uponSanitizeAttribute: UponSanitizeAttributeHook[];
2107
+ }
2108
+
2109
+ type ArrayElement<T> = T extends Array<infer U> ? U : never;
2110
+
2111
+ type HookFunction = ArrayElement<HooksMap[keyof HooksMap]>;
2112
+
2113
+ export type HookName =
2114
+ | BasicHookName
2115
+ | ElementHookName
2116
+ | DocumentFragmentHookName
2117
+ | UponSanitizeElementHookName
2118
+ | UponSanitizeAttributeHookName;
2119
+
2120
+ export type NodeHook = (
2121
+ this: DOMPurify,
2122
+ currentNode: Node,
2123
+ hookEvent: null,
2124
+ config: Config
2125
+ ) => void;
2126
+
2127
+ export type ElementHook = (
2128
+ this: DOMPurify,
2129
+ currentNode: Element,
2130
+ hookEvent: null,
2131
+ config: Config
2132
+ ) => void;
2133
+
2134
+ export type DocumentFragmentHook = (
2135
+ this: DOMPurify,
2136
+ currentNode: DocumentFragment,
2137
+ hookEvent: null,
2138
+ config: Config
2139
+ ) => void;
2140
+
2141
+ export type UponSanitizeElementHook = (
2142
+ this: DOMPurify,
2143
+ currentNode: Node,
2144
+ hookEvent: UponSanitizeElementHookEvent,
2145
+ config: Config
2146
+ ) => void;
2147
+
2148
+ export type UponSanitizeAttributeHook = (
2149
+ this: DOMPurify,
2150
+ currentNode: Element,
2151
+ hookEvent: UponSanitizeAttributeHookEvent,
2152
+ config: Config
2153
+ ) => void;
2154
+
2155
+ export interface UponSanitizeElementHookEvent {
2156
+ tagName: string;
2157
+ allowedTags: Record<string, boolean>;
2158
+ }
2159
+
2160
+ export interface UponSanitizeAttributeHookEvent {
2161
+ attrName: string;
2162
+ attrValue: string;
2163
+ keepAttr: boolean;
2164
+ allowedAttributes: Record<string, boolean>;
2165
+ forceKeepAttr: boolean | undefined;
2166
+ }
2167
+
2168
+ /**
2169
+ * A `Window`-like object containing the properties and types that DOMPurify requires.
2170
+ */
2171
+ export type WindowLike = Pick<
2172
+ typeof globalThis,
2173
+ | 'DocumentFragment'
2174
+ | 'HTMLTemplateElement'
2175
+ | 'Node'
2176
+ | 'Element'
2177
+ | 'NodeFilter'
2178
+ | 'NamedNodeMap'
2179
+ | 'HTMLFormElement'
2180
+ | 'DOMParser'
2181
+ > & {
2182
+ document?: Document;
2183
+ MozNamedAttrMap?: typeof window.NamedNodeMap;
2184
+ } & Pick<TrustedTypesWindow, 'trustedTypes'>;