dompurify 3.4.13 → 3.4.14

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 CHANGED
@@ -65,6 +65,48 @@ const NODE_TYPE = {
65
65
  notation: 12, // Deprecated
66
66
  };
67
67
 
68
+ /* HTML-namespace elements whose child text nodes are serialized *literally*
69
+ (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS
70
+ shapes ride on that literal serialization:
71
+ (a) an element child - a tree the HTML parser can never build, but the DOM
72
+ API and an XML/XHTML parse can - after which a `</tag>`-bearing text
73
+ sibling breaks the element open on reparse; and
74
+ (b) text-only content that already carries the element's OWN end tag, e.g.
75
+ `<style>...</style><img onerror=x>` built as a node, which the literal
76
+ serializer emits verbatim for the HTML parser to re-open.
77
+ Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape
78
+ (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized
79
+ form for these elements) rather than innerHTML, because an XML/XHTML working
80
+ document serializes innerHTML with `<` escaped, which silently blinds the
81
+ innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.
82
+ `script` is never allow-listed, but is kept here so the guard matches the
83
+ serializer's own literal-text list exactly. */
84
+ const LITERAL_TEXT_ELEMENT_NAMES = [
85
+ 'style',
86
+ 'script',
87
+ 'xmp',
88
+ 'iframe',
89
+ 'noembed',
90
+ 'noframes',
91
+ 'plaintext',
92
+ 'noscript',
93
+ ];
94
+ const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));
95
+
96
+ /* Per-element end-tag matcher. On an HTML reparse the ONLY token that
97
+ terminates a literal-text element's raw content is its own end tag; a foreign
98
+ literal-text close (e.g. `</xmp>` sitting inside `<style>`) does not break
99
+ out, so matching is per-element, not a shared alternation. The lookahead
100
+ requires an HTML tag-name terminator (whitespace, `/` or `>`) so a longer
101
+ name such as `</styles` is not mistaken for `</style`. */
102
+ const LITERAL_TEXT_CLOSE = (function (): Record<string, RegExp> {
103
+ const map: Record<string, RegExp> = {};
104
+ arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, (name) => {
105
+ map[name] = seal(new RegExp('</' + name + '(?=[\\t\\n\\f\\r />])', 'i'));
106
+ });
107
+ return freeze(map);
108
+ })();
109
+
68
110
  const getGlobal = function (): WindowLike {
69
111
  return typeof window === 'undefined' ? null : window;
70
112
  };
@@ -163,6 +205,28 @@ const _resolveSetOption = function (
163
205
  : fallback;
164
206
  };
165
207
 
208
+ /**
209
+ * Resolve an object-valued configuration option: a prototype-free clone
210
+ * of cfg[key] when it is an own, truthy object property, else a fresh
211
+ * fallback built by makeFallback (fresh on every parse, so a previous
212
+ * parse can never leak state into the next one).
213
+ *
214
+ * @param cfg the cloned, prototype-free configuration object
215
+ * @param key the configuration property to read
216
+ * @param makeFallback builds the fallback value when the option is absent
217
+ * @returns the resolved object
218
+ */
219
+ const _resolveObjectOption = function <T extends Record<string, any>>(
220
+ cfg: Config,
221
+ key: keyof Config,
222
+ makeFallback: () => T
223
+ ): T {
224
+ const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;
225
+ return value && typeof value === 'object'
226
+ ? clone(value as T)
227
+ : makeFallback();
228
+ };
229
+
166
230
  function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
167
231
  const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);
168
232
 
@@ -218,6 +282,18 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
218
282
  ? lookupGetter(Node.prototype, 'ownerDocument')
219
283
  : null;
220
284
 
285
+ /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype
286
+ getters, with a direct-property fallback for environments that lack
287
+ Node.prototype. Sites that need a different fallback (e.g. _isClobbered
288
+ returns early on a null name) intentionally keep their own reads. */
289
+ const _readNodeType = function (node: Node): number {
290
+ return getNodeType ? getNodeType(node) : (node as any).nodeType;
291
+ };
292
+
293
+ const _readNodeName = function (node: Node): string {
294
+ return getNodeName ? getNodeName(node) : (node as any).nodeName;
295
+ };
296
+
221
297
  // As per issue #47, the web-components registry is inherited by a
222
298
  // new document created via createHTMLDocument. As per the spec
223
299
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -728,26 +804,23 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
728
804
  NAMESPACE =
729
805
  typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
730
806
 
731
- MATHML_TEXT_INTEGRATION_POINTS =
732
- objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') &&
733
- cfg.MATHML_TEXT_INTEGRATION_POINTS &&
734
- typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object'
735
- ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS)
736
- : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map
737
-
738
- HTML_INTEGRATION_POINTS =
739
- objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') &&
740
- cfg.HTML_INTEGRATION_POINTS &&
741
- typeof cfg.HTML_INTEGRATION_POINTS === 'object'
742
- ? clone(cfg.HTML_INTEGRATION_POINTS)
743
- : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map
744
-
745
- const customElementHandling =
746
- objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') &&
747
- cfg.CUSTOM_ELEMENT_HANDLING &&
748
- typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object'
749
- ? clone(cfg.CUSTOM_ELEMENT_HANDLING)
750
- : create(null);
807
+ MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(
808
+ cfg,
809
+ 'MATHML_TEXT_INTEGRATION_POINTS',
810
+ () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS) // Default built-in map
811
+ );
812
+
813
+ HTML_INTEGRATION_POINTS = _resolveObjectOption(
814
+ cfg,
815
+ 'HTML_INTEGRATION_POINTS',
816
+ () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS) // Default built-in map
817
+ );
818
+
819
+ const customElementHandling = _resolveObjectOption(
820
+ cfg,
821
+ 'CUSTOM_ELEMENT_HANDLING',
822
+ () => create(null)
823
+ );
751
824
 
752
825
  CUSTOM_ELEMENT_HANDLING = create(null);
753
826
 
@@ -845,24 +918,6 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
845
918
  }
846
919
  }
847
920
 
848
- if (
849
- objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') &&
850
- arrayIsArray(cfg.ADD_URI_SAFE_ATTR)
851
- ) {
852
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
853
- }
854
-
855
- if (
856
- objectHasOwnProperty(cfg, 'FORBID_CONTENTS') &&
857
- arrayIsArray(cfg.FORBID_CONTENTS)
858
- ) {
859
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
860
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
861
- }
862
-
863
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
864
- }
865
-
866
921
  if (
867
922
  objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') &&
868
923
  arrayIsArray(cfg.ADD_FORBID_CONTENTS)
@@ -1175,6 +1230,37 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1175
1230
  }
1176
1231
  };
1177
1232
 
1233
+ /**
1234
+ * _stripAttributeNode
1235
+ *
1236
+ * Remove a single Attr node case/namespace-exactly on an attribute-teardown
1237
+ * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an
1238
+ * HTML element in an HTML document and so silently misses a case-preserved
1239
+ * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect
1240
+ * _removeAttribute() was fixed for, which a name-based call would reintroduce
1241
+ * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not
1242
+ * record into DOMPurify.removed: the neutralize passes intentionally do not
1243
+ * book-keep. A clobbered/detached node falls back to best-effort name-based
1244
+ * removal.
1245
+ *
1246
+ * @param element the element to strip the attribute from
1247
+ * @param attribute the Attr node to remove
1248
+ * @param name the attribute's name, for the fallback path
1249
+ */
1250
+ const _stripAttributeNode = function (
1251
+ element: Element,
1252
+ attribute: Attr,
1253
+ name: string
1254
+ ): void {
1255
+ try {
1256
+ element.removeAttributeNode(attribute);
1257
+ } catch (_) {
1258
+ try {
1259
+ element.removeAttribute(name);
1260
+ } catch (_) {}
1261
+ }
1262
+ };
1263
+
1178
1264
  /**
1179
1265
  * _neutralizeRoot
1180
1266
  *
@@ -1221,11 +1307,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1221
1307
  const attribute = attributes[i];
1222
1308
  const name = attribute && attribute.name;
1223
1309
  if (typeof name === 'string') {
1224
- try {
1225
- (root as Element).removeAttribute(name);
1226
- } catch (_) {
1227
- /* Clobbered removeAttribute — ignore (fail-closed best effort) */
1228
- }
1310
+ _stripAttributeNode(root as Element, attribute, name);
1229
1311
  }
1230
1312
  }
1231
1313
  }
@@ -1234,24 +1316,53 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1234
1316
  /**
1235
1317
  * _removeAttribute
1236
1318
  *
1319
+ * Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their
1320
+ * lookup key for HTML elements in an HTML document, so they silently miss an
1321
+ * attribute whose stored qualified name still contains uppercase ASCII
1322
+ * letters. That happens when the node came from a case-preserving source
1323
+ * (an XML/XHTML document imported via importNode(), or createAttributeNS()),
1324
+ * where e.g. `ONERROR` survives the walk: the policy check lowercases to
1325
+ * `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up
1326
+ * `onerror` and finds nothing. Remove the exact Attr node instead, which is
1327
+ * case- and namespace-exact, and fall back to name-based removal only when
1328
+ * the caller could not supply the node.
1329
+ *
1237
1330
  * @param name an Attribute name
1238
1331
  * @param element a DOM node
1332
+ * @param attr the exact Attr node to remove, when the caller has it
1239
1333
  */
1240
- const _removeAttribute = function (name: string, element: Element): void {
1334
+ const _removeAttribute = function (
1335
+ name: string,
1336
+ element: Element,
1337
+ attr?: Attr | null
1338
+ ): void {
1339
+ if (!attr) {
1340
+ try {
1341
+ attr = element.getAttributeNode(name);
1342
+ } catch (_) {
1343
+ attr = null;
1344
+ }
1345
+ }
1346
+
1347
+ arrayPush(DOMPurify.removed, {
1348
+ attribute: attr || null,
1349
+ from: element,
1350
+ });
1351
+
1241
1352
  try {
1242
- arrayPush(DOMPurify.removed, {
1243
- attribute: element.getAttributeNode(name),
1244
- from: element,
1245
- });
1353
+ if (attr) {
1354
+ element.removeAttributeNode(attr);
1355
+ } else {
1356
+ element.removeAttribute(name);
1357
+ }
1246
1358
  } catch (_) {
1247
- arrayPush(DOMPurify.removed, {
1248
- attribute: null,
1249
- from: element,
1250
- });
1359
+ /* Clobbered or already-detached node - best-effort fall back to a
1360
+ name-based removal so the "is" handling below still runs. */
1361
+ try {
1362
+ element.removeAttribute(name);
1363
+ } catch (_) {}
1251
1364
  }
1252
1365
 
1253
- element.removeAttribute(name);
1254
-
1255
1366
  // We void attribute values for unremovable "is" attributes
1256
1367
  if (name === 'is') {
1257
1368
  if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
@@ -1289,11 +1400,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1289
1400
  continue;
1290
1401
  }
1291
1402
 
1292
- try {
1293
- element.removeAttribute(name);
1294
- } catch (_) {
1295
- /* Clobbered removeAttribute on a doomed node — ignore */
1296
- }
1403
+ _stripAttributeNode(element, attribute, name);
1297
1404
  }
1298
1405
  };
1299
1406
 
@@ -1324,7 +1431,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1324
1431
 
1325
1432
  while (stack.length > 0) {
1326
1433
  const node = stack.pop();
1327
- const nodeType = getNodeType ? getNodeType(node) : (node as any).nodeType;
1434
+ const nodeType = _readNodeType(node);
1328
1435
 
1329
1436
  if (nodeType === NODE_TYPE.element) {
1330
1437
  _stripDisallowedAttributes(node as Element);
@@ -1374,6 +1481,32 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1374
1481
  *
1375
1482
  * @param root the in-place root to sweep
1376
1483
  */
1484
+ /**
1485
+ * Central policy for declarative-partial-updates patch-linkage attributes,
1486
+ * shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so
1487
+ * the two sites cannot drift: `patchsrc` always links, `for` links
1488
+ * everywhere except on <label>/<output>, and the whole policy is gated on
1489
+ * SAFE_FOR_XML (see the rationale block in _isValidAttribute).
1490
+ *
1491
+ * @param lcName the transformCaseFunc'd attribute name
1492
+ * @param lcTag the transformCaseFunc'd tag name of the carrying element
1493
+ * @return true if the attribute is patch linkage and must be dropped
1494
+ */
1495
+ const _isPatchLinkageAttribute = function (
1496
+ lcName: string,
1497
+ lcTag: string
1498
+ ): boolean {
1499
+ if (!SAFE_FOR_XML) {
1500
+ return false;
1501
+ }
1502
+
1503
+ if (lcName === 'patchsrc') {
1504
+ return true;
1505
+ }
1506
+
1507
+ return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';
1508
+ };
1509
+
1377
1510
  const _neutralizePatchLinkage = function (root: Node): void {
1378
1511
  if (!SAFE_FOR_XML) {
1379
1512
  return;
@@ -1382,7 +1515,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1382
1515
  const stack: Node[] = [root];
1383
1516
  while (stack.length > 0) {
1384
1517
  const node = stack.pop();
1385
- const nodeType = getNodeType ? getNodeType(node) : (node as any).nodeType;
1518
+ const nodeType = _readNodeType(node);
1386
1519
 
1387
1520
  /* Remove range markers (the target side of a patch linkage): every
1388
1521
  processing instruction, and any markup-bearing comment. */
@@ -1403,9 +1536,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1403
1536
  /* Strip patch-source attributes (the source side) off elements. */
1404
1537
  if (nodeType === NODE_TYPE.element) {
1405
1538
  const element = node as Element;
1406
- const lcTag = transformCaseFunc(
1407
- getNodeName ? getNodeName(node) : (node as any).nodeName
1408
- );
1539
+ const lcTag = transformCaseFunc(_readNodeName(node));
1409
1540
  try {
1410
1541
  if (element.hasAttribute && element.hasAttribute('patchsrc')) {
1411
1542
  element.removeAttribute('patchsrc');
@@ -1414,8 +1545,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1414
1545
  if (
1415
1546
  element.hasAttribute &&
1416
1547
  element.hasAttribute('for') &&
1417
- lcTag !== 'label' &&
1418
- lcTag !== 'output'
1548
+ _isPatchLinkageAttribute('for', lcTag)
1419
1549
  ) {
1420
1550
  element.removeAttribute('for');
1421
1551
  }
@@ -1751,12 +1881,22 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1751
1881
  return true;
1752
1882
  }
1753
1883
 
1754
- /* Remove risky CSS construction leading to mXSS */
1884
+ /* Remove rawtext/literal-text elements whose literal serialization
1885
+ re-opens markup on an HTML reparse - shapes (a) and (b) documented at
1886
+ LITERAL_TEXT_ELEMENTS. Both are invisible to rule 1 above (which
1887
+ self-disables once there is an element child, and whose second probe
1888
+ reads the innerHTML an XML/XHTML document serializes escaped), which
1889
+ is why both probes here read textContent instead. Previously only
1890
+ `style`-with-element-child was covered; every element in
1891
+ LITERAL_TEXT_ELEMENTS shares this literal serialization and is
1892
+ equally affected. */
1755
1893
  if (
1756
1894
  SAFE_FOR_XML &&
1757
1895
  currentNode.namespaceURI === HTML_NAMESPACE &&
1758
- tagName === 'style' &&
1759
- _isNode(currentNode.firstElementChild)
1896
+ LITERAL_TEXT_ELEMENTS[tagName] &&
1897
+ (_isNode(currentNode.firstElementChild) ||
1898
+ (typeof currentNode.textContent === 'string' &&
1899
+ regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent)))
1760
1900
  ) {
1761
1901
  return true;
1762
1902
  }
@@ -1778,6 +1918,34 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1778
1918
  return false;
1779
1919
  };
1780
1920
 
1921
+ /**
1922
+ * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate
1923
+ * function, per the validation in _parseConfig) against a name.
1924
+ * Additional arguments are forwarded to predicate functions - the
1925
+ * attributeNameCheck predicate receives the tag name as its second
1926
+ * argument. A null/absent check never matches.
1927
+ *
1928
+ * @param check the configured tagNameCheck / attributeNameCheck value
1929
+ * @param name the name to test
1930
+ * @param args extra arguments forwarded to a predicate function
1931
+ * @return true if the check matches the name
1932
+ */
1933
+ const _matchesNameCheck = function (
1934
+ check: unknown,
1935
+ name: string,
1936
+ ...args: unknown[]
1937
+ ): boolean {
1938
+ if (check instanceof RegExp) {
1939
+ return regExpTest(check, name);
1940
+ }
1941
+
1942
+ if (check instanceof Function) {
1943
+ return Boolean(check(name, ...args));
1944
+ }
1945
+
1946
+ return false;
1947
+ };
1948
+
1781
1949
  /**
1782
1950
  * Handle a node whose tag is forbidden or not allowlisted: keep
1783
1951
  * allowed custom elements (false return exits _sanitizeElements
@@ -1801,20 +1969,12 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1801
1969
  root: Node
1802
1970
  ): boolean {
1803
1971
  /* Check if we have a custom element to handle */
1804
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1805
- if (
1806
- CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&
1807
- regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)
1808
- ) {
1809
- return false;
1810
- }
1811
-
1812
- if (
1813
- CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&
1814
- CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)
1815
- ) {
1816
- return false;
1817
- }
1972
+ if (
1973
+ !FORBID_TAGS[tagName] &&
1974
+ _isBasicCustomElement(tagName) &&
1975
+ _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)
1976
+ ) {
1977
+ return false;
1818
1978
  }
1819
1979
 
1820
1980
  /* Keep content except for bad-listed elements.
@@ -1893,6 +2053,52 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1893
2053
  return set === defaultSet || set === setConfigSet ? clone(set) : set;
1894
2054
  };
1895
2055
 
2056
+ /**
2057
+ * Shared guard for a node that a hook has detached from the walk tree,
2058
+ * used after each element-hook site in _sanitizeElements. Detaching is a
2059
+ * long-standing user pattern (issue #469; draw.io-style foreignObject
2060
+ * filtering). Per the cached, unclobberable parentNode getter the node is
2061
+ * genuinely out of the tree, so it can reach neither the serialized
2062
+ * output nor an IN_PLACE live tree; treat it as removed and stop
2063
+ * processing it. Without this guard, the unsafe-node / namespace checks
2064
+ * would call _forceRemove on a parentless node and hit the REPORT-3
2065
+ * fail-closed throw — which exists for nodes DOMPurify wants gone but
2066
+ * *cannot* detach (clobbered / parentless roots), the opposite of a node
2067
+ * that is already safely gone. The walk root is exempt: a detached
2068
+ * IN_PLACE root is legitimate input and must still be fully sanitized,
2069
+ * and a kill-decision on it must keep hitting the REPORT-3 throw.
2070
+ *
2071
+ * Nodes detached by hooks stay the hook's responsibility for placement:
2072
+ * they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE
2073
+ * pass (which iterates DOMPurify.removed) does not reach them. But a
2074
+ * hook-detached subtree can still hold a queued resource-event handler -
2075
+ * e.g. an <img onload> that began loading when the caller built the live
2076
+ * tree - which fires in page scope after sanitize returns even though the
2077
+ * handler never reached the returned tree. That is the audit-5 F1 hazard,
2078
+ * and the documented node.remove() hook pattern walks straight into it.
2079
+ * So on the IN_PLACE path we neutralize the detached subtree inline,
2080
+ * stripping its non-allow-listed attributes before returning, exactly as
2081
+ * the post-walk pass does for _forceRemove'd subtrees.
2082
+ *
2083
+ * @param currentNode the node a hook may have detached
2084
+ * @param root the current walk root
2085
+ * @return true if the node is detached and now handled, false otherwise
2086
+ */
2087
+ const _handleHookDetachedNode = function (
2088
+ currentNode: Node,
2089
+ root: Node
2090
+ ): boolean {
2091
+ if (currentNode === root || getParentNode(currentNode) !== null) {
2092
+ return false;
2093
+ }
2094
+
2095
+ if (IN_PLACE) {
2096
+ _neutralizeSubtree(currentNode);
2097
+ }
2098
+
2099
+ return true;
2100
+ };
2101
+
1896
2102
  /**
1897
2103
  * _sanitizeElements
1898
2104
  *
@@ -1902,20 +2108,13 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1902
2108
  * @param currentNode to check for permission to exist
1903
2109
  * @return true if node was killed, false if left alive
1904
2110
  */
1905
- // eslint-disable-next-line complexity
1906
2111
  const _sanitizeElements = function (currentNode: any, root: Node): boolean {
1907
2112
  /* Execute a hook if present */
1908
2113
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1909
2114
 
1910
- /* A hook may have detached the node - treat it as removed (see the
1911
- detached-node comment after the uponSanitizeElement hook below). On
1912
- the IN_PLACE path, neutralize the detached subtree first so a queued
1913
- resource handler on it cannot fire in page scope after we return. */
1914
- if (currentNode !== root && getParentNode(currentNode) === null) {
1915
- if (IN_PLACE) {
1916
- _neutralizeSubtree(currentNode);
1917
- }
1918
-
2115
+ /* A hook may have detached the node - treat it as removed (see
2116
+ _handleHookDetachedNode for the full rationale). */
2117
+ if (_handleHookDetachedNode(currentNode, root)) {
1919
2118
  return true;
1920
2119
  }
1921
2120
 
@@ -1926,9 +2125,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1926
2125
  }
1927
2126
 
1928
2127
  /* Now let's check the element's type and name */
1929
- const tagName = transformCaseFunc(
1930
- getNodeName ? getNodeName(currentNode) : currentNode.nodeName
1931
- );
2128
+ const tagName = transformCaseFunc(_readNodeName(currentNode));
1932
2129
 
1933
2130
  /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement
1934
2131
  hook may have been installed after that guard sampled the hook arrays
@@ -1948,35 +2145,9 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
1948
2145
  allowedTags: ALLOWED_TAGS,
1949
2146
  });
1950
2147
 
1951
- /* A hook may have detached the node from the tree — a long-standing
1952
- user pattern (issue #469; draw.io-style foreignObject filtering).
1953
- Per the cached, unclobberable parentNode getter the node is
1954
- genuinely out of the tree, so it can reach neither the serialized
1955
- output nor an IN_PLACE live tree; treat it as removed and stop
1956
- processing it. Without this guard, the unsafe-node / namespace
1957
- checks below would call _forceRemove on a parentless node and hit
1958
- the REPORT-3 fail-closed throw — which exists for nodes DOMPurify
1959
- wants gone but *cannot* detach (clobbered / parentless roots), the
1960
- opposite of a node that is already safely gone. The walk root is
1961
- exempt: a detached IN_PLACE root is legitimate input and must still
1962
- be fully sanitized, and a kill-decision on it must keep hitting the
1963
- REPORT-3 throw. Nodes detached by hooks stay the hook's
1964
- responsibility for placement: they are not recorded in
1965
- DOMPurify.removed, so the post-walk IN_PLACE pass (which iterates
1966
- DOMPurify.removed) does not reach them. But a hook-detached subtree
1967
- can still hold a queued resource-event handler - e.g. an <img onload>
1968
- that began loading when the caller built the live tree - which fires
1969
- in page scope after sanitize returns even though the handler never
1970
- reached the returned tree. That is the audit-5 F1 hazard, and the
1971
- documented node.remove() hook pattern walks straight into it. So on
1972
- the IN_PLACE path we neutralize the detached subtree inline here,
1973
- stripping its non-allow-listed attributes before returning, exactly
1974
- as the post-walk pass does for _forceRemove'd subtrees. */
1975
- if (currentNode !== root && getParentNode(currentNode) === null) {
1976
- if (IN_PLACE) {
1977
- _neutralizeSubtree(currentNode);
1978
- }
1979
-
2148
+ /* The uponSanitizeElement hook may have detached the node, exactly as
2149
+ above (see _handleHookDetachedNode for the full rationale). */
2150
+ if (_handleHookDetachedNode(currentNode, root)) {
1980
2151
  return true;
1981
2152
  }
1982
2153
 
@@ -2021,7 +2192,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2021
2192
  bound and short-circuits to false for any node minted in a different
2022
2193
  realm — letting a foreign-realm element with a forbidden namespace
2023
2194
  slip past the namespace check entirely. */
2024
- const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
2195
+ const nt = _readNodeType(currentNode);
2025
2196
  if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
2026
2197
  _forceRemove(currentNode);
2027
2198
  return true;
@@ -2097,16 +2268,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2097
2268
  other structural-threat checks and stays overridable, consistent with
2098
2269
  the rest of the codebase. PI range markers are already removed by
2099
2270
  _isUnsafeNode. */
2100
- if (SAFE_FOR_XML && lcName === 'patchsrc') {
2101
- return false;
2102
- }
2103
-
2104
- if (
2105
- SAFE_FOR_XML &&
2106
- lcName === 'for' &&
2107
- lcTag !== 'label' &&
2108
- lcTag !== 'output'
2109
- ) {
2271
+ if (_isPatchLinkageAttribute(lcName, lcTag)) {
2110
2272
  return false;
2111
2273
  }
2112
2274
 
@@ -2129,73 +2291,76 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2129
2291
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
2130
2292
  We don't need to check the value; it's always URI safe. */
2131
2293
  if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR, lcName)) {
2132
- // This attribute is safe
2133
- } else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {
2134
- // This attribute is safe
2135
- /* Otherwise, check the name is permitted */
2136
- } else if (!nameIsPermitted) {
2137
- if (
2138
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
2139
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
2140
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
2294
+ return true;
2295
+ }
2296
+
2297
+ /* Allow valid aria-* attributes, the value is always URI safe */
2298
+ if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {
2299
+ return true;
2300
+ }
2301
+
2302
+ /* A name outside the allowlist is acceptable on custom-element terms
2303
+ only. The value checks below are intentionally skipped in that case:
2304
+ if the user supplied a tagNameCheck we also allow derived custom
2305
+ elements using the same test, and attributes passing the configured
2306
+ attributeNameCheck are allowed as custom elements define these at
2307
+ their own discretion. */
2308
+ if (!nameIsPermitted) {
2309
+ return (
2310
+ // Condition a) covers a basically valid custom element tag name whose
2311
+ // tag passes the configured tagNameCheck and whose attribute name
2312
+ // passes the configured attributeNameCheck ...
2141
2313
  (_isBasicCustomElement(lcTag) &&
2142
- ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&
2143
- regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag)) ||
2144
- (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&
2145
- CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag))) &&
2146
- ((CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp &&
2147
- regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName)) ||
2148
- (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function &&
2149
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)))) ||
2150
- // Alternative, second condition checks if it's an `is`-attribute, AND
2151
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
2314
+ _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) &&
2315
+ _matchesNameCheck(
2316
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck,
2317
+ lcName,
2318
+ lcTag
2319
+ )) ||
2320
+ // Condition b) covers an `is` attribute whose value passes the
2321
+ // configured tagNameCheck while customized built-in elements are
2322
+ // allowed.
2152
2323
  (lcName === 'is' &&
2153
2324
  CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&
2154
- ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&
2155
- regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)) ||
2156
- (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&
2157
- CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))))
2158
- ) {
2159
- // 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.
2160
- // 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.
2161
- } else {
2162
- return false;
2163
- }
2164
- /* Check value is safe. First, is attr inert? If so, is safe */
2165
- } else if (URI_SAFE_ATTRIBUTES[lcName]) {
2166
- // This attribute is safe
2167
- /* Check no script, data or unknown possibly unsafe URI
2325
+ _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value))
2326
+ );
2327
+ }
2328
+
2329
+ /* Check value is safe. First, is attr inert? If so, is safe */
2330
+ if (URI_SAFE_ATTRIBUTES[lcName]) {
2331
+ return true;
2332
+ }
2333
+
2334
+ /* Check no script, data or unknown possibly unsafe URI
2168
2335
  unless we know URI values are safe for that attribute */
2169
- } else if (
2170
- regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))
2171
- ) {
2172
- // This attribute is safe
2173
- /* Keep image data URIs alive if src/xlink:href is allowed */
2174
- /* Further prevent gadget XSS for dynamically built script tags */
2175
- } else if (
2336
+ if (regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))) {
2337
+ return true;
2338
+ }
2339
+
2340
+ /* Keep image data URIs alive if src/xlink:href is allowed */
2341
+ /* Further prevent gadget XSS for dynamically built script tags */
2342
+ if (
2176
2343
  (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&
2177
2344
  lcTag !== 'script' &&
2178
2345
  stringIndexOf(value, 'data:') === 0 &&
2179
2346
  DATA_URI_TAGS[lcTag]
2180
2347
  ) {
2181
- // This attribute is safe
2182
- /* Allow unknown protocols: This provides support for links that
2348
+ return true;
2349
+ }
2350
+
2351
+ /* Allow unknown protocols: This provides support for links that
2183
2352
  are handled by protocol handlers which may be unknown ahead of
2184
2353
  time, e.g. fb:, spotify: */
2185
- } else if (
2354
+ if (
2186
2355
  ALLOW_UNKNOWN_PROTOCOLS &&
2187
2356
  !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))
2188
2357
  ) {
2189
- // This attribute is safe
2190
- /* Check for binary attributes */
2191
- } else if (value) {
2192
- return false;
2193
- } else {
2194
- // Binary attributes are safe at this point
2195
- /* Anything else, presume unsafe, do not add it back */
2358
+ return true;
2196
2359
  }
2197
2360
 
2198
- return true;
2361
+ /* Only an empty (binary) value remains safe at this point;
2362
+ anything else is presumed unsafe, do not add it back */
2363
+ return !value;
2199
2364
  };
2200
2365
 
2201
2366
  /* Names the HTML spec reserves from valid-custom-element-name; these must
@@ -2372,7 +2537,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2372
2537
  stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0
2373
2538
  ) {
2374
2539
  // Remove the attribute with this value
2375
- _removeAttribute(name, currentNode);
2540
+ _removeAttribute(name, currentNode, attr);
2376
2541
  // Prefix the value and later re-create the attribute with the sanitized value
2377
2542
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
2378
2543
  }
@@ -2387,13 +2552,13 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2387
2552
  value
2388
2553
  )
2389
2554
  ) {
2390
- _removeAttribute(name, currentNode);
2555
+ _removeAttribute(name, currentNode, attr);
2391
2556
  continue;
2392
2557
  }
2393
2558
 
2394
2559
  /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
2395
2560
  if (lcName === 'attributename' && stringMatch(value, 'href')) {
2396
- _removeAttribute(name, currentNode);
2561
+ _removeAttribute(name, currentNode, attr);
2397
2562
  continue;
2398
2563
  }
2399
2564
 
@@ -2404,7 +2569,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2404
2569
 
2405
2570
  /* Did the hooks approve of the attribute? */
2406
2571
  if (!hookEvent.keepAttr) {
2407
- _removeAttribute(name, currentNode);
2572
+ _removeAttribute(name, currentNode, attr);
2408
2573
  continue;
2409
2574
  }
2410
2575
 
@@ -2413,7 +2578,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2413
2578
  !ALLOW_SELF_CLOSE_IN_ATTR &&
2414
2579
  regExpTest(EXPRESSIONS.SELF_CLOSING_TAG, value)
2415
2580
  ) {
2416
- _removeAttribute(name, currentNode);
2581
+ _removeAttribute(name, currentNode, attr);
2417
2582
  continue;
2418
2583
  }
2419
2584
 
@@ -2424,7 +2589,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2424
2589
 
2425
2590
  /* Is `value` valid for this attribute? */
2426
2591
  if (!_isValidAttribute(lcTag, lcName, value)) {
2427
- _removeAttribute(name, currentNode);
2592
+ _removeAttribute(name, currentNode, attr);
2428
2593
  continue;
2429
2594
  }
2430
2595
 
@@ -2481,10 +2646,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2481
2646
  Walk it explicitly. The nodeType guard avoids reading
2482
2647
  shadowRoot off text / comment / CDATA / PI nodes that the
2483
2648
  iterator also surfaces. */
2484
- const shadowNodeType = getNodeType
2485
- ? getNodeType(shadowNode)
2486
- : shadowNode.nodeType;
2487
- if (shadowNodeType === NODE_TYPE.element) {
2649
+ if (_readNodeType(shadowNode) === NODE_TYPE.element) {
2488
2650
  const innerSr = getShadowRoot(shadowNode);
2489
2651
  if (_isDocumentFragment(innerSr)) {
2490
2652
  _sanitizeAttachedShadowRoots(innerSr);
@@ -2546,7 +2708,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2546
2708
  }
2547
2709
 
2548
2710
  const node = item.node;
2549
- const nodeType = getNodeType ? getNodeType(node) : (node as any).nodeType;
2711
+ const nodeType = _readNodeType(node);
2550
2712
  const isElement = nodeType === NODE_TYPE.element;
2551
2713
 
2552
2714
  /* (pushed last → processed first) Children, snapshotted in reverse so
@@ -2675,9 +2837,7 @@ function createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {
2675
2837
  child named "nodeName" on the form root would otherwise shadow
2676
2838
  the property and let this check skip the root-allowlist
2677
2839
  validation entirely. */
2678
- const nn = getNodeName
2679
- ? getNodeName(dirty as Node)
2680
- : (dirty as Node).nodeName;
2840
+ const nn = _readNodeName(dirty as Node);
2681
2841
  if (typeof nn === 'string') {
2682
2842
  const tagName = transformCaseFunc(nn);
2683
2843
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {